@aeolus-fleet/gateway 0.31.0 → 0.32.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 (346) hide show
  1. package/dist/adapters/fleet/core-version.d.ts +1 -1
  2. package/dist/adapters/fleet/core-version.js +1 -1
  3. package/dist/adapters/fleet/proxy-ships-as-actor.js +5 -1
  4. package/dist/adapters/fleet/proxy-ships-as-actor.js.map +1 -1
  5. package/dist/adapters/fleet/rest-fleet-door.js +15 -6
  6. package/dist/adapters/fleet/rest-fleet-door.js.map +1 -1
  7. package/dist/adapters/http/mcp-endpoint.js +1 -1
  8. package/dist/adapters/http/mcp-endpoint.js.map +1 -1
  9. package/dist/adapters/http/person-tools.js +1 -1
  10. package/dist/adapters/http/person-tools.js.map +1 -1
  11. package/dist/adapters/pagasae/email-channel.js +4 -2
  12. package/dist/adapters/pagasae/email-channel.js.map +1 -1
  13. package/dist/adapters/prisma/generated/commonInputTypes.d.ts +50 -50
  14. package/dist/adapters/prisma/generated/internal/class.js +4 -4
  15. package/dist/adapters/prisma/generated/internal/class.js.map +1 -1
  16. package/dist/adapters/prisma/generated/internal/prismaNamespace.d.ts +2 -0
  17. package/dist/adapters/prisma/generated/internal/prismaNamespace.js +2 -0
  18. package/dist/adapters/prisma/generated/internal/prismaNamespace.js.map +1 -1
  19. package/dist/adapters/prisma/generated/internal/prismaNamespaceBrowser.d.ts +2 -0
  20. package/dist/adapters/prisma/generated/internal/prismaNamespaceBrowser.js +2 -0
  21. package/dist/adapters/prisma/generated/internal/prismaNamespaceBrowser.js.map +1 -1
  22. package/dist/adapters/prisma/generated/models/A2aPush.d.ts +0 -7
  23. package/dist/adapters/prisma/generated/models/Party.d.ts +70 -1
  24. package/dist/adapters/prisma/scope-requirements.d.ts +10 -0
  25. package/dist/adapters/prisma/scope-requirements.js +37 -0
  26. package/dist/adapters/prisma/scope-requirements.js.map +1 -0
  27. package/dist/adapters/trpc/router.d.ts +91 -8
  28. package/dist/adapters/trpc/router.js +98 -11
  29. package/dist/adapters/trpc/router.js.map +1 -1
  30. package/dist/app.js +34 -9
  31. package/dist/app.js.map +1 -1
  32. package/dist/core/a2a-out/agent-event.d.ts +1 -1
  33. package/dist/core/a2a-out/agent-event.js +2 -2
  34. package/dist/core/a2a-out/agent-event.js.map +1 -1
  35. package/dist/core/a2a-out/agent-statement.d.ts +2 -1
  36. package/dist/core/a2a-out/agent-statement.js +5 -2
  37. package/dist/core/a2a-out/agent-statement.js.map +1 -1
  38. package/dist/core/a2a-out/hand-a2a-message.d.ts +7 -2
  39. package/dist/core/a2a-out/hand-a2a-message.js +15 -1
  40. package/dist/core/a2a-out/hand-a2a-message.js.map +1 -1
  41. package/dist/core/a2a-out/read-agent-statement.d.ts +1 -0
  42. package/dist/core/a2a-out/read-agent-statement.js +1 -1
  43. package/dist/core/a2a-out/read-agent-statement.js.map +1 -1
  44. package/dist/core/a2a-out/state-a2a-agent.d.ts +3 -2
  45. package/dist/core/a2a-out/state-a2a-agent.js +3 -2
  46. package/dist/core/a2a-out/state-a2a-agent.js.map +1 -1
  47. package/dist/core/account-sign-in/account-in-view.d.ts +10 -1
  48. package/dist/core/account-sign-in/account-in-view.js +17 -4
  49. package/dist/core/account-sign-in/account-in-view.js.map +1 -1
  50. package/dist/core/connection/ports.d.ts +8 -0
  51. package/dist/core/mcp-out/hand-call.d.ts +6 -2
  52. package/dist/core/mcp-out/hand-call.js +14 -1
  53. package/dist/core/mcp-out/hand-call.js.map +1 -1
  54. package/dist/core/mcp-out/state-party.d.ts +3 -2
  55. package/dist/core/mcp-out/state-party.js +2 -2
  56. package/dist/core/mcp-out/state-party.js.map +1 -1
  57. package/dist/core/mcp-out/statement.d.ts +16 -0
  58. package/dist/core/mcp-out/statement.js +10 -3
  59. package/dist/core/mcp-out/statement.js.map +1 -1
  60. package/dist/core/operator/ports.d.ts +4 -4
  61. package/dist/core/parties/add-a2a-agent.js +1 -1
  62. package/dist/core/parties/add-a2a-agent.js.map +1 -1
  63. package/dist/core/parties/check-approving.d.ts +36 -0
  64. package/dist/core/parties/check-approving.js +48 -0
  65. package/dist/core/parties/check-approving.js.map +1 -0
  66. package/dist/core/parties/check-required-scopes.d.ts +34 -0
  67. package/dist/core/parties/check-required-scopes.js +27 -0
  68. package/dist/core/parties/check-required-scopes.js.map +1 -0
  69. package/dist/core/parties/ports.d.ts +21 -0
  70. package/dist/core/parties/read-listed-scopes.d.ts +17 -0
  71. package/dist/core/parties/read-listed-scopes.js +23 -0
  72. package/dist/core/parties/read-listed-scopes.js.map +1 -0
  73. package/dist/core/parties/read-scope-requirements.d.ts +18 -0
  74. package/dist/core/parties/read-scope-requirements.js +17 -0
  75. package/dist/core/parties/read-scope-requirements.js.map +1 -0
  76. package/dist/core/parties/scope-requirements.d.ts +34 -0
  77. package/dist/core/parties/scope-requirements.js +37 -0
  78. package/dist/core/parties/scope-requirements.js.map +1 -0
  79. package/dist/core/parties/set-scope-requirements.d.ts +45 -0
  80. package/dist/core/parties/set-scope-requirements.js +48 -0
  81. package/dist/core/parties/set-scope-requirements.js.map +1 -0
  82. package/dist/core/parties/switch-tools.d.ts +39 -0
  83. package/dist/core/parties/switch-tools.js +38 -0
  84. package/dist/core/parties/switch-tools.js.map +1 -0
  85. package/dist/core/parties/tool-switches.d.ts +4 -2
  86. package/dist/core/parties/tool-switches.js +2 -1
  87. package/dist/core/parties/tool-switches.js.map +1 -1
  88. package/dist/core/people/ports.d.ts +4 -2
  89. package/dist/core/people/wake-person.d.ts +22 -10
  90. package/dist/core/people/wake-person.js +88 -20
  91. package/dist/core/people/wake-person.js.map +1 -1
  92. package/dist/core/people/web-push-channel.js +1 -1
  93. package/dist/core/people/web-push-channel.js.map +1 -1
  94. package/dist/core/shared/errors.d.ts +1 -1
  95. package/dist/core/shared/errors.js.map +1 -1
  96. package/package.json +3 -3
  97. package/src/adapters/prisma/migrations/20261025140000_scope_requirements/migration.sql +3 -0
  98. package/src/adapters/prisma/schema.prisma +69 -65
  99. package/web/.next/BUILD_ID +1 -1
  100. package/web/.next/app-path-routes-manifest.json +1 -0
  101. package/web/.next/build-manifest.json +15 -3
  102. package/web/.next/diagnostics/route-bundle-stats.json +113 -77
  103. package/web/.next/fallback-build-manifest.json +3 -3
  104. package/web/.next/prerender-manifest.json +3 -3
  105. package/web/.next/routes-manifest.json +6 -0
  106. package/web/.next/server/app/(console)/gateway-off/page/app-paths-manifest.json +3 -0
  107. package/web/.next/server/app/(console)/gateway-off/page/build-manifest.json +23 -0
  108. package/web/.next/server/app/(console)/gateway-off/page/next-font-manifest.json +11 -0
  109. package/web/.next/server/app/(console)/gateway-off/page/react-loadable-manifest.json +1 -0
  110. package/web/.next/server/app/(console)/gateway-off/page/server-reference-manifest.json +15 -0
  111. package/web/.next/server/app/(console)/gateway-off/page.js +19 -0
  112. package/web/.next/server/app/(console)/gateway-off/page.js.map +5 -0
  113. package/web/.next/server/app/(console)/gateway-off/page.js.nft.json +1 -0
  114. package/web/.next/server/app/(console)/gateway-off/page_client-reference-manifest.js +3 -0
  115. package/web/.next/server/app/(console)/meetings/[meetingId]/page/server-reference-manifest.json +3 -3
  116. package/web/.next/server/app/(console)/meetings/[meetingId]/page.js.nft.json +1 -1
  117. package/web/.next/server/app/(console)/meetings/[meetingId]/page_client-reference-manifest.js +1 -1
  118. package/web/.next/server/app/(console)/outside-parties/[name]/change/page/server-reference-manifest.json +17 -7
  119. package/web/.next/server/app/(console)/outside-parties/[name]/change/page.js +4 -4
  120. package/web/.next/server/app/(console)/outside-parties/[name]/change/page.js.nft.json +1 -1
  121. package/web/.next/server/app/(console)/outside-parties/[name]/change/page_client-reference-manifest.js +1 -1
  122. package/web/.next/server/app/(console)/outside-parties/[name]/page/server-reference-manifest.json +15 -5
  123. package/web/.next/server/app/(console)/outside-parties/[name]/page.js +4 -4
  124. package/web/.next/server/app/(console)/outside-parties/[name]/page.js.nft.json +1 -1
  125. package/web/.next/server/app/(console)/outside-parties/[name]/page_client-reference-manifest.js +1 -1
  126. package/web/.next/server/app/(console)/outside-parties/[name]/retire/page/server-reference-manifest.json +17 -7
  127. package/web/.next/server/app/(console)/outside-parties/[name]/retire/page.js +4 -4
  128. package/web/.next/server/app/(console)/outside-parties/[name]/retire/page.js.nft.json +1 -1
  129. package/web/.next/server/app/(console)/outside-parties/[name]/retire/page_client-reference-manifest.js +1 -1
  130. package/web/.next/server/app/(console)/outside-parties/add/page/server-reference-manifest.json +17 -7
  131. package/web/.next/server/app/(console)/outside-parties/add/page.js +3 -4
  132. package/web/.next/server/app/(console)/outside-parties/add/page.js.nft.json +1 -1
  133. package/web/.next/server/app/(console)/outside-parties/add/page_client-reference-manifest.js +1 -1
  134. package/web/.next/server/app/(console)/outside-parties/add-a2a-agent/page/server-reference-manifest.json +2 -2
  135. package/web/.next/server/app/(console)/outside-parties/add-a2a-agent/page.js.nft.json +1 -1
  136. package/web/.next/server/app/(console)/outside-parties/add-a2a-agent/page_client-reference-manifest.js +1 -1
  137. package/web/.next/server/app/(console)/outside-parties/add-a2a-client/page/server-reference-manifest.json +2 -2
  138. package/web/.next/server/app/(console)/outside-parties/add-a2a-client/page.js.nft.json +1 -1
  139. package/web/.next/server/app/(console)/outside-parties/add-a2a-client/page_client-reference-manifest.js +1 -1
  140. package/web/.next/server/app/(console)/outside-parties/page/server-reference-manifest.json +2 -2
  141. package/web/.next/server/app/(console)/outside-parties/page.js.nft.json +1 -1
  142. package/web/.next/server/app/(console)/outside-parties/page_client-reference-manifest.js +1 -1
  143. package/web/.next/server/app/(console)/overview/changes/route.js.nft.json +1 -1
  144. package/web/.next/server/app/(console)/overview/focus/route.js.nft.json +1 -1
  145. package/web/.next/server/app/(console)/overview/page/server-reference-manifest.json +7 -7
  146. package/web/.next/server/app/(console)/overview/page.js.nft.json +1 -1
  147. package/web/.next/server/app/(console)/overview/page_client-reference-manifest.js +1 -1
  148. package/web/.next/server/app/(console)/overview/requests/[requestId]/page/server-reference-manifest.json +2 -2
  149. package/web/.next/server/app/(console)/overview/requests/[requestId]/page.js.nft.json +1 -1
  150. package/web/.next/server/app/(console)/overview/requests/[requestId]/page_client-reference-manifest.js +1 -1
  151. package/web/.next/server/app/(console)/parties/page/server-reference-manifest.json +7 -7
  152. package/web/.next/server/app/(console)/parties/page.js.nft.json +1 -1
  153. package/web/.next/server/app/(console)/parties/page_client-reference-manifest.js +1 -1
  154. package/web/.next/server/app/(console)/sign-in/failed/page/server-reference-manifest.json +1 -1
  155. package/web/.next/server/app/(console)/sign-in/failed/page.js.nft.json +1 -1
  156. package/web/.next/server/app/(console)/sign-in/failed/page_client-reference-manifest.js +1 -1
  157. package/web/.next/server/app/_global-error.html +1 -1
  158. package/web/.next/server/app/_global-error.rsc +1 -1
  159. package/web/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  160. package/web/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  161. package/web/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  162. package/web/.next/server/app/_not-found/page/server-reference-manifest.json +1 -1
  163. package/web/.next/server/app/_not-found/page.js.nft.json +1 -1
  164. package/web/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  165. package/web/.next/server/app/authorize/failed/page/server-reference-manifest.json +1 -1
  166. package/web/.next/server/app/authorize/failed/page.js.nft.json +1 -1
  167. package/web/.next/server/app/authorize/failed/page_client-reference-manifest.js +1 -1
  168. package/web/.next/server/app/authorize/pick/page/server-reference-manifest.json +1 -1
  169. package/web/.next/server/app/authorize/pick/page.js.nft.json +1 -1
  170. package/web/.next/server/app/authorize/pick/page_client-reference-manifest.js +1 -1
  171. package/web/.next/server/app/authorize/waiting/approval/page/server-reference-manifest.json +1 -1
  172. package/web/.next/server/app/authorize/waiting/approval/page.js.nft.json +1 -1
  173. package/web/.next/server/app/authorize/waiting/approval/page_client-reference-manifest.js +1 -1
  174. package/web/.next/server/app-paths-manifest.json +1 -0
  175. package/web/.next/server/chunks/[root-of-the-server]__0ykc8bq_c06a1._.js +1 -1
  176. package/web/.next/server/chunks/[root-of-the-server]__0ykc8bq_c06a1._.js.map +1 -1
  177. package/web/.next/server/chunks/ssr/0vkm_server_app_(console)_outside-parties_[name]_change_page_actions_04td11fxohsfm.js +1 -1
  178. package/web/.next/server/chunks/ssr/0vkm_server_app_(console)_outside-parties_[name]_change_page_actions_04td11fxohsfm.js.map +1 -1
  179. package/web/.next/server/chunks/ssr/0vkm_server_app_(console)_outside-parties_[name]_page_actions_0u-45itza1ls7.js +1 -1
  180. package/web/.next/server/chunks/ssr/0vkm_server_app_(console)_outside-parties_[name]_page_actions_0u-45itza1ls7.js.map +1 -1
  181. package/web/.next/server/chunks/ssr/0vkm_server_app_(console)_outside-parties_[name]_retire_page_actions_0s7ps6i0ts7v5.js +1 -1
  182. package/web/.next/server/chunks/ssr/0vkm_server_app_(console)_outside-parties_[name]_retire_page_actions_0s7ps6i0ts7v5.js.map +1 -1
  183. package/web/.next/server/chunks/ssr/0vkm_server_app_(console)_outside-parties_add-a2a-client_page_actions_0d_wgiu94c32e.js +1 -1
  184. package/web/.next/server/chunks/ssr/0vkm_server_app_(console)_outside-parties_add-a2a-client_page_actions_0d_wgiu94c32e.js.map +1 -1
  185. package/web/.next/server/chunks/ssr/0vkm_server_app_(console)_outside-parties_add_page_actions_0yfz_dfn-8uo7.js +1 -1
  186. package/web/.next/server/chunks/ssr/0vkm_server_app_(console)_outside-parties_add_page_actions_0yfz_dfn-8uo7.js.map +1 -1
  187. package/web/.next/server/chunks/ssr/0vkm_server_app_(console)_overview_requests_[requestId]_page_actions_0uki9j3mtuz9e.js +1 -1
  188. package/web/.next/server/chunks/ssr/0vkm_server_app_(console)_overview_requests_[requestId]_page_actions_0uki9j3mtuz9e.js.map +1 -1
  189. package/web/.next/server/chunks/ssr/[root-of-the-server]__0-og0bl8lr2xq._.js +1 -1
  190. package/web/.next/server/chunks/ssr/[root-of-the-server]__0-og0bl8lr2xq._.js.map +1 -1
  191. package/web/.next/server/chunks/ssr/[root-of-the-server]__00q22dte1g2ww._.js +3 -0
  192. package/web/.next/server/chunks/ssr/[root-of-the-server]__00q22dte1g2ww._.js.map +1 -0
  193. package/web/.next/server/chunks/ssr/[root-of-the-server]__0k3g0p3t9t0c-._.js +1 -1
  194. package/web/.next/server/chunks/ssr/[root-of-the-server]__0k3g0p3t9t0c-._.js.map +1 -1
  195. package/web/.next/server/chunks/ssr/[root-of-the-server]__0n2us07jk-78w._.js +1 -1
  196. package/web/.next/server/chunks/ssr/[root-of-the-server]__0rr5u24i9tjyc._.js +1 -1
  197. package/web/.next/server/chunks/ssr/[root-of-the-server]__1-c9wugbbwsp3._.js +4 -0
  198. package/web/.next/server/chunks/ssr/[root-of-the-server]__1-c9wugbbwsp3._.js.map +1 -0
  199. package/web/.next/server/chunks/ssr/[root-of-the-server]__18-8taiduk1jn._.js +1 -1
  200. package/web/.next/server/chunks/ssr/[root-of-the-server]__18-8taiduk1jn._.js.map +1 -1
  201. package/web/.next/server/chunks/ssr/{[root-of-the-server]__11w36a4le04vy._.js → [root-of-the-server]__1dc6okf5os70a._.js} +2 -2
  202. package/web/.next/server/chunks/ssr/[root-of-the-server]__1dc6okf5os70a._.js.map +1 -0
  203. package/web/.next/server/chunks/ssr/[root-of-the-server]__1dtyycvqa6uht._.js +1 -1
  204. package/web/.next/server/chunks/ssr/_0-lfpqqlgfhzj._.js.map +1 -1
  205. package/web/.next/server/chunks/ssr/_00dg5cvqofspn._.js +3 -0
  206. package/web/.next/server/chunks/ssr/_00dg5cvqofspn._.js.map +1 -0
  207. package/web/.next/server/chunks/ssr/_00hfzlqn1og18._.js +1 -1
  208. package/web/.next/server/chunks/ssr/_00hfzlqn1og18._.js.map +1 -1
  209. package/web/.next/server/chunks/ssr/_03lk54yp-yhw3._.js +2 -2
  210. package/web/.next/server/chunks/ssr/_03lk54yp-yhw3._.js.map +1 -1
  211. package/web/.next/server/chunks/ssr/_0_kakdt7lb6z-._.js +3 -0
  212. package/web/.next/server/chunks/ssr/_0_kakdt7lb6z-._.js.map +1 -0
  213. package/web/.next/server/chunks/ssr/_0bhvvyz0q_0ja._.js +1 -1
  214. package/web/.next/server/chunks/ssr/_0ka_9elusb800._.js +4 -0
  215. package/web/.next/server/chunks/ssr/_0ka_9elusb800._.js.map +1 -0
  216. package/web/.next/server/chunks/ssr/_0pyd1_y7w8ngp._.js +1 -1
  217. package/web/.next/server/chunks/ssr/_0pyd1_y7w8ngp._.js.map +1 -1
  218. package/web/.next/server/chunks/ssr/_0w2ptjht34s6t._.js +3 -0
  219. package/web/.next/server/chunks/ssr/_0w2ptjht34s6t._.js.map +1 -0
  220. package/web/.next/server/chunks/ssr/_0xickgbbju_9-._.js +1 -1
  221. package/web/.next/server/chunks/ssr/_0xickgbbju_9-._.js.map +1 -1
  222. package/web/.next/server/chunks/ssr/_12fsn_33ga-n0._.js +1 -1
  223. package/web/.next/server/chunks/ssr/_1_wav28san6dm._.js +1 -1
  224. package/web/.next/server/chunks/ssr/_1pjtire7rqla0._.js +1 -1
  225. package/web/.next/server/chunks/ssr/_1pjtire7rqla0._.js.map +1 -1
  226. package/web/.next/server/chunks/ssr/_1qbsmlji34yph._.js +1 -1
  227. package/web/.next/server/chunks/ssr/_1qbsmlji34yph._.js.map +1 -1
  228. package/web/.next/server/chunks/ssr/_1uuy6gkkhq6bx._.js +3 -0
  229. package/web/.next/server/chunks/ssr/_1uuy6gkkhq6bx._.js.map +1 -0
  230. package/web/.next/server/chunks/ssr/_1y1ovmdhl9_ml._.js +3 -0
  231. package/web/.next/server/chunks/ssr/_1y1ovmdhl9_ml._.js.map +1 -0
  232. package/web/.next/server/chunks/ssr/node_modules_07sxnbglqc5q9._.js +3 -0
  233. package/web/.next/server/chunks/ssr/node_modules_07sxnbglqc5q9._.js.map +1 -0
  234. package/web/.next/server/chunks/ssr/node_modules_0_cxkn6vujxay._.js +3 -0
  235. package/web/.next/server/chunks/ssr/node_modules_0_cxkn6vujxay._.js.map +1 -0
  236. package/web/.next/server/chunks/ssr/node_modules_0qlo87g8tugr4._.js +3 -0
  237. package/web/.next/server/chunks/ssr/node_modules_0qlo87g8tugr4._.js.map +1 -0
  238. package/web/.next/server/chunks/ssr/node_modules_15ceu3jhtifcw._.js +3 -0
  239. package/web/.next/server/chunks/ssr/node_modules_15ceu3jhtifcw._.js.map +1 -0
  240. package/web/.next/server/chunks/ssr/node_modules_@aeolus-fleet_common_dist_header_1jvz31plyg2f-._.js +1 -1
  241. package/web/.next/server/chunks/ssr/node_modules_@aeolus-fleet_common_dist_header_1jvz31plyg2f-._.js.map +1 -1
  242. package/web/.next/server/chunks/ssr/node_modules_@base-ui_react_utils_FloatingPortalLite_mjs_1uzc1ezeugtex._.js +3 -0
  243. package/web/.next/server/chunks/ssr/node_modules_@base-ui_react_utils_FloatingPortalLite_mjs_1uzc1ezeugtex._.js.map +1 -0
  244. package/web/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_1s46s8vlfx01v.js +3 -0
  245. package/web/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_1s46s8vlfx01v.js.map +1 -0
  246. package/web/.next/server/chunks/ssr/web_0v-7sowo0hupw._.js +1 -1
  247. package/web/.next/server/chunks/ssr/web_0wys4l6za8umr._.js +1 -1
  248. package/web/.next/server/chunks/ssr/web_0wys4l6za8umr._.js.map +1 -1
  249. package/web/.next/server/chunks/ssr/web_1wcpaty_bz55q._.js +3 -0
  250. package/web/.next/server/chunks/ssr/web_1wcpaty_bz55q._.js.map +1 -0
  251. package/web/.next/server/chunks/ssr/web__next-internal_server_app_(console)_overview_page_actions_18on1ziyg1nzy.js +1 -1
  252. package/web/.next/server/chunks/ssr/web__next-internal_server_app_(console)_overview_page_actions_18on1ziyg1nzy.js.map +1 -1
  253. package/web/.next/server/chunks/ssr/{web_features_0ahlkugj7fu3n._.js → web_features_0xbnkk4hfgr9v._.js} +2 -2
  254. package/web/.next/server/chunks/ssr/{web_features_0ahlkugj7fu3n._.js.map → web_features_0xbnkk4hfgr9v._.js.map} +1 -1
  255. package/web/.next/server/chunks/ssr/web_features_10xz3ojtvfi7h._.js +3 -0
  256. package/web/.next/server/chunks/ssr/web_features_10xz3ojtvfi7h._.js.map +1 -0
  257. package/web/.next/server/chunks/ssr/web_features_add-a2a-agent_ui_a2a-agent-form_tsx_0z8t1aalwzyl7._.js +1 -1
  258. package/web/.next/server/chunks/ssr/web_features_add-a2a-agent_ui_a2a-agent-form_tsx_0z8t1aalwzyl7._.js.map +1 -1
  259. package/web/.next/server/chunks/ssr/web_features_add-a2a-client_ui_a2a-client-form_tsx_1anv88g385nwe._.js +1 -1
  260. package/web/.next/server/chunks/ssr/web_features_add-a2a-client_ui_a2a-client-form_tsx_1anv88g385nwe._.js.map +1 -1
  261. package/web/.next/server/chunks/ssr/web_features_add-server_ui_add-server_tsx_1jnmar5xju49k._.js +1 -1
  262. package/web/.next/server/chunks/ssr/web_features_add-server_ui_add-server_tsx_1jnmar5xju49k._.js.map +1 -1
  263. package/web/.next/server/chunks/ssr/web_features_forms_1u0akr22eh_x_._.js +3 -0
  264. package/web/.next/server/chunks/ssr/web_features_forms_1u0akr22eh_x_._.js.map +1 -0
  265. package/web/.next/server/chunks/ssr/web_features_frame_0pe8cwpxe1egb._.js +1 -1
  266. package/web/.next/server/chunks/ssr/web_features_frame_ui_gateway-header_tsx_0e9tekx4jf7ng._.js +1 -1
  267. package/web/.next/server/chunks/ssr/web_features_frame_ui_gateway-header_tsx_0e9tekx4jf7ng._.js.map +1 -1
  268. package/web/.next/server/chunks/ssr/web_features_meeting_state_meeting-controls_tsx_12g4kzk2mbvvz._.js +1 -1
  269. package/web/.next/server/chunks/ssr/web_features_meeting_state_meeting-controls_tsx_12g4kzk2mbvvz._.js.map +1 -1
  270. package/web/.next/server/chunks/ssr/web_features_outside-parties_ui_switch-card_tsx_1_xnu9bm4tc-_._.js +1 -1
  271. package/web/.next/server/chunks/ssr/web_features_outside-parties_ui_switch-card_tsx_1_xnu9bm4tc-_._.js.map +1 -1
  272. package/web/.next/server/chunks/ssr/web_features_outside-party_0_9c27knfvw7u._.js +3 -0
  273. package/web/.next/server/chunks/ssr/web_features_outside-party_0_9c27knfvw7u._.js.map +1 -0
  274. package/web/.next/server/chunks/ssr/web_features_outside-party_actions_ts_102ar5pdowf8s._.js +1 -1
  275. package/web/.next/server/chunks/ssr/web_features_outside-party_actions_ts_102ar5pdowf8s._.js.map +1 -1
  276. package/web/.next/server/chunks/ssr/web_features_overview_0udx5lm8igils._.js +3 -0
  277. package/web/.next/server/chunks/ssr/{web_features_overview_16dyz2ngvs14b._.js.map → web_features_overview_0udx5lm8igils._.js.map} +1 -1
  278. package/web/.next/server/chunks/ssr/web_features_overview_hooks_overview-actions_ts_0-wrat07d1y5g._.js +1 -1
  279. package/web/.next/server/chunks/ssr/web_features_overview_state_1wuk95dw2_whp._.js +1 -1
  280. package/web/.next/server/chunks/ssr/web_features_overview_state_1wuk95dw2_whp._.js.map +1 -1
  281. package/web/.next/server/chunks/ssr/web_features_overview_state_decision-panel_tsx_0kpd26ggtr6h_._.js +1 -1
  282. package/web/.next/server/chunks/ssr/web_features_overview_state_decision-panel_tsx_0kpd26ggtr6h_._.js.map +1 -1
  283. package/web/.next/server/chunks/ssr/{web_features_overview_ui_action-button_tsx_14-5f45xbzbi6._.js → web_features_overview_ui_10mb24kjiffea._.js} +2 -2
  284. package/web/.next/server/chunks/ssr/{web_features_overview_ui_action-button_tsx_14-5f45xbzbi6._.js.map → web_features_overview_ui_10mb24kjiffea._.js.map} +1 -1
  285. package/web/.next/server/chunks/ssr/web_features_parties_actions_ts_0r-tbfsig2ty-._.js +1 -1
  286. package/web/.next/server/middleware-build-manifest.js +15 -3
  287. package/web/.next/server/next-font-manifest.js +1 -1
  288. package/web/.next/server/next-font-manifest.json +4 -0
  289. package/web/.next/server/pages/500.html +1 -1
  290. package/web/.next/server/preview-props.json +3 -3
  291. package/web/.next/server/server-reference-manifest.js +1 -1
  292. package/web/.next/server/server-reference-manifest.json +55 -29
  293. package/web/.next/static/chunks/0coxy5zad812a.js +1 -0
  294. package/web/.next/static/chunks/{2hsi-sahla2aj.js → 0u_4xjk1j74g3.js} +1 -1
  295. package/web/.next/static/chunks/0v9r_hyyubykq.js +1 -0
  296. package/web/.next/static/chunks/0zesq1ng-v3s6.js +1 -0
  297. package/web/.next/static/chunks/10wzmy096av_5.css +3 -0
  298. package/web/.next/static/chunks/{1juj2_tl8d16x.js → 12c3qjvto3m0f.js} +1 -1
  299. package/web/.next/static/chunks/1ahn4kx4ld-rc.js +1 -0
  300. package/web/.next/static/chunks/{21s2_ccrw90ok.js → 1xrn7oqwd48vi.js} +1 -1
  301. package/web/.next/static/chunks/{3o8h4o3utbvgc.js → 20n2z_lok8v0f.js} +1 -1
  302. package/web/.next/static/chunks/2cd4e71s711ad.js +1 -0
  303. package/web/.next/static/chunks/{1pafc2gfswboo.js → 2ew9kpu2kohk4.js} +1 -1
  304. package/web/.next/static/chunks/2i3ydqqupow_x.js +1 -0
  305. package/web/.next/static/chunks/2riya89_i0je8.js +1 -0
  306. package/web/.next/static/chunks/3_pwm8b3mf4mf.js +1 -0
  307. package/web/.next/static/chunks/{2x00o45pdbkok.js → 3x_8doukmdfpu.js} +1 -1
  308. package/web/.next/trace +1 -1
  309. package/web/.next/trace-build +1 -1
  310. package/web/.next/types/routes.d.ts +2 -1
  311. package/web/.next/types/validator.ts +17 -0
  312. package/dist/core/parties/switch-tool.d.ts +0 -29
  313. package/dist/core/parties/switch-tool.js +0 -33
  314. package/dist/core/parties/switch-tool.js.map +0 -1
  315. package/web/.next/server/chunks/ssr/[root-of-the-server]__0m57jyae0dn_7._.js +0 -3
  316. package/web/.next/server/chunks/ssr/[root-of-the-server]__0m57jyae0dn_7._.js.map +0 -1
  317. package/web/.next/server/chunks/ssr/[root-of-the-server]__11w36a4le04vy._.js.map +0 -1
  318. package/web/.next/server/chunks/ssr/[root-of-the-server]__1k25lo5ka4mgd._.js +0 -3
  319. package/web/.next/server/chunks/ssr/[root-of-the-server]__1k25lo5ka4mgd._.js.map +0 -1
  320. package/web/.next/server/chunks/ssr/[root-of-the-server]__1yjb00o7x58xv._.js +0 -3
  321. package/web/.next/server/chunks/ssr/[root-of-the-server]__1yjb00o7x58xv._.js.map +0 -1
  322. package/web/.next/server/chunks/ssr/node_modules_0cyjln1rocvt5._.js +0 -3
  323. package/web/.next/server/chunks/ssr/node_modules_0cyjln1rocvt5._.js.map +0 -1
  324. package/web/.next/server/chunks/ssr/node_modules_1ins1z8o_qrka._.js +0 -3
  325. package/web/.next/server/chunks/ssr/node_modules_1ins1z8o_qrka._.js.map +0 -1
  326. package/web/.next/server/chunks/ssr/web_features_0i_kwiszuiqcp._.js +0 -3
  327. package/web/.next/server/chunks/ssr/web_features_0i_kwiszuiqcp._.js.map +0 -1
  328. package/web/.next/server/chunks/ssr/web_features_1--8ungjj--ht._.js +0 -3
  329. package/web/.next/server/chunks/ssr/web_features_1--8ungjj--ht._.js.map +0 -1
  330. package/web/.next/server/chunks/ssr/web_features_1qq_ruz59ldc9._.js +0 -3
  331. package/web/.next/server/chunks/ssr/web_features_1qq_ruz59ldc9._.js.map +0 -1
  332. package/web/.next/server/chunks/ssr/web_features_forms_form-state_ts_2142hiopykfk1._.js +0 -3
  333. package/web/.next/server/chunks/ssr/web_features_forms_form-state_ts_2142hiopykfk1._.js.map +0 -1
  334. package/web/.next/server/chunks/ssr/web_features_outside-party_ui_20x5u9bhxeehi._.js +0 -3
  335. package/web/.next/server/chunks/ssr/web_features_outside-party_ui_20x5u9bhxeehi._.js.map +0 -1
  336. package/web/.next/server/chunks/ssr/web_features_overview_16dyz2ngvs14b._.js +0 -3
  337. package/web/.next/static/chunks/183mifyxtyab5.css +0 -3
  338. package/web/.next/static/chunks/1bnlc-p1_cm01.js +0 -1
  339. package/web/.next/static/chunks/1ca21kggixrjz.js +0 -1
  340. package/web/.next/static/chunks/2-t4g6oq6tjkg.js +0 -1
  341. package/web/.next/static/chunks/2l27ty2dy2pb4.js +0 -1
  342. package/web/.next/static/chunks/2n2qsek2y94y5.js +0 -1
  343. package/web/.next/static/chunks/3tss77vu57zju.js +0 -1
  344. /package/web/.next/static/{3whgLnRJ9iJe_25h6KGzQ → wnr2MrrQvcto8MOm16D8r}/_buildManifest.js +0 -0
  345. /package/web/.next/static/{3whgLnRJ9iJe_25h6KGzQ → wnr2MrrQvcto8MOm16D8r}/_clientMiddlewareManifest.js +0 -0
  346. /package/web/.next/static/{3whgLnRJ9iJe_25h6KGzQ → wnr2MrrQvcto8MOm16D8r}/_ssgManifest.js +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../node_modules/%40aeolus-fleet/common/src/ids/index.ts","../../../../../node_modules/%40aeolus-fleet/common/src/schemas/account-token.ts","../../../../../node_modules/%40trpc/client/dist/objectSpread2-weooBxVk.mjs","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/createProxy.ts","../../../../../node_modules/%40trpc/server/src/observable/observable.ts","../../../../../node_modules/%40trpc/server/src/observable/operators.ts","../../../../../node_modules/%40trpc/client/src/getFetch.ts","../../../../../node_modules/%40trpc/client/src/links/internals/createChain.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/error/formatter.ts","../../../../../node_modules/%40trpc/client/src/links/loggerLink.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/http/parseConnectionParams.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/utils.ts","../../../../../node_modules/%40trpc/client/src/links/wsLink/wsClient/encoder.ts","../../../../../node_modules/%40trpc/client/src/TRPCClientError.ts","../../../../../node_modules/%40trpc/client/src/links/internals/contentTypes.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/error/TRPCError.ts","../../../../../node_modules/%40trpc/client/src/internals/dataLoader.ts","../../../../../node_modules/%40trpc/client/src/internals/transformer.ts","../../../../../node_modules/%40trpc/client/src/internals/TRPCUntypedClient.ts","../../../../../node_modules/%40trpc/client/src/links/wsLink/wsClient/options.ts","../../../../../node_modules/%40trpc/client/src/links/httpLink.ts","../../../../../node_modules/%40trpc/client/src/internals/signals.ts","../../../../../node_modules/%40trpc/client/src/links/splitLink.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/http/contentType.ts","../../../../../node_modules/%40trpc/client/src/links/internals/urlWithConnectionParams.ts","../../../../../node_modules/%40trpc/client/src/links/wsLink/wsClient/utils.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/transformer.ts","../../../../../node_modules/%40trpc/client/src/links/internals/httpUtils.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/http/getHTTPStatusCode.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/rpc/codes.ts","../../../../../node_modules/%40trpc/client/src/createTRPCUntypedClient.ts","../../../../../node_modules/%40trpc/client/src/createTRPCClient.ts","../../../../../node_modules/%40trpc/client/src/links/wsLink/wsClient/requestManager.ts","../../../../../node_modules/%40trpc/client/src/links/httpBatchLink.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/router.ts","../../../../../node_modules/%40trpc/server/src/observable/behaviorSubject.ts","../../../../../node_modules/%40trpc/client/src/links/httpBatchStreamLink.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/error/getErrorShape.ts","../../../../../node_modules/%40trpc/client/src/links/wsLink/wsClient/wsConnection.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/http/abortError.ts","../../../../../node_modules/%40trpc/server/src/vendor/is-plain-object.ts","../../../../../node_modules/%40trpc/client/src/internals/inputWithTrackedEventId.ts","../../../../../node_modules/%40trpc/server/src/vendor/unpromise/unpromise.ts","../../../../../node_modules/%40trpc/client/src/links/httpSubscriptionLink.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/stream/tracked.ts","../../../../../node_modules/%40trpc/client/src/links/wsLink/wsClient/wsClient.ts","../../../../../node_modules/%40trpc/client/src/links/retryLink.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/stream/utils/disposable.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/stream/utils/timerResource.ts","../../../../../node_modules/%40trpc/client/src/links/wsLink/createWsClient.ts","../../../../../node_modules/%40trpc/client/src/links/wsLink/wsLink.ts","../../../../../node_modules/%40trpc/client/src/links/localLink.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/stream/utils/asyncIterable.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/stream/utils/createDeferred.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/stream/utils/mergeAsyncIterables.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/stream/utils/readableStreamFrom.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/stream/utils/withPing.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/stream/jsonl.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/stream/sse.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/http/resolveResponse.ts","../../../../../node_modules/src/api/navigation.react-server.ts","../../../../../node_modules/next/src/client/components/forbidden.ts","../../../../../node_modules/next/src/client/components/http-access-fallback/http-access-fallback.ts","../../../../../node_modules/next/src/client/components/is-next-router-error.ts","../../../../../node_modules/next/src/client/components/navigation.react-server.ts","../../../../../node_modules/next/src/client/components/not-found.ts","../../../../../node_modules/next/src/client/components/readonly-url-search-params.ts","../../../../../node_modules/next/src/client/components/redirect-error.ts","../../../../../node_modules/next/src/client/components/redirect-status-code.ts","../../../../../node_modules/next/src/client/components/redirect.ts","../../../../../node_modules/next/src/client/components/server-async-storage.ts","../../../../../node_modules/next/src/client/components/unauthorized.ts","../../../../../node_modules/next/src/client/components/unstable-rethrow.ts","../../../../../node_modules/next/src/shared/lib/lazy-dynamic/bailout-to-csr.ts","../../../../../node_modules/zod/v4/core/util.js","../../../../../node_modules/zod/v4/core/core.js","../../../../../node_modules/zod/v4/core/memoizer.js","../../../../../node_modules/zod/v4/core/registries.js","../../../../../node_modules/zod/v4/core/regexes.js","../../../../../node_modules/zod/v4/core/checks.js","../../../../../node_modules/zod/v4/core/doc.js","../../../../../node_modules/zod/v4/core/errors.js","../../../../../node_modules/zod/v4/core/parse.js","../../../../../node_modules/zod/v4/core/versions.js","../../../../../node_modules/zod/v4/core/schemas.js","../../../../../node_modules/zod/v4/core/api.js","../../../../../node_modules/zod/v4/core/to-json-schema.js","../../../../../node_modules/zod/v4/core/json-schema-processors.js","../../../../../node_modules/zod/v4/locales/en.js","../../../../../node_modules/zod/v4/classic/errors.js","../../../../../node_modules/zod/v4/classic/parse.js","../../../../../node_modules/zod/v4/classic/schemas.js","../../../../../node_modules/zod/v4/classic/iso.js","../../../../../node_modules/%40aeolus-fleet/common/src/fleet/index.ts","../../../../../web/lib/gateway-api/gateway-api.ts","../../../../../web/lib/gateway-api/page-account.ts","../../../../../web/lib/gateway-api/page-api.ts"],"sourcesContent":["unable to read source [project]/node_modules/@aeolus-fleet/common/src/ids/index.ts","unable to read source [project]/node_modules/@aeolus-fleet/common/src/schemas/account-token.ts","//#region \\0@oxc-project+runtime@0.149.0/helpers/esm/typeof.js\nfunction _typeof(o) {\n\t\"@babel/helpers - typeof\";\n\treturn _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function(o) {\n\t\treturn typeof o;\n\t} : function(o) {\n\t\treturn o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n\t}, _typeof(o);\n}\n//#endregion\n//#region \\0@oxc-project+runtime@0.149.0/helpers/esm/toPrimitive.js\nfunction toPrimitive(t, r) {\n\tif (\"object\" != _typeof(t) || !t) return t;\n\tvar e = t[Symbol.toPrimitive];\n\tif (void 0 !== e) {\n\t\tvar i = e.call(t, r || \"default\");\n\t\tif (\"object\" != _typeof(i)) return i;\n\t\tthrow new TypeError(\"@@toPrimitive must return a primitive value.\");\n\t}\n\treturn (\"string\" === r ? String : Number)(t);\n}\n//#endregion\n//#region \\0@oxc-project+runtime@0.149.0/helpers/esm/toPropertyKey.js\nfunction toPropertyKey(t) {\n\tvar i = toPrimitive(t, \"string\");\n\treturn \"symbol\" == _typeof(i) ? i : i + \"\";\n}\n//#endregion\n//#region \\0@oxc-project+runtime@0.149.0/helpers/esm/defineProperty.js\nfunction _defineProperty(e, r, t) {\n\treturn (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n\t\tvalue: t,\n\t\tenumerable: !0,\n\t\tconfigurable: !0,\n\t\twritable: !0\n\t}) : e[r] = t, e;\n}\n//#endregion\n//#region \\0@oxc-project+runtime@0.149.0/helpers/esm/objectSpread2.js\nfunction ownKeys(e, r) {\n\tvar t = Object.keys(e);\n\tif (Object.getOwnPropertySymbols) {\n\t\tvar o = Object.getOwnPropertySymbols(e);\n\t\tr && (o = o.filter(function(r) {\n\t\t\treturn Object.getOwnPropertyDescriptor(e, r).enumerable;\n\t\t})), t.push.apply(t, o);\n\t}\n\treturn t;\n}\nfunction _objectSpread2(e) {\n\tfor (var r = 1; r < arguments.length; r++) {\n\t\tvar t = null != arguments[r] ? arguments[r] : {};\n\t\tr % 2 ? ownKeys(Object(t), !0).forEach(function(r) {\n\t\t\t_defineProperty(e, r, t[r]);\n\t\t}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r) {\n\t\t\tObject.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));\n\t\t});\n\t}\n\treturn e;\n}\n//#endregion\nexport { _defineProperty as n, _objectSpread2 as t };\n","import { emptyObject } from './utils';\n\ninterface ProxyCallbackOptions {\n path: readonly string[];\n args: readonly unknown[];\n}\ntype ProxyCallback = (opts: ProxyCallbackOptions) => unknown;\n\nconst noop = () => {\n // noop\n};\n\nconst freezeIfAvailable = (obj: object) => {\n if (Object.freeze) {\n Object.freeze(obj);\n }\n};\n\nfunction createInnerProxy(\n callback: ProxyCallback,\n path: readonly string[],\n memo: Record<string, unknown>,\n) {\n const cacheKey = path.join('.');\n\n memo[cacheKey] ??= new Proxy(noop, {\n get(_obj, key) {\n if (typeof key !== 'string' || key === 'then') {\n // special case for if the proxy is accidentally treated\n // like a PromiseLike (like in `Promise.resolve(proxy)`)\n return undefined;\n }\n return createInnerProxy(callback, [...path, key], memo);\n },\n apply(_1, _2, args) {\n const lastOfPath = path[path.length - 1];\n\n // React 19 may call valueOf / toString / toJSON when coercing a proxy\n // to a primitive (e.g. during rendering or logging). Return a debug\n // string so the coercion does not recurse into the proxy. This only\n // triggers for direct calls (proxy.toString()), not for chained access\n // (proxy.toString.query()), preserving route naming freedom.\n if (\n lastOfPath === 'valueOf' ||\n lastOfPath === 'toString' ||\n lastOfPath === 'toJSON'\n ) {\n const debugPath = path.slice(0, -1).join('.');\n return `tRPC.proxy(${debugPath})`;\n }\n\n let opts = { args, path };\n // special handling for e.g. `trpc.hello.call(this, 'there')` and `trpc.hello.apply(this, ['there'])\n if (lastOfPath === 'call') {\n opts = {\n args: args.length >= 2 ? [args[1]] : [],\n path: path.slice(0, -1),\n };\n } else if (lastOfPath === 'apply') {\n opts = {\n args: args.length >= 2 ? args[1] : [],\n path: path.slice(0, -1),\n };\n }\n freezeIfAvailable(opts.args);\n freezeIfAvailable(opts.path);\n return callback(opts);\n },\n });\n\n return memo[cacheKey];\n}\n\n/**\n * Creates a proxy that calls the callback with the path and arguments\n *\n * @internal\n */\nexport const createRecursiveProxy = <TFaux = unknown>(\n callback: ProxyCallback,\n): TFaux => createInnerProxy(callback, [], emptyObject()) as TFaux;\n\n/**\n * Used in place of `new Proxy` where each handler will map 1 level deep to another value.\n *\n * @internal\n */\nexport const createFlatProxy = <TFaux>(\n callback: (path: keyof TFaux) => any,\n): TFaux => {\n return new Proxy(noop, {\n get(_obj, name) {\n if (name === 'then') {\n // special case for if the proxy is accidentally treated\n // like a PromiseLike (like in `Promise.resolve(proxy)`)\n return undefined;\n }\n return callback(name as any);\n },\n }) as TFaux;\n};\n","import type { Result } from '../unstable-core-do-not-import';\nimport type {\n Observable,\n Observer,\n OperatorFunction,\n TeardownLogic,\n UnaryFunction,\n Unsubscribable,\n} from './types';\n\n/** @public */\nexport type inferObservableValue<TObservable> =\n TObservable extends Observable<infer TValue, unknown> ? TValue : never;\n\n/** @public */\nexport function isObservable(x: unknown): x is Observable<unknown, unknown> {\n return typeof x === 'object' && x !== null && 'subscribe' in x;\n}\n\n/** @public */\nexport function observable<TValue, TError = unknown>(\n subscribe: (observer: Observer<TValue, TError>) => TeardownLogic,\n): Observable<TValue, TError> {\n const self: Observable<TValue, TError> = {\n subscribe(observer) {\n let teardownRef: TeardownLogic | null = null;\n let isDone = false;\n let unsubscribed = false;\n let teardownImmediately = false;\n function unsubscribe() {\n if (teardownRef === null) {\n teardownImmediately = true;\n return;\n }\n if (unsubscribed) {\n return;\n }\n unsubscribed = true;\n\n if (typeof teardownRef === 'function') {\n teardownRef();\n } else if (teardownRef) {\n teardownRef.unsubscribe();\n }\n }\n teardownRef = subscribe({\n next(value) {\n if (isDone) {\n return;\n }\n observer.next?.(value);\n },\n error(err) {\n if (isDone) {\n return;\n }\n isDone = true;\n observer.error?.(err);\n unsubscribe();\n },\n complete() {\n if (isDone) {\n return;\n }\n isDone = true;\n observer.complete?.();\n unsubscribe();\n },\n });\n if (teardownImmediately) {\n unsubscribe();\n }\n return {\n unsubscribe,\n };\n },\n pipe(\n ...operations: OperatorFunction<any, any, any, any>[]\n ): Observable<any, any> {\n return operations.reduce(pipeReducer, self);\n },\n };\n return self;\n}\n\nfunction pipeReducer(prev: any, fn: UnaryFunction<any, any>) {\n return fn(prev);\n}\n\n/** @internal */\nexport function observableToPromise<TValue>(\n observable: Observable<TValue, unknown>,\n) {\n const ac = new AbortController();\n const promise = new Promise<TValue>((resolve, reject) => {\n let isDone = false;\n function onDone() {\n if (isDone) {\n return;\n }\n isDone = true;\n obs$.unsubscribe();\n }\n ac.signal.addEventListener('abort', () => {\n reject(ac.signal.reason);\n });\n const obs$ = observable.subscribe({\n next(data) {\n isDone = true;\n resolve(data);\n onDone();\n },\n error(data) {\n reject(data);\n },\n complete() {\n ac.abort();\n onDone();\n },\n });\n });\n return promise;\n}\n\n/**\n * @internal\n */\nfunction observableToReadableStream<TValue>(\n observable: Observable<TValue, unknown>,\n signal: AbortSignal,\n): ReadableStream<Result<TValue>> {\n let unsub: Unsubscribable | null = null;\n\n const onAbort = () => {\n unsub?.unsubscribe();\n unsub = null;\n signal.removeEventListener('abort', onAbort);\n };\n\n return new ReadableStream<Result<TValue>>({\n start(controller) {\n unsub = observable.subscribe({\n next(data) {\n controller.enqueue({ ok: true, value: data });\n },\n error(error) {\n controller.enqueue({ ok: false, error });\n controller.close();\n },\n complete() {\n controller.close();\n },\n });\n\n if (signal.aborted) {\n onAbort();\n } else {\n signal.addEventListener('abort', onAbort, { once: true });\n }\n },\n cancel() {\n onAbort();\n },\n });\n}\n\n/** @internal */\nexport function observableToAsyncIterable<TValue>(\n observable: Observable<TValue, unknown>,\n signal: AbortSignal,\n): AsyncIterable<TValue> {\n const stream = observableToReadableStream(observable, signal);\n\n const reader = stream.getReader();\n const iterator: AsyncIterator<TValue> = {\n async next() {\n const value = await reader.read();\n if (value.done) {\n return {\n value: undefined,\n done: true,\n };\n }\n const { value: result } = value;\n if (!result.ok) {\n throw result.error;\n }\n return {\n value: result.value,\n done: false,\n };\n },\n async return() {\n await reader.cancel();\n return {\n value: undefined,\n done: true,\n };\n },\n };\n return {\n [Symbol.asyncIterator]() {\n return iterator;\n },\n };\n}\n","import { observable } from './observable';\nimport type {\n MonoTypeOperatorFunction,\n Observer,\n OperatorFunction,\n Unsubscribable,\n} from './types';\n\nexport function map<TValueBefore, TError, TValueAfter>(\n project: (value: TValueBefore, index: number) => TValueAfter,\n): OperatorFunction<TValueBefore, TError, TValueAfter, TError> {\n return (source) => {\n return observable((destination) => {\n let index = 0;\n const subscription = source.subscribe({\n next(value) {\n destination.next(project(value, index++));\n },\n error(error) {\n destination.error(error);\n },\n complete() {\n destination.complete();\n },\n });\n return subscription;\n });\n };\n}\n\ninterface ShareConfig {}\nexport function share<TValue, TError>(\n _opts?: ShareConfig,\n): MonoTypeOperatorFunction<TValue, TError> {\n return (source) => {\n let refCount = 0;\n\n let subscription: Unsubscribable | null = null;\n const observers: Partial<Observer<TValue, TError>>[] = [];\n\n function startIfNeeded() {\n if (subscription) {\n return;\n }\n subscription = source.subscribe({\n next(value) {\n for (const observer of observers) {\n observer.next?.(value);\n }\n },\n error(error) {\n for (const observer of observers) {\n observer.error?.(error);\n }\n },\n complete() {\n for (const observer of observers) {\n observer.complete?.();\n }\n },\n });\n }\n function resetIfNeeded() {\n // \"resetOnRefCountZero\"\n if (refCount === 0 && subscription) {\n const _sub = subscription;\n subscription = null;\n _sub.unsubscribe();\n }\n }\n\n return observable((subscriber) => {\n refCount++;\n\n observers.push(subscriber);\n startIfNeeded();\n return {\n unsubscribe() {\n refCount--;\n resetIfNeeded();\n\n const index = observers.findIndex((v) => v === subscriber);\n\n if (index > -1) {\n observers.splice(index, 1);\n }\n },\n };\n });\n };\n}\n\nexport function tap<TValue, TError>(\n observer: Partial<Observer<TValue, TError>>,\n): MonoTypeOperatorFunction<TValue, TError> {\n return (source) => {\n return observable((destination) => {\n return source.subscribe({\n next(value) {\n observer.next?.(value);\n destination.next(value);\n },\n error(error) {\n observer.error?.(error);\n destination.error(error);\n },\n complete() {\n observer.complete?.();\n destination.complete();\n },\n });\n });\n };\n}\n\nconst distinctUnsetMarker = Symbol();\nexport function distinctUntilChanged<TValue, TError>(\n compare: (a: TValue, b: TValue) => boolean = (a, b) => a === b,\n): MonoTypeOperatorFunction<TValue, TError> {\n return (source) => {\n return observable((destination) => {\n let lastValue: TValue | typeof distinctUnsetMarker = distinctUnsetMarker;\n\n return source.subscribe({\n next(value) {\n if (lastValue !== distinctUnsetMarker && compare(lastValue, value)) {\n return;\n }\n lastValue = value;\n destination.next(value);\n },\n error(error) {\n destination.error(error);\n },\n complete() {\n destination.complete();\n },\n });\n });\n };\n}\n\nconst isDeepEqual = <T>(a: T, b: T): boolean => {\n if (a === b) {\n return true;\n }\n const bothAreObjects =\n a && b && typeof a === 'object' && typeof b === 'object';\n\n return (\n !!bothAreObjects &&\n Object.keys(a).length === Object.keys(b).length &&\n Object.entries(a).every(([k, v]) => isDeepEqual(v, b[k as keyof T]))\n );\n};\nexport function distinctUntilDeepChanged<\n TValue,\n TError,\n>(): MonoTypeOperatorFunction<TValue, TError> {\n return distinctUntilChanged(isDeepEqual);\n}\n","import type { FetchEsque, NativeFetchEsque } from './internals/types';\n\ntype AnyFn = (...args: any[]) => unknown;\n\nconst isFunction = (fn: unknown): fn is AnyFn => typeof fn === 'function';\n\nexport function getFetch(\n customFetchImpl?: FetchEsque | NativeFetchEsque,\n): FetchEsque {\n if (customFetchImpl) {\n return customFetchImpl as FetchEsque;\n }\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (typeof window !== 'undefined' && isFunction(window.fetch)) {\n return window.fetch.bind(window);\n }\n\n if (typeof globalThis !== 'undefined' && isFunction(globalThis.fetch)) {\n return globalThis.fetch;\n }\n\n throw new Error('No fetch implementation found');\n}\n","import { observable } from '@trpc/server/observable';\nimport type { AnyRouter } from '@trpc/server/unstable-core-do-not-import';\nimport type {\n Operation,\n OperationLink,\n OperationResultObservable,\n} from '../types';\n\n/** @internal */\nexport function createChain<\n TRouter extends AnyRouter,\n TInput = unknown,\n TOutput = unknown,\n>(opts: {\n links: OperationLink<TRouter, TInput, TOutput>[];\n op: Operation<TInput>;\n}): OperationResultObservable<TRouter, TOutput> {\n return observable((observer) => {\n function execute(index = 0, op = opts.op) {\n const next = opts.links[index];\n if (!next) {\n throw new Error(\n 'No more links to execute - did you forget to add an ending link?',\n );\n }\n const subscription = next({\n op,\n next(nextOp) {\n const nextObserver = execute(index + 1, nextOp);\n\n return nextObserver;\n },\n });\n return subscription;\n }\n\n const obs$ = execute();\n return obs$.subscribe(observer);\n });\n}\n","import type { ProcedureType } from '../procedure';\nimport type {\n TRPC_ERROR_CODE_KEY,\n TRPC_ERROR_CODE_NUMBER,\n TRPCErrorShape,\n} from '../rpc';\nimport type { TRPCError } from './TRPCError';\n\n/**\n * @internal\n */\nexport type ErrorFormatter<TContext, TShape extends TRPCErrorShape> = (opts: {\n error: TRPCError;\n type: ProcedureType | 'unknown';\n path: string | undefined;\n input: unknown;\n ctx: TContext | undefined;\n shape: DefaultErrorShape;\n}) => TShape;\n\n/**\n * @internal\n */\nexport type DefaultErrorData = {\n code: TRPC_ERROR_CODE_KEY;\n httpStatus: number;\n /**\n * Path to the procedure that threw the error\n */\n path?: string;\n /**\n * Stack trace of the error (only in development)\n */\n stack?: string;\n};\n\n/**\n * @internal\n */\nexport interface DefaultErrorShape extends TRPCErrorShape<DefaultErrorData> {\n message: string;\n code: TRPC_ERROR_CODE_NUMBER;\n}\n\nexport const defaultFormatter: ErrorFormatter<any, any> = ({ shape }) => {\n return shape;\n};\n","/// <reference lib=\"dom.iterable\" />\n\n// `dom.iterable` types are explicitly required for extracting `FormData` values,\n// as all implementations of `Symbol.iterable` are separated from the main `dom` types.\n// Using triple-slash directive makes sure that it will be available,\n// even if end-user `tsconfig.json` omits it in the `lib` array.\n\nimport { observable, tap } from '@trpc/server/observable';\nimport type {\n AnyRouter,\n InferrableClientTypes,\n} from '@trpc/server/unstable-core-do-not-import';\nimport type { TRPCClientError } from '../TRPCClientError';\nimport type { Operation, OperationResultEnvelope, TRPCLink } from './types';\n\ntype ConsoleEsque = {\n log: (...args: any[]) => void;\n error: (...args: any[]) => void;\n};\n\ntype EnableFnOptions<TRouter extends InferrableClientTypes> =\n | {\n direction: 'down';\n result:\n | OperationResultEnvelope<unknown, TRPCClientError<TRouter>>\n | TRPCClientError<TRouter>;\n }\n | (Operation & {\n direction: 'up';\n });\ntype EnabledFn<TRouter extends AnyRouter> = (\n opts: EnableFnOptions<TRouter>,\n) => boolean;\n\ntype LoggerLinkFnOptions<TRouter extends AnyRouter> = Operation &\n (\n | {\n /**\n * Request result\n */\n direction: 'down';\n result:\n | OperationResultEnvelope<unknown, TRPCClientError<TRouter>>\n | TRPCClientError<TRouter>;\n elapsedMs: number;\n }\n | {\n /**\n * Request was just initialized\n */\n direction: 'up';\n }\n );\n\ntype LoggerLinkFn<TRouter extends AnyRouter> = (\n opts: LoggerLinkFnOptions<TRouter>,\n) => void;\n\ntype ColorMode = 'ansi' | 'css' | 'none';\n\nexport interface LoggerLinkOptions<TRouter extends AnyRouter> {\n logger?: LoggerLinkFn<TRouter>;\n enabled?: EnabledFn<TRouter>;\n /**\n * Used in the built-in defaultLogger\n */\n console?: ConsoleEsque;\n /**\n * Color mode\n * @default typeof window === 'undefined' ? 'ansi' : 'css'\n */\n colorMode?: ColorMode;\n\n /**\n * Include context in the log - defaults to false unless `colorMode` is 'css'\n */\n withContext?: boolean;\n}\n\nfunction isFormData(value: unknown): value is FormData {\n if (typeof FormData === 'undefined') {\n // FormData is not supported\n return false;\n }\n return value instanceof FormData;\n}\n\nconst palettes = {\n css: {\n query: ['72e3ff', '3fb0d8'],\n mutation: ['c5a3fc', '904dfc'],\n subscription: ['ff49e1', 'd83fbe'],\n },\n ansi: {\n regular: {\n // Cyan background, black and white text respectively\n query: ['\\x1b[30;46m', '\\x1b[97;46m'],\n // Magenta background, black and white text respectively\n mutation: ['\\x1b[30;45m', '\\x1b[97;45m'],\n // Green background, black and white text respectively\n subscription: ['\\x1b[30;42m', '\\x1b[97;42m'],\n },\n bold: {\n query: ['\\x1b[1;30;46m', '\\x1b[1;97;46m'],\n mutation: ['\\x1b[1;30;45m', '\\x1b[1;97;45m'],\n subscription: ['\\x1b[1;30;42m', '\\x1b[1;97;42m'],\n },\n },\n} as const;\n\nfunction constructPartsAndArgs(\n opts: LoggerLinkFnOptions<any> & {\n colorMode: ColorMode;\n withContext?: boolean;\n },\n) {\n const { direction, type, withContext, path, id, input } = opts;\n\n const parts: string[] = [];\n const args: any[] = [];\n\n if (opts.colorMode === 'none') {\n parts.push(direction === 'up' ? '>>' : '<<', type, `#${id}`, path);\n } else if (opts.colorMode === 'ansi') {\n const [lightRegular, darkRegular] = palettes.ansi.regular[type];\n const [lightBold, darkBold] = palettes.ansi.bold[type];\n const reset = '\\x1b[0m';\n\n parts.push(\n direction === 'up' ? lightRegular : darkRegular,\n direction === 'up' ? '>>' : '<<',\n type,\n direction === 'up' ? lightBold : darkBold,\n `#${id}`,\n path,\n reset,\n );\n } else {\n // css color mode\n const [light, dark] = palettes.css[type];\n const css = `\n background-color: #${direction === 'up' ? light : dark};\n color: ${direction === 'up' ? 'black' : 'white'};\n padding: 2px;\n `;\n\n parts.push(\n '%c',\n direction === 'up' ? '>>' : '<<',\n type,\n `#${id}`,\n `%c${path}%c`,\n '%O',\n );\n args.push(\n css,\n `${css}; font-weight: bold;`,\n `${css}; font-weight: normal;`,\n );\n }\n\n if (direction === 'up') {\n args.push(withContext ? { input, context: opts.context } : { input });\n } else {\n args.push({\n input,\n result: opts.result,\n elapsedMs: opts.elapsedMs,\n ...(withContext && { context: opts.context }),\n });\n }\n\n return { parts, args };\n}\n\n// maybe this should be moved to it's own package\nconst defaultLogger =\n <TRouter extends AnyRouter>({\n c = console,\n colorMode = 'css',\n withContext,\n }: {\n c?: ConsoleEsque;\n colorMode?: ColorMode;\n withContext?: boolean;\n }): LoggerLinkFn<TRouter> =>\n (props) => {\n const rawInput = props.input;\n const input = isFormData(rawInput)\n ? Object.fromEntries(rawInput)\n : rawInput;\n\n const { parts, args } = constructPartsAndArgs({\n ...props,\n colorMode,\n input,\n withContext,\n });\n\n const fn: 'error' | 'log' =\n props.direction === 'down' &&\n props.result &&\n (props.result instanceof Error ||\n ('error' in props.result.result && props.result.result.error))\n ? 'error'\n : 'log';\n\n c[fn].apply(null, [parts.join(' ')].concat(args));\n };\n\n/**\n * @see https://trpc.io/docs/v11/client/links/loggerLink\n */\nexport function loggerLink<TRouter extends AnyRouter = AnyRouter>(\n opts: LoggerLinkOptions<TRouter> = {},\n): TRPCLink<TRouter> {\n const { enabled = () => true } = opts;\n\n const colorMode =\n opts.colorMode ?? (typeof window === 'undefined' ? 'ansi' : 'css');\n const withContext = opts.withContext ?? colorMode === 'css';\n const {\n logger = defaultLogger({ c: opts.console, colorMode, withContext }),\n } = opts;\n\n return () => {\n return ({ op, next }) => {\n return observable((observer) => {\n // ->\n if (enabled({ ...op, direction: 'up' })) {\n logger({\n ...op,\n direction: 'up',\n });\n }\n const requestStartTime = Date.now();\n function logResult(\n result:\n | OperationResultEnvelope<unknown, TRPCClientError<TRouter>>\n | TRPCClientError<TRouter>,\n ) {\n const elapsedMs = Date.now() - requestStartTime;\n\n if (enabled({ ...op, direction: 'down', result })) {\n logger({\n ...op,\n direction: 'down',\n elapsedMs,\n result,\n });\n }\n }\n return next(op)\n .pipe(\n tap({\n next(result) {\n logResult(result);\n },\n error(result) {\n logResult(result);\n },\n }),\n )\n .subscribe(observer);\n });\n };\n };\n}\n","import { TRPCError } from '../error/TRPCError';\nimport { isObject } from '../utils';\nimport type { TRPCRequestInfo } from './types';\n\nexport function parseConnectionParamsFromUnknown(\n parsed: unknown,\n): TRPCRequestInfo['connectionParams'] {\n try {\n if (parsed === null) {\n return null;\n }\n if (!isObject(parsed)) {\n throw new Error('Expected object');\n }\n const nonStringValues = Object.entries(parsed).filter(\n ([_key, value]) => typeof value !== 'string',\n );\n\n if (nonStringValues.length > 0) {\n throw new Error(\n `Expected connectionParams to be string values. Got ${nonStringValues\n .map(([key, value]) => `${key}: ${typeof value}`)\n .join(', ')}`,\n );\n }\n return parsed as Record<string, string>;\n } catch (cause) {\n throw new TRPCError({\n code: 'PARSE_ERROR',\n message: 'Invalid connection params shape',\n cause,\n });\n }\n}\nexport function parseConnectionParamsFromString(\n str: string,\n): TRPCRequestInfo['connectionParams'] {\n let parsed: unknown;\n try {\n parsed = JSON.parse(str);\n } catch (cause) {\n throw new TRPCError({\n code: 'PARSE_ERROR',\n message: 'Not JSON-parsable query params',\n cause,\n });\n }\n return parseConnectionParamsFromUnknown(parsed);\n}\n","/** @internal */\nexport type UnsetMarker = 'unsetMarker' & {\n __brand: 'unsetMarker';\n};\n\n/**\n * Ensures there are no duplicate keys when building a procedure.\n * @internal\n */\nexport function mergeWithoutOverrides<TType extends Record<string, unknown>>(\n obj1: TType,\n ...objs: Partial<TType>[]\n): TType {\n const newObj: TType = Object.assign(emptyObject(), obj1);\n\n for (const overrides of objs) {\n for (const key in overrides) {\n if (key in newObj && newObj[key] !== overrides[key]) {\n throw new Error(`Duplicate key ${key}`);\n }\n newObj[key as keyof TType] = overrides[key] as TType[keyof TType];\n }\n }\n return newObj;\n}\n\n/**\n * Check that value is object\n * @internal\n */\nexport function isObject(value: unknown): value is Record<string, unknown> {\n return !!value && !Array.isArray(value) && typeof value === 'object';\n}\n\ntype AnyFn = ((...args: any[]) => unknown) & Record<keyof any, unknown>;\nexport function isFunction(fn: unknown): fn is AnyFn {\n return typeof fn === 'function';\n}\n\n/**\n * Create an object without inheriting anything from `Object.prototype`\n * @internal\n */\nexport function emptyObject<TObj extends Record<string, unknown>>(): TObj {\n return Object.create(null);\n}\n\nconst asyncIteratorsSupported =\n typeof Symbol === 'function' && !!Symbol.asyncIterator;\n\nexport function isAsyncIterable<TValue>(\n value: unknown,\n): value is AsyncIterable<TValue> {\n return (\n asyncIteratorsSupported && isObject(value) && Symbol.asyncIterator in value\n );\n}\n\n/**\n * Run an IIFE\n */\nexport const run = <TValue>(fn: () => TValue): TValue => fn();\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nexport function noop(): void {}\n\nexport function identity<T>(it: T): T {\n return it;\n}\n\n/**\n * Generic runtime assertion function. Throws, if the condition is not `true`.\n *\n * Can be used as a slightly less dangerous variant of type assertions. Code\n * mistakes would be revealed at runtime then (hopefully during testing).\n */\nexport function assert(\n condition: boolean,\n msg = 'no additional info',\n): asserts condition {\n if (!condition) {\n throw new Error(`AssertionError: ${msg}`);\n }\n}\n\nexport function sleep(ms = 0): Promise<void> {\n return new Promise<void>((res) => setTimeout(res, ms));\n}\n\n/**\n * Ponyfill for\n * [`AbortSignal.any`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/any_static).\n */\nexport function abortSignalsAnyPonyfill(signals: AbortSignal[]): AbortSignal {\n if (typeof AbortSignal.any === 'function') {\n return AbortSignal.any(signals);\n }\n\n const ac = new AbortController();\n\n for (const signal of signals) {\n if (signal.aborted) {\n trigger();\n break;\n }\n signal.addEventListener('abort', trigger, { once: true });\n }\n\n return ac.signal;\n\n function trigger() {\n ac.abort();\n for (const signal of signals) {\n signal.removeEventListener('abort', trigger);\n }\n }\n}\n","import type { Encoder } from '@trpc/server/adapters/ws';\n\nexport type { Encoder };\n\nexport const jsonEncoder: Encoder = {\n encode: (data) => JSON.stringify(data),\n decode: (data) => {\n if (typeof data !== 'string') {\n throw new Error(\n 'jsonEncoder received binary data. JSON uses text frames. ' +\n 'Use a binary encoder for binary data.',\n );\n }\n return JSON.parse(data);\n },\n};\n","import type {\n inferClientTypes,\n InferrableClientTypes,\n Maybe,\n TRPCErrorResponse,\n} from '@trpc/server/unstable-core-do-not-import';\nimport {\n isObject,\n type DefaultErrorShape,\n} from '@trpc/server/unstable-core-do-not-import';\n\ntype inferErrorShape<TInferrable extends InferrableClientTypes> =\n inferClientTypes<TInferrable>['errorShape'];\nexport interface TRPCClientErrorBase<TShape extends DefaultErrorShape> {\n readonly message: string;\n readonly shape: Maybe<TShape>;\n readonly data: Maybe<TShape['data']>;\n}\nexport type TRPCClientErrorLike<TInferrable extends InferrableClientTypes> =\n TRPCClientErrorBase<inferErrorShape<TInferrable>>;\n\nexport function isTRPCClientError<TInferrable extends InferrableClientTypes>(\n cause: unknown,\n): cause is TRPCClientError<TInferrable> {\n return cause instanceof TRPCClientError;\n}\n\nfunction isTRPCErrorResponse(obj: unknown): obj is TRPCErrorResponse<any> {\n return (\n isObject(obj) &&\n isObject(obj['error']) &&\n typeof obj['error']['code'] === 'number' &&\n typeof obj['error']['message'] === 'string'\n );\n}\n\nfunction getMessageFromUnknownError(err: unknown, fallback: string): string {\n if (typeof err === 'string') {\n return err;\n }\n if (isObject(err) && typeof err['message'] === 'string') {\n return err['message'];\n }\n return fallback;\n}\n\nexport class TRPCClientError<TRouterOrProcedure extends InferrableClientTypes>\n extends Error\n implements TRPCClientErrorBase<inferErrorShape<TRouterOrProcedure>>\n{\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore override doesn't work in all environments due to \"This member cannot have an 'override' modifier because it is not declared in the base class 'Error'\"\n public override readonly cause;\n public readonly shape: Maybe<inferErrorShape<TRouterOrProcedure>>;\n public readonly data: Maybe<inferErrorShape<TRouterOrProcedure>['data']>;\n\n /**\n * Additional meta data about the error\n * In the case of HTTP-errors, we'll have `response` and potentially `responseJSON` here\n */\n public meta;\n\n constructor(\n message: string,\n opts?: {\n result?: Maybe<TRPCErrorResponse<inferErrorShape<TRouterOrProcedure>>>;\n cause?: Error;\n meta?: Record<string, unknown>;\n },\n ) {\n const cause = opts?.cause;\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore https://github.com/tc39/proposal-error-cause\n super(message, { cause });\n\n this.meta = opts?.meta;\n\n this.cause = cause;\n this.shape = opts?.result?.error;\n this.data = opts?.result?.error.data;\n this.name = 'TRPCClientError';\n\n Object.setPrototypeOf(this, TRPCClientError.prototype);\n }\n\n public static from<TRouterOrProcedure extends InferrableClientTypes>(\n _cause: Error | TRPCErrorResponse<any> | object,\n opts: { meta?: Record<string, unknown>; cause?: Error } = {},\n ): TRPCClientError<TRouterOrProcedure> {\n const cause = _cause as unknown;\n\n if (isTRPCClientError(cause)) {\n if (opts.meta) {\n // Decorate with meta error data\n cause.meta = {\n ...cause.meta,\n ...opts.meta,\n };\n }\n return cause;\n }\n if (isTRPCErrorResponse(cause)) {\n return new TRPCClientError(cause.error.message, {\n ...opts,\n result: cause,\n cause: opts.cause,\n });\n }\n return new TRPCClientError(\n getMessageFromUnknownError(cause, 'Unknown error'),\n {\n ...opts,\n cause: cause as any,\n },\n );\n }\n}\n","export function isOctetType(\n input: unknown,\n): input is Uint8Array<ArrayBuffer> | Blob {\n return (\n input instanceof Uint8Array ||\n // File extends from Blob but is only available in nodejs from v20\n input instanceof Blob\n );\n}\n\nexport function isFormData(input: unknown) {\n return input instanceof FormData;\n}\n\nexport function isNonJsonSerializable(input: unknown) {\n return isOctetType(input) || isFormData(input);\n}\n","import type { TRPC_ERROR_CODE_KEY } from '../rpc/codes';\nimport { isObject } from '../utils';\n\nclass UnknownCauseError extends Error {\n [key: string]: unknown;\n\n constructor(cause: object) {\n super(getMessage(cause));\n Object.assign(this, cause);\n }\n}\n\nfunction getMessage(cause: object) {\n if ('message' in cause) return String(cause.message);\n\n return undefined;\n}\n\nexport function getCauseFromUnknown(cause: unknown): Error | undefined {\n if (cause instanceof Error) {\n return cause;\n }\n\n const type = typeof cause;\n if (type === 'undefined' || type === 'function' || cause === null) {\n return undefined;\n }\n\n // Primitive types just get wrapped in an error\n if (type !== 'object') {\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n return new Error(String(cause));\n }\n\n // If it's an object, we'll create a synthetic error\n if (isObject(cause)) {\n return new UnknownCauseError(cause);\n }\n\n return undefined;\n}\n\nexport function getTRPCErrorFromUnknown(cause: unknown): TRPCError {\n if (cause instanceof TRPCError) {\n return cause;\n }\n if (cause instanceof Error && cause.name === 'TRPCError') {\n // https://github.com/trpc/trpc/pull/4848\n return cause as TRPCError;\n }\n\n const trpcError = new TRPCError({\n code: 'INTERNAL_SERVER_ERROR',\n cause,\n });\n\n // Inherit stack from error\n if (cause instanceof Error && cause.stack) {\n trpcError.stack = cause.stack;\n }\n\n return trpcError;\n}\n\nexport class TRPCError extends Error {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore override doesn't work in all environments due to \"This member cannot have an 'override' modifier because it is not declared in the base class 'Error'\"\n public override readonly cause?: Error;\n public readonly code;\n\n constructor(opts: {\n message?: string;\n code: TRPC_ERROR_CODE_KEY;\n cause?: unknown;\n }) {\n const cause = getCauseFromUnknown(opts.cause);\n const message = opts.message ?? cause?.message ?? opts.code;\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore https://github.com/tc39/proposal-error-cause\n super(message, { cause });\n\n this.code = opts.code;\n this.name = 'TRPCError';\n this.cause ??= cause;\n }\n}\n","/* eslint-disable @typescript-eslint/no-non-null-assertion */\n\ntype BatchItem<TKey, TValue> = {\n aborted: boolean;\n key: TKey;\n resolve: ((value: TValue) => void) | null;\n reject: ((error: Error) => void) | null;\n batch: Batch<TKey, TValue> | null;\n};\ntype Batch<TKey, TValue> = {\n items: BatchItem<TKey, TValue>[];\n};\nexport type BatchLoader<TKey, TValue> = {\n validate: (keys: TKey[]) => boolean;\n fetch: (keys: TKey[]) => Promise<TValue[] | Promise<TValue>[]>;\n};\n\n/**\n * A function that should never be called unless we messed something up.\n */\nconst throwFatalError = () => {\n throw new Error(\n 'Something went wrong. Please submit an issue at https://github.com/trpc/trpc/issues/new',\n );\n};\n\n/**\n * Dataloader that's very inspired by https://github.com/graphql/dataloader\n * Less configuration, no caching, and allows you to cancel requests\n * When cancelling a single fetch the whole batch will be cancelled only when _all_ items are cancelled\n */\nexport function dataLoader<TKey, TValue>(\n batchLoader: BatchLoader<TKey, TValue>,\n) {\n let pendingItems: BatchItem<TKey, TValue>[] | null = null;\n let dispatchTimer: ReturnType<typeof setTimeout> | null = null;\n\n const destroyTimerAndPendingItems = () => {\n clearTimeout(dispatchTimer as any);\n dispatchTimer = null;\n pendingItems = null;\n };\n\n /**\n * Iterate through the items and split them into groups based on the `batchLoader`'s validate function\n */\n function groupItems(items: BatchItem<TKey, TValue>[]) {\n const groupedItems: BatchItem<TKey, TValue>[][] = [[]];\n let index = 0;\n while (true) {\n const item = items[index];\n if (!item) {\n // we're done\n break;\n }\n const lastGroup = groupedItems[groupedItems.length - 1]!;\n\n if (item.aborted) {\n // Item was aborted before it was dispatched\n item.reject?.(new Error('Aborted'));\n index++;\n continue;\n }\n\n const isValid = batchLoader.validate(\n lastGroup.concat(item).map((it) => it.key),\n );\n\n if (isValid) {\n lastGroup.push(item);\n index++;\n continue;\n }\n\n if (lastGroup.length === 0) {\n item.reject?.(new Error('Input is too big for a single dispatch'));\n index++;\n continue;\n }\n // Create new group, next iteration will try to add the item to that\n groupedItems.push([]);\n }\n return groupedItems;\n }\n\n function dispatch() {\n const groupedItems = groupItems(pendingItems!);\n destroyTimerAndPendingItems();\n\n // Create batches for each group of items\n for (const items of groupedItems) {\n if (!items.length) {\n continue;\n }\n const batch: Batch<TKey, TValue> = {\n items,\n };\n for (const item of items) {\n item.batch = batch;\n }\n const promise = batchLoader.fetch(batch.items.map((_item) => _item.key));\n\n promise\n .then(async (result) => {\n await Promise.all(\n result.map(async (valueOrPromise, index) => {\n const item = batch.items[index]!;\n try {\n const value = await Promise.resolve(valueOrPromise);\n\n item.resolve?.(value);\n } catch (cause) {\n item.reject?.(cause as Error);\n }\n\n item.batch = null;\n item.reject = null;\n item.resolve = null;\n }),\n );\n\n for (const item of batch.items) {\n item.reject?.(new Error('Missing result'));\n item.batch = null;\n }\n })\n .catch((cause) => {\n for (const item of batch.items) {\n item.reject?.(cause);\n item.batch = null;\n }\n });\n }\n }\n function load(key: TKey): Promise<TValue> {\n const item: BatchItem<TKey, TValue> = {\n aborted: false,\n key,\n batch: null,\n resolve: throwFatalError,\n reject: throwFatalError,\n };\n\n const promise = new Promise<TValue>((resolve, reject) => {\n item.reject = reject;\n item.resolve = resolve;\n\n pendingItems ??= [];\n pendingItems.push(item);\n });\n\n dispatchTimer ??= setTimeout(dispatch);\n\n return promise;\n }\n\n return {\n load,\n };\n}\n","import type {\n AnyClientTypes,\n CombinedDataTransformer,\n DataTransformerOptions,\n TypeError,\n} from '@trpc/server/unstable-core-do-not-import';\n\n/**\n * @internal\n */\nexport type CoercedTransformerParameters = {\n transformer?: DataTransformerOptions;\n};\n\ntype TransformerOptionYes = {\n /**\n * Data transformer\n *\n * You must use the same transformer on the backend and frontend\n * @see https://trpc.io/docs/v11/data-transformers\n **/\n transformer: DataTransformerOptions;\n};\ntype TransformerOptionNo = {\n /**\n * Data transformer\n *\n * You must use the same transformer on the backend and frontend\n * @see https://trpc.io/docs/v11/data-transformers\n **/\n transformer?: TypeError<'You must define a transformer on your your `initTRPC`-object first'>;\n};\n\n/**\n * @internal\n */\nexport type TransformerOptions<\n TRoot extends Pick<AnyClientTypes, 'transformer'>,\n> = TRoot['transformer'] extends true\n ? TransformerOptionYes\n : TransformerOptionNo;\n/**\n * @internal\n */\n\n/**\n * @internal\n */\nexport function getTransformer(\n transformer:\n | TransformerOptions<{ transformer: false }>['transformer']\n | TransformerOptions<{ transformer: true }>['transformer']\n | undefined,\n): CombinedDataTransformer {\n const _transformer =\n transformer as CoercedTransformerParameters['transformer'];\n if (!_transformer) {\n return {\n input: {\n serialize: (data) => data,\n deserialize: (data) => data,\n },\n output: {\n serialize: (data) => data,\n deserialize: (data) => data,\n },\n };\n }\n if ('input' in _transformer) {\n return _transformer;\n }\n return {\n input: _transformer,\n output: _transformer,\n };\n}\n","import type {\n inferObservableValue,\n Unsubscribable,\n} from '@trpc/server/observable';\nimport { observableToPromise, share } from '@trpc/server/observable';\nimport type {\n AnyRouter,\n inferAsyncIterableYield,\n InferrableClientTypes,\n Maybe,\n TypeError,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { createChain } from '../links/internals/createChain';\nimport type { TRPCConnectionState } from '../links/internals/subscriptions';\nimport type {\n OperationContext,\n OperationLink,\n TRPCClientRuntime,\n TRPCLink,\n} from '../links/types';\nimport { TRPCClientError } from '../TRPCClientError';\n\ntype TRPCType = 'mutation' | 'query' | 'subscription';\nexport interface TRPCRequestOptions {\n /**\n * Pass additional context to links\n */\n context?: OperationContext;\n signal?: AbortSignal;\n}\n\nexport interface TRPCSubscriptionObserver<TValue, TError> {\n onStarted: (opts: { context: OperationContext | undefined }) => void;\n onData: (value: inferAsyncIterableYield<TValue>) => void;\n onError: (err: TError) => void;\n onStopped: () => void;\n onComplete: () => void;\n onConnectionStateChange: (state: TRPCConnectionState<TError>) => void;\n}\n\n/** @internal */\nexport type CreateTRPCClientOptions<TRouter extends InferrableClientTypes> = {\n links: TRPCLink<TRouter>[];\n transformer?: TypeError<'The transformer property has moved to httpLink/httpBatchLink/wsLink'>;\n};\n\nexport class TRPCUntypedClient<TInferrable extends InferrableClientTypes> {\n private readonly links: OperationLink<TInferrable>[];\n public readonly runtime: TRPCClientRuntime;\n private requestId: number;\n\n constructor(opts: CreateTRPCClientOptions<TInferrable>) {\n this.requestId = 0;\n\n this.runtime = {};\n\n // Initialize the links\n this.links = opts.links.map((link) => link(this.runtime));\n }\n\n private $request<TInput = unknown, TOutput = unknown>(opts: {\n type: TRPCType;\n input: TInput;\n path: string;\n context?: OperationContext;\n signal: Maybe<AbortSignal>;\n }) {\n const chain$ = createChain<AnyRouter, TInput, TOutput>({\n links: this.links as OperationLink<any, any, any>[],\n op: {\n ...opts,\n context: opts.context ?? {},\n id: ++this.requestId,\n },\n });\n return chain$.pipe(share());\n }\n\n private async requestAsPromise<TInput = unknown, TOutput = unknown>(opts: {\n type: TRPCType;\n input: TInput;\n path: string;\n context?: OperationContext;\n signal: Maybe<AbortSignal>;\n }): Promise<TOutput> {\n try {\n const req$ = this.$request<TInput, TOutput>(opts);\n type TValue = inferObservableValue<typeof req$>;\n\n const envelope = await observableToPromise<TValue>(req$);\n const data = (envelope.result as any).data;\n return data;\n } catch (err) {\n throw TRPCClientError.from(err as Error);\n }\n }\n public query(path: string, input?: unknown, opts?: TRPCRequestOptions) {\n return this.requestAsPromise<unknown, unknown>({\n type: 'query',\n path,\n input,\n context: opts?.context,\n signal: opts?.signal,\n });\n }\n public mutation(path: string, input?: unknown, opts?: TRPCRequestOptions) {\n return this.requestAsPromise<unknown, unknown>({\n type: 'mutation',\n path,\n input,\n context: opts?.context,\n signal: opts?.signal,\n });\n }\n public subscription(\n path: string,\n input: unknown,\n opts: Partial<\n TRPCSubscriptionObserver<unknown, TRPCClientError<AnyRouter>>\n > &\n TRPCRequestOptions,\n ): Unsubscribable {\n const observable$ = this.$request({\n type: 'subscription',\n path,\n input,\n context: opts.context,\n signal: opts.signal,\n });\n return observable$.subscribe({\n next(envelope) {\n switch (envelope.result.type) {\n case 'state': {\n opts.onConnectionStateChange?.(envelope.result);\n break;\n }\n case 'started': {\n opts.onStarted?.({\n context: envelope.context,\n });\n break;\n }\n case 'stopped': {\n opts.onStopped?.();\n break;\n }\n case 'data':\n case undefined: {\n opts.onData?.(envelope.result.data);\n break;\n }\n }\n },\n error(err) {\n opts.onError?.(err);\n },\n complete() {\n opts.onComplete?.();\n },\n });\n }\n}\n","import type { UrlOptionsWithConnectionParams } from '../../internals/urlWithConnectionParams';\nimport type { Encoder } from './encoder';\n\nexport interface WebSocketClientOptions extends UrlOptionsWithConnectionParams {\n /**\n * Ponyfill which WebSocket implementation to use\n */\n WebSocket?: typeof WebSocket;\n /**\n * The number of milliseconds before a reconnect is attempted.\n * @default {@link exponentialBackoff}\n */\n retryDelayMs?: (attemptIndex: number) => number;\n /**\n * Triggered when a WebSocket connection is established\n */\n onOpen?: () => void;\n /**\n * Triggered when a WebSocket connection encounters an error\n */\n onError?: (evt?: Event) => void;\n /**\n * Triggered when a WebSocket connection is closed\n */\n onClose?: (cause?: { code?: number }) => void;\n /**\n * Lazy mode will close the WebSocket automatically after a period of inactivity (no messages sent or received and no pending requests)\n */\n lazy?: {\n /**\n * Enable lazy mode\n * @default false\n */\n enabled: boolean;\n /**\n * Close the WebSocket after this many milliseconds\n * @default 0\n */\n closeMs: number;\n };\n /**\n * Send ping messages to the server and kill the connection if no pong message is returned\n */\n keepAlive?: {\n /**\n * @default false\n */\n enabled: boolean;\n /**\n * Send a ping message every this many milliseconds\n * @default 5_000\n */\n intervalMs?: number;\n /**\n * Close the WebSocket after this many milliseconds if the server does not respond\n * @default 1_000\n */\n pongTimeoutMs?: number;\n };\n /**\n * Custom encoder for wire encoding (e.g. custom binary formats)\n * @default jsonEncoder\n */\n experimental_encoder?: Encoder;\n}\n\n/**\n * Default options for lazy WebSocket connections.\n * Determines whether the connection should be established lazily and defines the delay before closure.\n */\nexport type LazyOptions = Required<NonNullable<WebSocketClientOptions['lazy']>>;\nexport const lazyDefaults: LazyOptions = {\n enabled: false,\n closeMs: 0,\n};\n\n/**\n * Default options for the WebSocket keep-alive mechanism.\n * Configures whether keep-alive is enabled and specifies the timeout and interval for ping-pong messages.\n */\nexport type KeepAliveOptions = Required<\n NonNullable<WebSocketClientOptions['keepAlive']>\n>;\nexport const keepAliveDefaults: KeepAliveOptions = {\n enabled: false,\n pongTimeoutMs: 1_000,\n intervalMs: 5_000,\n};\n\n/**\n * Calculates a delay for exponential backoff based on the retry attempt index.\n * The delay starts at 0 for the first attempt and doubles for each subsequent attempt,\n * capped at 30 seconds.\n */\nexport const exponentialBackoff = (attemptIndex: number) => {\n return attemptIndex === 0 ? 0 : Math.min(1000 * 2 ** attemptIndex, 30000);\n};\n","import { observable } from '@trpc/server/observable';\nimport type {\n AnyClientTypes,\n AnyRouter,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { transformResult } from '@trpc/server/unstable-core-do-not-import';\nimport { raceAbortSignals } from '../internals/signals';\nimport { TRPCClientError } from '../TRPCClientError';\nimport type {\n HTTPLinkBaseOptions,\n HTTPResult,\n Requester,\n} from './internals/httpUtils';\nimport {\n getUrl,\n httpRequest,\n jsonHttpRequester,\n resolveHTTPLinkOptions,\n} from './internals/httpUtils';\nimport {\n isFormData,\n isOctetType,\n type HTTPHeaders,\n type Operation,\n type TRPCLink,\n} from './types';\n\nexport type HTTPLinkOptions<TRoot extends AnyClientTypes> =\n HTTPLinkBaseOptions<TRoot> & {\n /**\n * Headers to be set on outgoing requests or a callback that of said headers\n * @see http://trpc.io/docs/client/headers\n */\n headers?:\n | HTTPHeaders\n | ((opts: { op: Operation }) => HTTPHeaders | Promise<HTTPHeaders>);\n };\n\nconst universalRequester: Requester = (opts) => {\n if ('input' in opts) {\n const { input } = opts;\n if (isFormData(input)) {\n if (opts.type !== 'mutation' && opts.methodOverride !== 'POST') {\n throw new Error('FormData is only supported for mutations');\n }\n\n return httpRequest({\n ...opts,\n // The browser will set this automatically and include the boundary= in it\n contentTypeHeader: undefined,\n getUrl,\n getBody: () => input,\n });\n }\n\n if (isOctetType(input)) {\n if (opts.type !== 'mutation' && opts.methodOverride !== 'POST') {\n throw new Error('Octet type input is only supported for mutations');\n }\n\n return httpRequest({\n ...opts,\n contentTypeHeader: 'application/octet-stream',\n getUrl,\n getBody: () => input,\n });\n }\n }\n\n return jsonHttpRequester(opts);\n};\n\n/**\n * @see https://trpc.io/docs/client/links/httpLink\n */\nexport function httpLink<TRouter extends AnyRouter = AnyRouter>(\n opts: HTTPLinkOptions<TRouter['_def']['_config']['$types']>,\n): TRPCLink<TRouter> {\n const resolvedOpts = resolveHTTPLinkOptions(opts);\n return () => {\n return (operationOpts) => {\n const { op } = operationOpts;\n return observable((observer) => {\n const { path, input, type } = op;\n /* istanbul ignore if -- @preserve */\n if (type === 'subscription') {\n throw new Error(\n 'Subscriptions are unsupported by `httpLink` - use `httpSubscriptionLink` or `wsLink`',\n );\n }\n\n const ac = new AbortController();\n const request = universalRequester({\n ...resolvedOpts,\n type,\n path,\n input,\n signal: raceAbortSignals(op.signal, ac.signal),\n headers() {\n if (!opts.headers) {\n return {};\n }\n if (typeof opts.headers === 'function') {\n return opts.headers({\n op,\n });\n }\n return opts.headers;\n },\n });\n let isDone = false;\n let meta: HTTPResult['meta'] | undefined = undefined;\n request\n .then((res) => {\n isDone = true;\n meta = res.meta;\n const transformed = transformResult(\n res.json,\n resolvedOpts.transformer.output,\n );\n\n if (!transformed.ok) {\n observer.error(\n TRPCClientError.from(transformed.error, {\n meta,\n }),\n );\n return;\n }\n observer.next({\n context: res.meta,\n result: transformed.result,\n });\n observer.complete();\n })\n .catch((cause) => {\n isDone = true;\n observer.error(TRPCClientError.from(cause, { meta }));\n });\n\n return () => {\n if (!isDone) {\n ac.abort();\n }\n };\n });\n };\n };\n}\n","import type { Maybe } from '@trpc/server/unstable-core-do-not-import';\n\n/**\n * Like `Promise.all()` but for abort signals\n * - When all signals have been aborted, the merged signal will be aborted\n * - If one signal is `null`, no signal will be aborted\n */\nexport function allAbortSignals(...signals: Maybe<AbortSignal>[]): AbortSignal {\n const ac = new AbortController();\n\n const count = signals.length;\n\n let abortedCount = 0;\n\n const onAbort = () => {\n if (++abortedCount === count) {\n ac.abort();\n }\n };\n\n for (const signal of signals) {\n if (signal?.aborted) {\n onAbort();\n } else {\n signal?.addEventListener('abort', onAbort, {\n once: true,\n });\n }\n }\n\n return ac.signal;\n}\n\n/**\n * Like `Promise.race` but for abort signals\n *\n * Basically, a ponyfill for\n * [`AbortSignal.any`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/any_static).\n */\nexport function raceAbortSignals(\n ...signals: Maybe<AbortSignal>[]\n): AbortSignal {\n const ac = new AbortController();\n\n for (const signal of signals) {\n if (signal?.aborted) {\n ac.abort();\n } else {\n signal?.addEventListener('abort', () => ac.abort(), { once: true });\n }\n }\n\n return ac.signal;\n}\n\nexport function abortSignalToPromise(signal: AbortSignal): Promise<never> {\n return new Promise((_, reject) => {\n if (signal.aborted) {\n reject(signal.reason);\n return;\n }\n signal.addEventListener(\n 'abort',\n () => {\n reject(signal.reason);\n },\n { once: true },\n );\n });\n}\n","import { observable } from '@trpc/server/observable';\nimport type { AnyRouter } from '@trpc/server/unstable-core-do-not-import';\nimport { createChain } from './internals/createChain';\nimport type { Operation, TRPCLink } from './types';\n\nfunction asArray<TType>(value: TType | TType[]) {\n return Array.isArray(value) ? value : [value];\n}\nexport function splitLink<TRouter extends AnyRouter = AnyRouter>(opts: {\n condition: (op: Operation) => boolean;\n /**\n * The link to execute next if the test function returns `true`.\n */\n true: TRPCLink<TRouter> | TRPCLink<TRouter>[];\n /**\n * The link to execute next if the test function returns `false`.\n */\n false: TRPCLink<TRouter> | TRPCLink<TRouter>[];\n}): TRPCLink<TRouter> {\n return (runtime) => {\n const yes = asArray(opts.true).map((link) => link(runtime));\n const no = asArray(opts.false).map((link) => link(runtime));\n return (props) => {\n return observable((observer) => {\n const links = opts.condition(props.op) ? yes : no;\n return createChain({ op: props.op, links }).subscribe(observer);\n });\n };\n };\n}\n","import { TRPCError } from '../error/TRPCError';\nimport type { ProcedureType } from '../procedure';\nimport { getProcedureAtPath, type AnyRouter } from '../router';\nimport { emptyObject, isObject } from '../utils';\nimport { parseConnectionParamsFromString } from './parseConnectionParams';\nimport type { TRPCAcceptHeader, TRPCRequestInfo } from './types';\n\nexport function getAcceptHeader(headers: Headers): TRPCAcceptHeader | null {\n return (\n (headers.get('trpc-accept') as TRPCAcceptHeader | null) ??\n (headers\n .get('accept')\n ?.split(',')\n .some((t) => t.trim() === 'application/jsonl')\n ? 'application/jsonl'\n : null)\n );\n}\n\ntype GetRequestInfoOptions = {\n path: string;\n req: Request;\n url: URL | null;\n searchParams: URLSearchParams;\n headers: Headers;\n router: AnyRouter;\n maxBatchSize?: number;\n};\n\ntype ContentTypeHandler = {\n isMatch: (opts: Request) => boolean;\n parse: (opts: GetRequestInfoOptions) => Promise<TRPCRequestInfo>;\n};\n\n/**\n * Memoize a function that takes no arguments\n * @internal\n */\nfunction memo<TReturn>(fn: () => Promise<TReturn>) {\n let promise: Promise<TReturn> | null = null;\n const sym = Symbol.for('@trpc/server/http/memo');\n let value: TReturn | typeof sym = sym;\n return {\n /**\n * Lazily read the value\n */\n read: async (): Promise<TReturn> => {\n if (value !== sym) {\n return value;\n }\n\n // dedupes promises and catches errors\n promise ??= fn().catch((cause) => {\n if (cause instanceof TRPCError) {\n throw cause;\n }\n throw new TRPCError({\n code: 'BAD_REQUEST',\n message: cause instanceof Error ? cause.message : 'Invalid input',\n cause,\n });\n });\n\n value = await promise;\n promise = null;\n\n return value;\n },\n /**\n * Get an already stored result\n */\n result: (): TReturn | undefined => {\n return value !== sym ? value : undefined;\n },\n };\n}\n\nconst jsonContentTypeHandler: ContentTypeHandler = {\n isMatch(req) {\n return !!req.headers.get('content-type')?.startsWith('application/json');\n },\n async parse(opts) {\n const { req } = opts;\n const isBatchCall = opts.searchParams.get('batch') === '1';\n const maxBatchSize = opts.maxBatchSize;\n\n const paths = isBatchCall ? opts.path.split(',') : [opts.path];\n if (\n isBatchCall &&\n typeof maxBatchSize === 'number' &&\n paths.length > maxBatchSize\n ) {\n throw new TRPCError({\n code: 'BAD_REQUEST',\n message: `Batch call exceeds maximum size`,\n });\n }\n\n type InputRecord = Record<number, unknown>;\n const getInputs = memo(async (): Promise<InputRecord> => {\n let inputs: unknown = undefined;\n if (req.method === 'GET') {\n const queryInput = opts.searchParams.get('input');\n if (queryInput) {\n inputs = JSON.parse(queryInput);\n }\n } else {\n inputs = await req.json();\n }\n if (inputs === undefined) {\n return emptyObject();\n }\n\n if (!isBatchCall) {\n const result: InputRecord = emptyObject();\n result[0] =\n opts.router._def._config.transformer.input.deserialize(inputs);\n return result;\n }\n\n if (!isObject(inputs)) {\n throw new TRPCError({\n code: 'BAD_REQUEST',\n message: '\"input\" needs to be an object when doing a batch call',\n });\n }\n const acc: InputRecord = emptyObject();\n for (const index of paths.keys()) {\n const input = inputs[index];\n if (input !== undefined) {\n acc[index] =\n opts.router._def._config.transformer.input.deserialize(input);\n }\n }\n\n return acc;\n });\n\n const calls = await Promise.all(\n paths.map(\n async (path, index): Promise<TRPCRequestInfo['calls'][number]> => {\n const procedure = await getProcedureAtPath(opts.router, path);\n return {\n batchIndex: index,\n path,\n procedure,\n getRawInput: async () => {\n const inputs = await getInputs.read();\n let input = inputs[index];\n\n if (procedure?._def.type === 'subscription') {\n const lastEventId =\n opts.headers.get('last-event-id') ??\n opts.searchParams.get('lastEventId') ??\n opts.searchParams.get('Last-Event-Id');\n\n if (lastEventId) {\n if (isObject(input)) {\n input = {\n ...input,\n lastEventId: lastEventId,\n };\n } else {\n input ??= {\n lastEventId: lastEventId,\n };\n }\n }\n }\n return input;\n },\n result: () => {\n return getInputs.result()?.[index];\n },\n };\n },\n ),\n );\n\n const types = new Set(\n calls.map((call) => call.procedure?._def.type).filter(Boolean),\n );\n\n /* istanbul ignore if -- @preserve */\n if (types.size > 1) {\n throw new TRPCError({\n code: 'BAD_REQUEST',\n message: `Cannot mix procedure types in call: ${Array.from(types).join(\n ', ',\n )}`,\n });\n }\n const type: ProcedureType | 'unknown' =\n types.values().next().value ?? 'unknown';\n\n const connectionParamsStr = opts.searchParams.get('connectionParams');\n\n const info: TRPCRequestInfo = {\n isBatchCall,\n accept: getAcceptHeader(req.headers),\n calls,\n type,\n connectionParams:\n connectionParamsStr === null\n ? null\n : parseConnectionParamsFromString(connectionParamsStr),\n signal: req.signal,\n url: opts.url,\n };\n return info;\n },\n};\n\nconst formDataContentTypeHandler: ContentTypeHandler = {\n isMatch(req) {\n return !!req.headers.get('content-type')?.startsWith('multipart/form-data');\n },\n async parse(opts) {\n const { req } = opts;\n if (req.method !== 'POST') {\n throw new TRPCError({\n code: 'METHOD_NOT_SUPPORTED',\n message:\n 'Only POST requests are supported for multipart/form-data requests',\n });\n }\n const getInputs = memo(async () => {\n const fd = await req.formData();\n return fd;\n });\n const procedure = await getProcedureAtPath(opts.router, opts.path);\n return {\n accept: null,\n calls: [\n {\n batchIndex: 0,\n path: opts.path,\n getRawInput: getInputs.read,\n result: getInputs.result,\n procedure,\n },\n ],\n isBatchCall: false,\n type: 'mutation',\n connectionParams: null,\n signal: req.signal,\n url: opts.url,\n };\n },\n};\n\nconst octetStreamContentTypeHandler: ContentTypeHandler = {\n isMatch(req) {\n return !!req.headers\n .get('content-type')\n ?.startsWith('application/octet-stream');\n },\n async parse(opts) {\n const { req } = opts;\n if (req.method !== 'POST') {\n throw new TRPCError({\n code: 'METHOD_NOT_SUPPORTED',\n message:\n 'Only POST requests are supported for application/octet-stream requests',\n });\n }\n const getInputs = memo(async () => {\n return req.body;\n });\n return {\n calls: [\n {\n batchIndex: 0,\n path: opts.path,\n getRawInput: getInputs.read,\n result: getInputs.result,\n procedure: await getProcedureAtPath(opts.router, opts.path),\n },\n ],\n isBatchCall: false,\n accept: null,\n type: 'mutation',\n connectionParams: null,\n signal: req.signal,\n url: opts.url,\n };\n },\n};\n\nconst handlers = [\n jsonContentTypeHandler,\n formDataContentTypeHandler,\n octetStreamContentTypeHandler,\n];\n\nfunction getContentTypeHandler(req: Request): ContentTypeHandler {\n const handler = handlers.find((handler) => handler.isMatch(req));\n if (handler) {\n return handler;\n }\n\n if (!handler && req.method === 'GET') {\n // fallback to JSON for get requests so GET-requests can be opened in browser easily\n return jsonContentTypeHandler;\n }\n\n throw new TRPCError({\n code: 'UNSUPPORTED_MEDIA_TYPE',\n message: req.headers.has('content-type')\n ? `Unsupported content-type \"${req.headers.get('content-type')}`\n : 'Missing content-type header',\n });\n}\n\nexport async function getRequestInfo(\n opts: GetRequestInfoOptions,\n): Promise<TRPCRequestInfo> {\n const handler = getContentTypeHandler(opts.req);\n return await handler.parse(opts);\n}\n","import { type TRPCRequestInfo } from '@trpc/server/http';\n\n/**\n * Get the result of a value or function that returns a value\n * It also optionally accepts typesafe arguments for the function\n */\nexport const resultOf = <T, TArgs extends any[]>(\n value: T | ((...args: TArgs) => T),\n ...args: TArgs\n): T => {\n return typeof value === 'function'\n ? (value as (...args: TArgs) => T)(...args)\n : value;\n};\n\n/**\n * A value that can be wrapped in callback\n */\nexport type CallbackOrValue<T> = T | (() => T | Promise<T>);\n\nexport interface UrlOptionsWithConnectionParams {\n /**\n * The URL to connect to (can be a function that returns a URL)\n */\n url: CallbackOrValue<string>;\n\n /**\n * Connection params that are available in `createContext()`\n * - For `wsLink`/`wsClient`, these are sent as the first message\n * - For `httpSubscriptionLink`, these are serialized as part of the URL under the `connectionParams` query\n */\n connectionParams?: CallbackOrValue<TRPCRequestInfo['connectionParams']>;\n}\n","import type {\n TRPCConnectionParamsMessage,\n TRPCRequestInfo,\n} from '@trpc/server/unstable-core-do-not-import';\nimport type {\n CallbackOrValue,\n UrlOptionsWithConnectionParams,\n} from '../../internals/urlWithConnectionParams';\nimport { resultOf } from '../../internals/urlWithConnectionParams';\nimport type { Encoder } from './encoder';\n\nexport class TRPCWebSocketClosedError extends Error {\n constructor(opts: { message: string; cause?: unknown }) {\n super(opts.message, {\n cause: opts.cause,\n });\n this.name = 'TRPCWebSocketClosedError';\n Object.setPrototypeOf(this, TRPCWebSocketClosedError.prototype);\n }\n}\n\n/**\n * Utility class for managing a timeout that can be started, stopped, and reset.\n * Useful for scenarios where the timeout duration is reset dynamically based on events.\n */\nexport class ResettableTimeout {\n private timeout: ReturnType<typeof setTimeout> | undefined;\n\n constructor(\n private readonly onTimeout: () => void,\n private readonly timeoutMs: number,\n ) {}\n\n /**\n * Resets the current timeout, restarting it with the same duration.\n * Does nothing if no timeout is active.\n */\n public reset() {\n if (!this.timeout) return;\n\n clearTimeout(this.timeout);\n this.timeout = setTimeout(this.onTimeout, this.timeoutMs);\n }\n\n public start() {\n clearTimeout(this.timeout);\n this.timeout = setTimeout(this.onTimeout, this.timeoutMs);\n }\n\n public stop() {\n clearTimeout(this.timeout);\n this.timeout = undefined;\n }\n}\n\n// Ponyfill for Promise.withResolvers https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers\nexport function withResolvers<T>() {\n let resolve: (value: T | PromiseLike<T>) => void;\n let reject: (reason?: any) => void;\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return { promise, resolve: resolve!, reject: reject! };\n}\n\n/**\n * Resolves a WebSocket URL and optionally appends connection parameters.\n *\n * If connectionParams are provided, appends 'connectionParams=1' query parameter.\n */\nexport async function prepareUrl(urlOptions: UrlOptionsWithConnectionParams) {\n const url = await resultOf(urlOptions.url);\n\n if (!urlOptions.connectionParams) return url;\n\n // append `?connectionParams=1` when connection params are used\n const prefix = url.includes('?') ? '&' : '?';\n const connectionParams = `${prefix}connectionParams=1`;\n\n return url + connectionParams;\n}\n\nexport async function buildConnectionMessage(\n connectionParams: CallbackOrValue<TRPCRequestInfo['connectionParams']>,\n encoder: Encoder,\n) {\n const message: TRPCConnectionParamsMessage = {\n method: 'connectionParams',\n data: await resultOf(connectionParams),\n };\n\n return encoder.encode(message);\n}\n","import type { AnyRootTypes, RootConfig } from './rootConfig';\nimport type { AnyRouter, inferRouterError } from './router';\nimport type {\n TRPCResponse,\n TRPCResponseMessage,\n TRPCResultMessage,\n} from './rpc';\nimport { isObject } from './utils';\n\n/**\n * @public\n */\nexport interface DataTransformer {\n serialize(object: any): any;\n deserialize(object: any): any;\n}\n\ninterface InputDataTransformer extends DataTransformer {\n /**\n * This function runs **on the client** before sending the data to the server.\n */\n serialize(object: any): any;\n /**\n * This function runs **on the server** to transform the data before it is passed to the resolver\n */\n deserialize(object: any): any;\n}\n\ninterface OutputDataTransformer extends DataTransformer {\n /**\n * This function runs **on the server** before sending the data to the client.\n */\n serialize(object: any): any;\n /**\n * This function runs **only on the client** to transform the data sent from the server.\n */\n deserialize(object: any): any;\n}\n\n/**\n * @public\n */\nexport interface CombinedDataTransformer {\n /**\n * Specify how the data sent from the client to the server should be transformed.\n */\n input: InputDataTransformer;\n /**\n * Specify how the data sent from the server to the client should be transformed.\n */\n output: OutputDataTransformer;\n}\n\n/**\n * @public\n */\nexport type CombinedDataTransformerClient = {\n input: Pick<CombinedDataTransformer['input'], 'serialize'>;\n output: Pick<CombinedDataTransformer['output'], 'deserialize'>;\n};\n\n/**\n * @public\n */\nexport type DataTransformerOptions = CombinedDataTransformer | DataTransformer;\n\n/**\n * @internal\n */\nexport function getDataTransformer(\n transformer: DataTransformerOptions,\n): CombinedDataTransformer {\n if ('input' in transformer) {\n return transformer;\n }\n return { input: transformer, output: transformer };\n}\n\n/**\n * @internal\n */\nexport const defaultTransformer: CombinedDataTransformer = {\n input: { serialize: (obj) => obj, deserialize: (obj) => obj },\n output: { serialize: (obj) => obj, deserialize: (obj) => obj },\n};\n\nfunction transformTRPCResponseItem<\n TResponseItem extends TRPCResponse | TRPCResponseMessage,\n>(config: RootConfig<AnyRootTypes>, item: TResponseItem): TResponseItem {\n if ('error' in item) {\n return {\n ...item,\n error: config.transformer.output.serialize(item.error),\n };\n }\n\n if ('data' in item.result) {\n return {\n ...item,\n result: {\n ...item.result,\n data: config.transformer.output.serialize(item.result.data),\n },\n };\n }\n\n return item;\n}\n\n/**\n * Takes a unserialized `TRPCResponse` and serializes it with the router's transformers\n **/\nexport function transformTRPCResponse<\n TResponse extends\n TRPCResponse | TRPCResponse[] | TRPCResponseMessage | TRPCResponseMessage[],\n>(config: RootConfig<AnyRootTypes>, itemOrItems: TResponse) {\n return Array.isArray(itemOrItems)\n ? itemOrItems.map((item) => transformTRPCResponseItem(config, item))\n : transformTRPCResponseItem(config, itemOrItems);\n}\n\n// FIXME:\n// - the generics here are probably unnecessary\n// - the RPC-spec could probably be simplified to combine HTTP + WS\n/** @internal */\nfunction transformResultInner<TRouter extends AnyRouter, TOutput>(\n response:\n | TRPCResponse<TOutput, inferRouterError<TRouter>>\n | TRPCResponseMessage<TOutput, inferRouterError<TRouter>>,\n transformer: DataTransformer,\n) {\n if ('error' in response) {\n const error = transformer.deserialize(\n response.error,\n ) as inferRouterError<TRouter>;\n return {\n ok: false,\n error: {\n ...response,\n error,\n },\n } as const;\n }\n\n const result = {\n ...response.result,\n ...((!response.result.type || response.result.type === 'data') && {\n type: 'data',\n data: transformer.deserialize(response.result.data),\n }),\n } as TRPCResultMessage<TOutput>['result'];\n return { ok: true, result } as const;\n}\n\nclass TransformResultError extends Error {\n constructor() {\n super('Unable to transform response from server');\n }\n}\n\n/**\n * Transforms and validates that the result is a valid TRPCResponse\n * @internal\n */\nexport function transformResult<TRouter extends AnyRouter, TOutput>(\n response:\n | TRPCResponse<TOutput, inferRouterError<TRouter>>\n | TRPCResponseMessage<TOutput, inferRouterError<TRouter>>,\n transformer: DataTransformer,\n): ReturnType<typeof transformResultInner> {\n let result: ReturnType<typeof transformResultInner>;\n try {\n // Use the data transformers on the JSON-response\n result = transformResultInner(response, transformer);\n } catch {\n throw new TransformResultError();\n }\n\n // check that output of the transformers is a valid TRPCResponse\n if (\n !result.ok &&\n (!isObject(result.error.error) ||\n typeof result.error.error['code'] !== 'number')\n ) {\n throw new TransformResultError();\n }\n if (result.ok && !isObject(result.result)) {\n throw new TransformResultError();\n }\n return result;\n}\n","import type {\n AnyClientTypes,\n CombinedDataTransformer,\n Maybe,\n ProcedureType,\n TRPCAcceptHeader,\n TRPCResponse,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { getFetch } from '../../getFetch';\nimport type {\n FetchEsque,\n RequestInitEsque,\n ResponseEsque,\n} from '../../internals/types';\nimport type { TransformerOptions } from '../../unstable-internals';\nimport { getTransformer } from '../../unstable-internals';\nimport type { HTTPHeaders } from '../types';\n\n/**\n * @internal\n */\nexport type HTTPLinkBaseOptions<\n TRoot extends Pick<AnyClientTypes, 'transformer'>,\n> = {\n url: string | URL;\n /**\n * Add ponyfill for fetch\n */\n fetch?: FetchEsque;\n /**\n * Send all requests `as POST`s requests regardless of the procedure type\n * The HTTP handler must separately allow overriding the method. See:\n * @see https://trpc.io/docs/rpc\n */\n methodOverride?: 'POST';\n} & TransformerOptions<TRoot>;\n\nexport interface ResolvedHTTPLinkOptions {\n url: string;\n fetch?: FetchEsque;\n transformer: CombinedDataTransformer;\n methodOverride?: 'POST';\n}\n\nexport function resolveHTTPLinkOptions(\n opts: HTTPLinkBaseOptions<AnyClientTypes>,\n): ResolvedHTTPLinkOptions {\n return {\n url: opts.url.toString(),\n fetch: opts.fetch,\n transformer: getTransformer(opts.transformer),\n methodOverride: opts.methodOverride,\n };\n}\n\n// https://github.com/trpc/trpc/pull/669\nfunction arrayToDict(array: unknown[]) {\n const dict: Record<number, unknown> = {};\n for (let index = 0; index < array.length; index++) {\n const element = array[index];\n dict[index] = element;\n }\n return dict;\n}\n\nconst METHOD = {\n query: 'GET',\n mutation: 'POST',\n subscription: 'PATCH',\n} as const;\n\nexport interface HTTPResult {\n json: TRPCResponse;\n meta: {\n response: ResponseEsque;\n responseJSON?: unknown;\n };\n}\n\ntype GetInputOptions = {\n transformer: CombinedDataTransformer;\n} & ({ input: unknown } | { inputs: unknown[] });\n\nexport function getInput(opts: GetInputOptions) {\n return 'input' in opts\n ? opts.transformer.input.serialize(opts.input)\n : arrayToDict(\n opts.inputs.map((_input) => opts.transformer.input.serialize(_input)),\n );\n}\n\nexport type HTTPBaseRequestOptions = GetInputOptions &\n ResolvedHTTPLinkOptions & {\n type: ProcedureType;\n path: string;\n signal: Maybe<AbortSignal>;\n };\n\ntype GetUrl = (opts: HTTPBaseRequestOptions) => string;\ntype GetBody = (opts: HTTPBaseRequestOptions) => RequestInitEsque['body'];\n\nexport type ContentOptions = {\n trpcAcceptHeader?: TRPCAcceptHeader;\n trpcAcceptHeaderKey?: 'trpc-accept' | 'accept';\n contentTypeHeader?: string;\n getUrl: GetUrl;\n getBody: GetBody;\n};\n\nexport const getUrl: GetUrl = (opts) => {\n const parts = opts.url.split('?') as [string, string?];\n const base = parts[0].replace(/\\/$/, ''); // Remove any trailing slashes\n\n let url = base + '/' + opts.path;\n const queryParts: string[] = [];\n\n if (parts[1]) {\n queryParts.push(parts[1]);\n }\n if ('inputs' in opts) {\n queryParts.push('batch=1');\n }\n if (opts.type === 'query' || opts.type === 'subscription') {\n const input = getInput(opts);\n if (input !== undefined && opts.methodOverride !== 'POST') {\n queryParts.push(`input=${encodeURIComponent(JSON.stringify(input))}`);\n }\n }\n if (queryParts.length) {\n url += '?' + queryParts.join('&');\n }\n return url;\n};\n\nexport const getBody: GetBody = (opts) => {\n if (opts.type === 'query' && opts.methodOverride !== 'POST') {\n return undefined;\n }\n const input = getInput(opts);\n return input !== undefined ? JSON.stringify(input) : undefined;\n};\n\nexport type Requester = (\n opts: HTTPBaseRequestOptions & {\n headers: () => HTTPHeaders | Promise<HTTPHeaders>;\n },\n) => Promise<HTTPResult>;\n\nexport const jsonHttpRequester: Requester = (opts) => {\n return httpRequest({\n ...opts,\n contentTypeHeader: 'application/json',\n getUrl,\n getBody,\n });\n};\n\n/**\n * Polyfill for DOMException with AbortError name\n */\nclass AbortError extends Error {\n constructor() {\n const name = 'AbortError';\n super(name);\n this.name = name;\n this.message = name;\n }\n}\n\nexport type HTTPRequestOptions = ContentOptions &\n HTTPBaseRequestOptions & {\n headers: () => HTTPHeaders | Promise<HTTPHeaders>;\n };\n\n/**\n * Polyfill for `signal.throwIfAborted()`\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/throwIfAborted\n */\nconst throwIfAborted = (signal: Maybe<AbortSignal>) => {\n if (!signal?.aborted) {\n return;\n }\n // If available, use the native implementation\n signal.throwIfAborted?.();\n\n // If we have `DOMException`, use it\n if (typeof DOMException !== 'undefined') {\n throw new DOMException('AbortError', 'AbortError');\n }\n\n // Otherwise, use our own implementation\n throw new AbortError();\n};\n\nexport async function fetchHTTPResponse(opts: HTTPRequestOptions) {\n throwIfAborted(opts.signal);\n\n const url = opts.getUrl(opts);\n const body = opts.getBody(opts);\n const method = opts.methodOverride ?? METHOD[opts.type];\n const resolvedHeaders = await (async () => {\n const heads = await opts.headers();\n if (Symbol.iterator in heads) {\n return Object.fromEntries(heads);\n }\n return heads;\n })();\n const headers = {\n ...(opts.contentTypeHeader && method !== 'GET'\n ? { 'content-type': opts.contentTypeHeader }\n : {}),\n ...(opts.trpcAcceptHeader\n ? { [opts.trpcAcceptHeaderKey ?? 'trpc-accept']: opts.trpcAcceptHeader }\n : undefined),\n ...resolvedHeaders,\n };\n\n return getFetch(opts.fetch)(url, {\n method,\n signal: opts.signal,\n body,\n headers,\n });\n}\n\nexport async function httpRequest(\n opts: HTTPRequestOptions,\n): Promise<HTTPResult> {\n const meta = {} as HTTPResult['meta'];\n\n const res = await fetchHTTPResponse(opts);\n meta.response = res;\n\n const json = await res.json();\n\n meta.responseJSON = json;\n\n return {\n json: json as TRPCResponse,\n meta,\n };\n}\n","import type { TRPCError } from '../error/TRPCError';\nimport type { TRPC_ERROR_CODES_BY_KEY, TRPCResponse } from '../rpc';\nimport { TRPC_ERROR_CODES_BY_NUMBER } from '../rpc';\nimport type { InvertKeyValue, ValueOf } from '../types';\nimport { isObject } from '../utils';\n\nexport const JSONRPC2_TO_HTTP_CODE: Record<\n keyof typeof TRPC_ERROR_CODES_BY_KEY,\n number\n> = {\n PARSE_ERROR: 400,\n BAD_REQUEST: 400,\n UNAUTHORIZED: 401,\n PAYMENT_REQUIRED: 402,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n METHOD_NOT_SUPPORTED: 405,\n TIMEOUT: 408,\n CONFLICT: 409,\n PRECONDITION_FAILED: 412,\n PAYLOAD_TOO_LARGE: 413,\n UNSUPPORTED_MEDIA_TYPE: 415,\n UNPROCESSABLE_CONTENT: 422,\n PRECONDITION_REQUIRED: 428,\n TOO_MANY_REQUESTS: 429,\n CLIENT_CLOSED_REQUEST: 499,\n INTERNAL_SERVER_ERROR: 500,\n NOT_IMPLEMENTED: 501,\n BAD_GATEWAY: 502,\n SERVICE_UNAVAILABLE: 503,\n GATEWAY_TIMEOUT: 504,\n};\n\nexport const HTTP_CODE_TO_JSONRPC2: InvertKeyValue<\n typeof JSONRPC2_TO_HTTP_CODE\n> = {\n 400: 'BAD_REQUEST',\n 401: 'UNAUTHORIZED',\n 402: 'PAYMENT_REQUIRED',\n 403: 'FORBIDDEN',\n 404: 'NOT_FOUND',\n 405: 'METHOD_NOT_SUPPORTED',\n 408: 'TIMEOUT',\n 409: 'CONFLICT',\n 412: 'PRECONDITION_FAILED',\n 413: 'PAYLOAD_TOO_LARGE',\n 415: 'UNSUPPORTED_MEDIA_TYPE',\n 422: 'UNPROCESSABLE_CONTENT',\n 428: 'PRECONDITION_REQUIRED',\n 429: 'TOO_MANY_REQUESTS',\n 499: 'CLIENT_CLOSED_REQUEST',\n 500: 'INTERNAL_SERVER_ERROR',\n 501: 'NOT_IMPLEMENTED',\n 502: 'BAD_GATEWAY',\n 503: 'SERVICE_UNAVAILABLE',\n 504: 'GATEWAY_TIMEOUT',\n} as const;\n\nexport function getStatusCodeFromKey(\n code: keyof typeof TRPC_ERROR_CODES_BY_KEY,\n) {\n return JSONRPC2_TO_HTTP_CODE[code] ?? 500;\n}\n\nexport function getStatusKeyFromCode(\n code: keyof typeof HTTP_CODE_TO_JSONRPC2,\n): ValueOf<typeof HTTP_CODE_TO_JSONRPC2> {\n return HTTP_CODE_TO_JSONRPC2[code] ?? 'INTERNAL_SERVER_ERROR';\n}\n\nexport function getHTTPStatusCode(json: TRPCResponse | TRPCResponse[]) {\n const arr = Array.isArray(json) ? json : [json];\n const httpStatuses = new Set<number>(\n arr.map((res) => {\n if ('error' in res && isObject(res.error.data)) {\n if (typeof res.error.data?.['httpStatus'] === 'number') {\n return res.error.data['httpStatus'];\n }\n const code = TRPC_ERROR_CODES_BY_NUMBER[res.error.code];\n return getStatusCodeFromKey(code);\n }\n return 200;\n }),\n );\n\n if (httpStatuses.size !== 1) {\n return 207;\n }\n\n const httpStatus = httpStatuses.values().next().value;\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return httpStatus!;\n}\n\nexport function getHTTPStatusCodeFromError(error: TRPCError) {\n return getStatusCodeFromKey(error.code);\n}\n","import type { InvertKeyValue, ValueOf } from '../types';\n\n// reference: https://www.jsonrpc.org/specification\n\n/**\n * JSON-RPC 2.0 Error codes\n *\n * `-32000` to `-32099` are reserved for implementation-defined server-errors.\n * For tRPC we're copying the last digits of HTTP 4XX errors.\n */\nexport const TRPC_ERROR_CODES_BY_KEY = {\n /**\n * Invalid JSON was received by the server.\n * An error occurred on the server while parsing the JSON text.\n */\n PARSE_ERROR: -32700,\n /**\n * The JSON sent is not a valid Request object.\n */\n BAD_REQUEST: -32600, // 400\n\n // Internal JSON-RPC error\n INTERNAL_SERVER_ERROR: -32603, // 500\n NOT_IMPLEMENTED: -32603, // 501\n BAD_GATEWAY: -32603, // 502\n SERVICE_UNAVAILABLE: -32603, // 503\n GATEWAY_TIMEOUT: -32603, // 504\n\n // Implementation specific errors\n UNAUTHORIZED: -32001, // 401\n PAYMENT_REQUIRED: -32002, // 402\n FORBIDDEN: -32003, // 403\n NOT_FOUND: -32004, // 404\n METHOD_NOT_SUPPORTED: -32005, // 405\n TIMEOUT: -32008, // 408\n CONFLICT: -32009, // 409\n PRECONDITION_FAILED: -32012, // 412\n PAYLOAD_TOO_LARGE: -32013, // 413\n UNSUPPORTED_MEDIA_TYPE: -32015, // 415\n UNPROCESSABLE_CONTENT: -32022, // 422\n PRECONDITION_REQUIRED: -32028, // 428\n TOO_MANY_REQUESTS: -32029, // 429\n CLIENT_CLOSED_REQUEST: -32099, // 499\n} as const;\n\n// pure\nexport const TRPC_ERROR_CODES_BY_NUMBER: InvertKeyValue<\n typeof TRPC_ERROR_CODES_BY_KEY\n> = {\n [-32700]: 'PARSE_ERROR',\n [-32600]: 'BAD_REQUEST',\n [-32603]: 'INTERNAL_SERVER_ERROR',\n [-32001]: 'UNAUTHORIZED',\n [-32002]: 'PAYMENT_REQUIRED',\n [-32003]: 'FORBIDDEN',\n [-32004]: 'NOT_FOUND',\n [-32005]: 'METHOD_NOT_SUPPORTED',\n [-32008]: 'TIMEOUT',\n [-32009]: 'CONFLICT',\n [-32012]: 'PRECONDITION_FAILED',\n [-32013]: 'PAYLOAD_TOO_LARGE',\n [-32015]: 'UNSUPPORTED_MEDIA_TYPE',\n [-32022]: 'UNPROCESSABLE_CONTENT',\n [-32028]: 'PRECONDITION_REQUIRED',\n [-32029]: 'TOO_MANY_REQUESTS',\n [-32099]: 'CLIENT_CLOSED_REQUEST',\n};\n\nexport type TRPC_ERROR_CODE_NUMBER = ValueOf<typeof TRPC_ERROR_CODES_BY_KEY>;\nexport type TRPC_ERROR_CODE_KEY = keyof typeof TRPC_ERROR_CODES_BY_KEY;\n\n/**\n * tRPC error codes that are considered retryable\n * With out of the box SSE, the client will reconnect when these errors are encountered\n */\nexport const retryableRpcCodes: TRPC_ERROR_CODE_NUMBER[] = [\n TRPC_ERROR_CODES_BY_KEY.BAD_GATEWAY,\n TRPC_ERROR_CODES_BY_KEY.SERVICE_UNAVAILABLE,\n TRPC_ERROR_CODES_BY_KEY.GATEWAY_TIMEOUT,\n TRPC_ERROR_CODES_BY_KEY.INTERNAL_SERVER_ERROR,\n];\n","import type { AnyRouter } from '@trpc/server/unstable-core-do-not-import';\nimport type { CreateTRPCClientOptions } from './internals/TRPCUntypedClient';\nimport { TRPCUntypedClient } from './internals/TRPCUntypedClient';\n\nexport function createTRPCUntypedClient<TRouter extends AnyRouter>(\n opts: CreateTRPCClientOptions<TRouter>,\n): TRPCUntypedClient<TRouter> {\n return new TRPCUntypedClient(opts);\n}\n\nexport type {\n CreateTRPCClientOptions,\n TRPCRequestOptions,\n} from './internals/TRPCUntypedClient';\nexport { TRPCUntypedClient } from './internals/TRPCUntypedClient';\n","/* eslint-disable @typescript-eslint/no-non-null-assertion */\nimport type { Unsubscribable } from '@trpc/server/observable';\nimport type {\n AnyProcedure,\n AnyRouter,\n inferClientTypes,\n inferProcedureInput,\n InferrableClientTypes,\n inferTransformedProcedureOutput,\n ProcedureType,\n RouterRecord,\n} from '@trpc/server/unstable-core-do-not-import';\nimport {\n createFlatProxy,\n createRecursiveProxy,\n} from '@trpc/server/unstable-core-do-not-import';\nimport type { CreateTRPCClientOptions } from './createTRPCUntypedClient';\nimport type { TRPCSubscriptionObserver } from './internals/TRPCUntypedClient';\nimport { TRPCUntypedClient } from './internals/TRPCUntypedClient';\nimport type { TRPCProcedureOptions } from './internals/types';\nimport type { TRPCClientError } from './TRPCClientError';\n\n/**\n * @public\n * @deprecated use {@link TRPCClient} instead, will be removed in v12\n **/\nexport type inferRouterClient<TRouter extends AnyRouter> = TRPCClient<TRouter>;\n\n/**\n * @public\n * @deprecated use {@link TRPCClient} instead, will be removed in v12\n **/\nexport type CreateTRPCClient<TRouter extends AnyRouter> = TRPCClient<TRouter>;\n\nconst untypedClientSymbol = Symbol.for('trpc_untypedClient');\n\n/**\n * @public\n **/\nexport type TRPCClient<TRouter extends AnyRouter> = DecoratedProcedureRecord<\n {\n transformer: TRouter['_def']['_config']['$types']['transformer'];\n errorShape: TRouter['_def']['_config']['$types']['errorShape'];\n },\n TRouter['_def']['record']\n> & {\n [untypedClientSymbol]: TRPCUntypedClient<TRouter>;\n};\n\n/** @internal */\nexport type TRPCResolverDef = {\n input: any;\n output: any;\n transformer: boolean;\n errorShape: any;\n};\n\ntype coerceAsyncGeneratorToIterable<T> =\n T extends AsyncGenerator<infer $T, infer $Return, infer $Next>\n ? AsyncIterable<$T, $Return, $Next>\n : T;\n\n/** @internal */\nexport type Resolver<TDef extends TRPCResolverDef> = (\n input: TDef['input'],\n opts?: TRPCProcedureOptions,\n) => Promise<coerceAsyncGeneratorToIterable<TDef['output']>>;\n\n/** @internal */\nexport type SubscriptionResolver<TDef extends TRPCResolverDef> = (\n input: TDef['input'],\n opts: Partial<\n TRPCSubscriptionObserver<TDef['output'], TRPCClientError<TDef>>\n > &\n TRPCProcedureOptions,\n) => Unsubscribable;\n\ntype DecorateProcedure<\n TType extends ProcedureType,\n TDef extends TRPCResolverDef,\n> = TType extends 'query'\n ? {\n query: Resolver<TDef>;\n }\n : TType extends 'mutation'\n ? {\n mutate: Resolver<TDef>;\n }\n : TType extends 'subscription'\n ? {\n subscribe: SubscriptionResolver<TDef>;\n }\n : never;\n\n/**\n * @internal\n */\ntype DecoratedProcedureRecord<\n TRoot extends InferrableClientTypes,\n TRecord extends RouterRecord,\n> = {\n [TKey in keyof TRecord]: TRecord[TKey] extends infer $Value\n ? $Value extends AnyProcedure\n ? DecorateProcedure<\n $Value['_def']['type'],\n {\n input: inferProcedureInput<$Value>;\n output: inferTransformedProcedureOutput<\n inferClientTypes<TRoot>,\n $Value\n >;\n errorShape: inferClientTypes<TRoot>['errorShape'];\n transformer: inferClientTypes<TRoot>['transformer'];\n }\n >\n : $Value extends RouterRecord\n ? DecoratedProcedureRecord<TRoot, $Value>\n : never\n : never;\n};\n\nconst clientCallTypeMap: Record<\n keyof DecorateProcedure<any, any>,\n ProcedureType\n> = {\n query: 'query',\n mutate: 'mutation',\n subscribe: 'subscription',\n};\n\n/** @internal */\nexport const clientCallTypeToProcedureType = (\n clientCallType: string,\n): ProcedureType => {\n return clientCallTypeMap[clientCallType as keyof typeof clientCallTypeMap];\n};\n\n/**\n * @internal\n */\nexport function createTRPCClientProxy<TRouter extends AnyRouter>(\n client: TRPCUntypedClient<TRouter>,\n): TRPCClient<TRouter> {\n const proxy = createRecursiveProxy<TRPCClient<TRouter>>(({ path, args }) => {\n const pathCopy = [...path];\n const procedureType = clientCallTypeToProcedureType(pathCopy.pop()!);\n\n const fullPath = pathCopy.join('.');\n\n return (client[procedureType] as any)(fullPath, ...(args as any));\n });\n return createFlatProxy<TRPCClient<TRouter>>((key) => {\n if (key === untypedClientSymbol) {\n return client;\n }\n return proxy[key];\n });\n}\n\nexport function createTRPCClient<TRouter extends AnyRouter>(\n opts: CreateTRPCClientOptions<TRouter>,\n): TRPCClient<TRouter> {\n const client = new TRPCUntypedClient(opts);\n const proxy = createTRPCClientProxy<TRouter>(client);\n return proxy;\n}\n\n/**\n * Get an untyped client from a proxy client\n * @internal\n */\nexport function getUntypedClient<TRouter extends AnyRouter>(\n client: TRPCClient<TRouter>,\n): TRPCUntypedClient<TRouter> {\n return client[untypedClientSymbol];\n}\n","import type { AnyTRPCRouter, inferRouterError } from '@trpc/server';\nimport type { Observer } from '@trpc/server/observable';\nimport type {\n TRPCClientOutgoingMessage,\n TRPCResponseMessage,\n} from '@trpc/server/unstable-core-do-not-import';\nimport type { TRPCClientError } from '../../../TRPCClientError';\nimport { withResolvers } from './utils';\n\nexport type TCallbacks = Observer<\n TRPCResponseMessage<unknown, inferRouterError<AnyTRPCRouter>>,\n TRPCClientError<AnyTRPCRouter>\n>;\n\ntype MessageId = string;\ntype MessageIdLike = string | number | null;\n\n/**\n * Represents a WebSocket request managed by the RequestManager.\n * Combines the network message, a utility promise (`end`) that mirrors the lifecycle\n * handled by `callbacks`, and a set of state monitoring callbacks.\n */\ninterface Request {\n message: TRPCClientOutgoingMessage;\n end: Promise<void>;\n callbacks: TCallbacks;\n}\n\n/**\n * Manages WebSocket requests, tracking their lifecycle and providing utility methods\n * for handling outgoing and pending requests.\n *\n * - **Outgoing requests**: Requests that are queued and waiting to be sent.\n * - **Pending requests**: Requests that have been sent and are in flight awaiting a response.\n * For subscriptions, multiple responses may be received until the subscription is closed.\n */\nexport class RequestManager {\n /**\n * Stores requests that are outgoing, meaning they are registered but not yet sent over the WebSocket.\n */\n private outgoingRequests = new Array<Request & { id: MessageId }>();\n\n /**\n * Stores requests that are pending (in flight), meaning they have been sent over the WebSocket\n * and are awaiting responses. For subscriptions, this includes requests\n * that may receive multiple responses.\n */\n private pendingRequests: Record<MessageId, Request> = {};\n\n /**\n * Registers a new request by adding it to the outgoing queue and setting up\n * callbacks for lifecycle events such as completion or error.\n *\n * @param message - The outgoing message to be sent.\n * @param callbacks - Callback functions to observe the request's state.\n * @returns A cleanup function to manually remove the request.\n */\n public register(message: TRPCClientOutgoingMessage, callbacks: TCallbacks) {\n const { promise: end, resolve } = withResolvers<void>();\n\n this.outgoingRequests.push({\n id: String(message.id),\n message,\n end,\n callbacks: {\n next: callbacks.next,\n complete: () => {\n callbacks.complete();\n resolve();\n },\n error: (e) => {\n callbacks.error(e);\n resolve();\n },\n },\n });\n\n return () => {\n this.delete(message.id);\n callbacks.complete();\n resolve();\n };\n }\n\n /**\n * Deletes a request from both the outgoing and pending collections, if it exists.\n */\n public delete(messageId: MessageIdLike) {\n if (messageId === null) return;\n\n this.outgoingRequests = this.outgoingRequests.filter(\n ({ id }) => id !== String(messageId),\n );\n delete this.pendingRequests[String(messageId)];\n }\n\n /**\n * Moves all outgoing requests to the pending state and clears the outgoing queue.\n *\n * The caller is expected to handle the actual sending of the requests\n * (e.g., sending them over the network) after this method is called.\n *\n * @returns The list of requests that were transitioned to the pending state.\n */\n public flush() {\n const requests = this.outgoingRequests;\n this.outgoingRequests = [];\n\n for (const request of requests) {\n this.pendingRequests[request.id] = request;\n }\n return requests;\n }\n\n /**\n * Retrieves all currently pending requests, which are in flight awaiting responses\n * or handling ongoing subscriptions.\n */\n public getPendingRequests() {\n return Object.values(this.pendingRequests);\n }\n\n /**\n * Retrieves a specific pending request by its message ID.\n */\n public getPendingRequest(messageId: MessageIdLike) {\n if (messageId === null) return null;\n\n return this.pendingRequests[String(messageId)];\n }\n\n /**\n * Retrieves all outgoing requests, which are waiting to be sent.\n */\n public getOutgoingRequests() {\n return this.outgoingRequests;\n }\n\n /**\n * Retrieves all requests, both outgoing and pending, with their respective states.\n *\n * @returns An array of all requests with their state (\"outgoing\" or \"pending\").\n */\n public getRequests() {\n return [\n ...this.getOutgoingRequests().map((request) => ({\n state: 'outgoing' as const,\n message: request.message,\n end: request.end,\n callbacks: request.callbacks,\n })),\n ...this.getPendingRequests().map((request) => ({\n state: 'pending' as const,\n message: request.message,\n end: request.end,\n callbacks: request.callbacks,\n })),\n ];\n }\n\n /**\n * Checks if there are any pending requests, including ongoing subscriptions.\n */\n public hasPendingRequests() {\n return this.getPendingRequests().length > 0;\n }\n\n /**\n * Checks if there are any pending subscriptions\n */\n public hasPendingSubscriptions() {\n return this.getPendingRequests().some(\n (request) => request.message.method === 'subscription',\n );\n }\n\n /**\n * Checks if there are any outgoing requests waiting to be sent.\n */\n public hasOutgoingRequests() {\n return this.outgoingRequests.length > 0;\n }\n}\n","import type { AnyRouter, ProcedureType } from '@trpc/server';\nimport { observable } from '@trpc/server/observable';\nimport { transformResult } from '@trpc/server/unstable-core-do-not-import';\nimport type { BatchLoader } from '../internals/dataLoader';\nimport { dataLoader } from '../internals/dataLoader';\nimport { allAbortSignals, raceAbortSignals } from '../internals/signals';\nimport type { NonEmptyArray } from '../internals/types';\nimport { TRPCClientError } from '../TRPCClientError';\nimport type { HTTPBatchLinkOptions } from './HTTPBatchLinkOptions';\nimport type { HTTPResult } from './internals/httpUtils';\nimport {\n getUrl,\n jsonHttpRequester,\n resolveHTTPLinkOptions,\n} from './internals/httpUtils';\nimport type { Operation, TRPCLink } from './types';\n\n/**\n * @see https://trpc.io/docs/client/links/httpBatchLink\n */\nexport function httpBatchLink<TRouter extends AnyRouter>(\n opts: HTTPBatchLinkOptions<TRouter['_def']['_config']['$types']>,\n): TRPCLink<TRouter> {\n const resolvedOpts = resolveHTTPLinkOptions(opts);\n const maxURLLength = opts.maxURLLength ?? Infinity;\n const maxItems = opts.maxItems ?? Infinity;\n\n return () => {\n const batchLoader = (\n type: ProcedureType,\n ): BatchLoader<Operation, HTTPResult> => {\n return {\n validate(batchOps) {\n if (maxURLLength === Infinity && maxItems === Infinity) {\n // escape hatch for quick calcs\n return true;\n }\n if (batchOps.length > maxItems) {\n return false;\n }\n const path = batchOps.map((op) => op.path).join(',');\n const inputs = batchOps.map((op) => op.input);\n\n const url = getUrl({\n ...resolvedOpts,\n type,\n path,\n inputs,\n signal: null,\n });\n\n return url.length <= maxURLLength;\n },\n async fetch(batchOps) {\n const path = batchOps.map((op) => op.path).join(',');\n const inputs = batchOps.map((op) => op.input);\n const signal = allAbortSignals(...batchOps.map((op) => op.signal));\n\n const res = await jsonHttpRequester({\n ...resolvedOpts,\n path,\n inputs,\n type,\n headers() {\n if (!opts.headers) {\n return {};\n }\n if (typeof opts.headers === 'function') {\n return opts.headers({\n opList: batchOps as NonEmptyArray<Operation>,\n });\n }\n return opts.headers;\n },\n signal,\n });\n const resJSON = Array.isArray(res.json)\n ? res.json\n : batchOps.map(() => res.json);\n const result = resJSON.map((item) => ({\n meta: res.meta,\n json: item,\n }));\n return result;\n },\n };\n };\n\n const query = dataLoader(batchLoader('query'));\n const mutation = dataLoader(batchLoader('mutation'));\n\n const loaders = { query, mutation };\n return ({ op }) => {\n return observable((observer) => {\n /* istanbul ignore if -- @preserve */\n if (op.type === 'subscription') {\n throw new Error(\n 'Subscriptions are unsupported by `httpLink` - use `httpSubscriptionLink` or `wsLink`',\n );\n }\n const ac = new AbortController();\n const loader = loaders[op.type];\n const promise = loader.load({\n ...op,\n signal: raceAbortSignals(op.signal, ac.signal),\n });\n\n let isDone = false;\n let _res = undefined as HTTPResult | undefined;\n promise\n .then((res) => {\n isDone = true;\n _res = res;\n const transformed = transformResult(\n res.json,\n resolvedOpts.transformer.output,\n );\n\n if (!transformed.ok) {\n observer.error(\n TRPCClientError.from(transformed.error, {\n meta: res.meta,\n }),\n );\n return;\n }\n observer.next({\n context: res.meta,\n result: transformed.result,\n });\n observer.complete();\n })\n .catch((err) => {\n isDone = true;\n observer.error(\n TRPCClientError.from(err, {\n meta: _res?.meta,\n }),\n );\n });\n\n return () => {\n if (!isDone) {\n ac.abort();\n }\n };\n });\n };\n };\n}\n","import type { Observable } from '../observable';\nimport { createRecursiveProxy } from './createProxy';\nimport { defaultFormatter } from './error/formatter';\nimport { getTRPCErrorFromUnknown, TRPCError } from './error/TRPCError';\nimport type {\n AnyProcedure,\n ErrorHandlerOptions,\n inferProcedureInput,\n inferProcedureOutput,\n LegacyObservableSubscriptionProcedure,\n} from './procedure';\nimport type { ProcedureCallOptions } from './procedureBuilder';\nimport type { AnyRootTypes, RootConfig } from './rootConfig';\nimport { defaultTransformer } from './transformer';\nimport type { MaybePromise, ValueOf } from './types';\nimport {\n emptyObject,\n isFunction,\n isObject,\n mergeWithoutOverrides,\n} from './utils';\n\nexport interface RouterRecord {\n [key: string]: AnyProcedure | RouterRecord;\n}\n\ntype DecorateProcedure<TProcedure extends AnyProcedure> = (\n input: inferProcedureInput<TProcedure>,\n) => Promise<\n TProcedure['_def']['type'] extends 'subscription'\n ? TProcedure extends LegacyObservableSubscriptionProcedure<any>\n ? Observable<inferProcedureOutput<TProcedure>, TRPCError>\n : inferProcedureOutput<TProcedure>\n : inferProcedureOutput<TProcedure>\n>;\n\n/**\n * @internal\n */\nexport type DecorateRouterRecord<TRecord extends RouterRecord> = {\n [TKey in keyof TRecord]: TRecord[TKey] extends infer $Value\n ? $Value extends AnyProcedure\n ? DecorateProcedure<$Value>\n : $Value extends RouterRecord\n ? DecorateRouterRecord<$Value>\n : never\n : never;\n};\n\n/**\n * @internal\n */\n\nexport type RouterCallerErrorHandler<TContext> = (\n opts: ErrorHandlerOptions<TContext>,\n) => void;\n\n/**\n * @internal\n */\nexport type RouterCaller<\n TRoot extends AnyRootTypes,\n TRecord extends RouterRecord,\n> = (\n /**\n * @note\n * If passing a function, we recommend it's a cached function\n * e.g. wrapped in `React.cache` to avoid unnecessary computations\n */\n ctx: TRoot['ctx'] | (() => MaybePromise<TRoot['ctx']>),\n options?: {\n onError?: RouterCallerErrorHandler<TRoot['ctx']>;\n signal?: AbortSignal;\n },\n) => DecorateRouterRecord<TRecord>;\n\n/**\n * @internal\n */\nconst lazyMarker = 'lazyMarker' as 'lazyMarker' & {\n __brand: 'lazyMarker';\n};\nexport type Lazy<TAny> = (() => Promise<TAny>) & { [lazyMarker]: true };\n\ntype LazyLoader<TAny> = {\n load: () => Promise<void>;\n ref: Lazy<TAny>;\n};\n\nfunction once<T>(fn: () => T): () => T {\n const uncalled = Symbol();\n let result: T | typeof uncalled = uncalled;\n return (): T => {\n if (result === uncalled) {\n result = fn();\n }\n return result;\n };\n}\n\n/**\n * Lazy load a router\n * @see https://trpc.io/docs/server/merging-routers#lazy-load\n */\nexport function lazy<TRouter extends AnyRouter>(\n importRouter: () => Promise<\n | TRouter\n | {\n [key: string]: TRouter;\n }\n >,\n): Lazy<NoInfer<TRouter>> {\n async function resolve(): Promise<TRouter> {\n const mod = await importRouter();\n\n // if the module is a router, return it\n if (isRouter(mod)) {\n return mod;\n }\n\n const routers = Object.values(mod);\n\n if (routers.length !== 1 || !isRouter(routers[0])) {\n throw new Error(\n \"Invalid router module - either define exactly 1 export or return the router directly.\\nExample: `lazy(() => import('./slow.js').then((m) => m.slowRouter))`\",\n );\n }\n\n return routers[0];\n }\n\n (resolve as Lazy<NoInfer<TRouter>>)[lazyMarker] = true as const;\n\n return resolve as Lazy<NoInfer<TRouter>>;\n}\n\nfunction isLazy<TAny>(input: unknown): input is Lazy<TAny> {\n return typeof input === 'function' && lazyMarker in input;\n}\n\n/**\n * @internal\n */\nexport interface RouterDef<\n TRoot extends AnyRootTypes,\n TRecord extends RouterRecord,\n> {\n _config: RootConfig<TRoot>;\n router: true;\n procedure?: never;\n procedures: TRecord;\n record: TRecord;\n lazy: Record<string, LazyLoader<AnyRouter>>;\n}\n\nexport interface Router<\n TRoot extends AnyRootTypes,\n TRecord extends RouterRecord,\n> {\n _def: RouterDef<TRoot, TRecord>;\n /**\n * @see https://trpc.io/docs/v11/server/server-side-calls\n */\n createCaller: RouterCaller<TRoot, TRecord>;\n}\n\nexport type BuiltRouter<\n TRoot extends AnyRootTypes,\n TRecord extends RouterRecord,\n> = Router<TRoot, TRecord> & TRecord;\n\nexport interface RouterBuilder<TRoot extends AnyRootTypes> {\n <TIn extends CreateRouterOptions>(\n _: TIn,\n ): BuiltRouter<TRoot, DecorateCreateRouterOptions<TIn>>;\n}\n\nexport type AnyRouter = Router<any, any>;\n\nexport type inferRouterRootTypes<TRouter extends AnyRouter> =\n TRouter['_def']['_config']['$types'];\n\nexport type inferRouterContext<TRouter extends AnyRouter> =\n inferRouterRootTypes<TRouter>['ctx'];\nexport type inferRouterError<TRouter extends AnyRouter> =\n inferRouterRootTypes<TRouter>['errorShape'];\nexport type inferRouterMeta<TRouter extends AnyRouter> =\n inferRouterRootTypes<TRouter>['meta'];\n\nfunction isRouter(value: unknown): value is AnyRouter {\n return (\n isObject(value) && isObject(value['_def']) && 'router' in value['_def']\n );\n}\n\nconst emptyRouter = {\n _ctx: null as any,\n _errorShape: null as any,\n _meta: null as any,\n queries: {},\n mutations: {},\n subscriptions: {},\n errorFormatter: defaultFormatter,\n transformer: defaultTransformer,\n};\n\n/**\n * Reserved words that can't be used as router or procedure names\n */\nconst reservedWords = [\n /**\n * Then is a reserved word because otherwise we can't return a promise that returns a Proxy\n * since JS will think that `.then` is something that exists\n */\n 'then',\n /**\n * `fn.call()` and `fn.apply()` are reserved words because otherwise we can't call a function using `.call` or `.apply`\n */\n 'call',\n 'apply',\n];\n\n/** @internal */\nexport type CreateRouterOptions = {\n [key: string]:\n AnyProcedure | AnyRouter | CreateRouterOptions | Lazy<AnyRouter>;\n};\n\n/** @internal */\nexport type DecorateCreateRouterOptions<\n TRouterOptions extends CreateRouterOptions,\n> = {\n [K in keyof TRouterOptions]: TRouterOptions[K] extends infer $Value\n ? $Value extends AnyProcedure\n ? $Value\n : $Value extends Router<any, infer TRecord>\n ? TRecord\n : $Value extends Lazy<Router<any, infer TRecord>>\n ? TRecord\n : $Value extends CreateRouterOptions\n ? DecorateCreateRouterOptions<$Value>\n : never\n : never;\n};\n\n/**\n * @internal\n */\nexport function createRouterFactory<TRoot extends AnyRootTypes>(\n config: RootConfig<TRoot>,\n) {\n function createRouterInner<TInput extends CreateRouterOptions>(\n input: TInput,\n ): BuiltRouter<TRoot, DecorateCreateRouterOptions<TInput>> {\n const reservedWordsUsed = new Set(\n Object.keys(input).filter((v) => reservedWords.includes(v)),\n );\n if (reservedWordsUsed.size > 0) {\n throw new Error(\n 'Reserved words used in `router({})` call: ' +\n Array.from(reservedWordsUsed).join(', '),\n );\n }\n\n const procedures: Record<string, AnyProcedure> = emptyObject();\n const lazy: Record<string, LazyLoader<AnyRouter>> = emptyObject();\n\n function createLazyLoader(opts: {\n ref: Lazy<AnyRouter>;\n path: readonly string[];\n key: string;\n aggregate: RouterRecord;\n }): LazyLoader<AnyRouter> {\n return {\n ref: opts.ref,\n load: once(async () => {\n const router = await opts.ref();\n const lazyPath = [...opts.path, opts.key];\n const lazyKey = lazyPath.join('.');\n\n opts.aggregate[opts.key] = step(router._def.record, lazyPath);\n\n delete lazy[lazyKey];\n\n // add lazy loaders for nested routers\n for (const [nestedKey, nestedItem] of Object.entries(\n router._def.lazy,\n )) {\n const nestedRouterKey = [...lazyPath, nestedKey].join('.');\n\n // console.log('adding lazy', nestedRouterKey);\n lazy[nestedRouterKey] = createLazyLoader({\n ref: nestedItem.ref,\n path: lazyPath,\n key: nestedKey,\n aggregate: opts.aggregate[opts.key] as RouterRecord,\n });\n }\n }),\n };\n }\n\n function step(from: CreateRouterOptions, path: readonly string[] = []) {\n const aggregate: RouterRecord = emptyObject();\n for (const [key, item] of Object.entries(from ?? {})) {\n if (isLazy(item)) {\n lazy[[...path, key].join('.')] = createLazyLoader({\n path,\n ref: item,\n key,\n aggregate,\n });\n continue;\n }\n if (isRouter(item)) {\n aggregate[key] = step(item._def.record, [...path, key]);\n continue;\n }\n if (!isProcedure(item)) {\n // RouterRecord\n aggregate[key] = step(item, [...path, key]);\n continue;\n }\n\n const newPath = [...path, key].join('.');\n\n if (procedures[newPath]) {\n throw new Error(`Duplicate key: ${newPath}`);\n }\n\n procedures[newPath] = item;\n aggregate[key] = item;\n }\n\n return aggregate;\n }\n const record = step(input);\n\n const _def: AnyRouter['_def'] = {\n _config: config,\n router: true,\n procedures,\n lazy,\n ...emptyRouter,\n record,\n };\n\n const router: BuiltRouter<TRoot, {}> = {\n ...(record as {}),\n _def,\n createCaller: createCallerFactory<TRoot>()({\n _def,\n }),\n };\n return router as BuiltRouter<TRoot, DecorateCreateRouterOptions<TInput>>;\n }\n\n return createRouterInner;\n}\n\nfunction isProcedure(\n procedureOrRouter: ValueOf<CreateRouterOptions>,\n): procedureOrRouter is AnyProcedure {\n return typeof procedureOrRouter === 'function';\n}\n\n/**\n * @internal\n */\nexport async function getProcedureAtPath(\n router: Pick<Router<any, any>, '_def'>,\n path: string,\n): Promise<AnyProcedure | null> {\n const { _def } = router;\n let procedure = _def.procedures[path];\n\n while (!procedure) {\n const key = Object.keys(_def.lazy).find(\n (key) => path === key || path.startsWith(key + '.'),\n );\n // console.log(`found lazy: ${key ?? 'NOPE'} (fullPath: ${fullPath})`);\n\n if (!key) {\n return null;\n }\n // console.log('loading', key, '.......');\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const lazyRouter = _def.lazy[key]!;\n await lazyRouter.load();\n\n procedure = _def.procedures[path];\n }\n\n return procedure;\n}\n\n/**\n * @internal\n */\nexport async function callProcedure(\n opts: ProcedureCallOptions<unknown> & {\n router: AnyRouter;\n allowMethodOverride?: boolean;\n },\n) {\n const { type, path } = opts;\n const proc = await getProcedureAtPath(opts.router, path);\n if (\n !proc ||\n !isProcedure(proc) ||\n (proc._def.type !== type && !opts.allowMethodOverride)\n ) {\n throw new TRPCError({\n code: 'NOT_FOUND',\n message: `No \"${type}\"-procedure on path \"${path}\"`,\n });\n }\n\n /* istanbul ignore if -- @preserve */\n if (\n proc._def.type !== type &&\n opts.allowMethodOverride &&\n proc._def.type === 'subscription'\n ) {\n throw new TRPCError({\n code: 'METHOD_NOT_SUPPORTED',\n message: `Method override is not supported for subscriptions`,\n });\n }\n\n return proc(opts);\n}\n\nexport interface RouterCallerFactory<TRoot extends AnyRootTypes> {\n <TRecord extends RouterRecord>(\n router: Pick<Router<TRoot, TRecord>, '_def'>,\n ): RouterCaller<TRoot, TRecord>;\n}\n\nexport function createCallerFactory<\n TRoot extends AnyRootTypes,\n>(): RouterCallerFactory<TRoot> {\n return function createCallerInner<TRecord extends RouterRecord>(\n router: Pick<Router<TRoot, TRecord>, '_def'>,\n ): RouterCaller<TRoot, TRecord> {\n const { _def } = router;\n type Context = TRoot['ctx'];\n\n return function createCaller(ctxOrCallback, opts) {\n return createRecursiveProxy<ReturnType<RouterCaller<any, any>>>(\n async (innerOpts) => {\n const { path, args } = innerOpts;\n const fullPath = path.join('.');\n\n if (path.length === 1 && path[0] === '_def') {\n return _def;\n }\n\n const procedure = await getProcedureAtPath(router, fullPath);\n\n let ctx: Context | undefined = undefined;\n try {\n if (!procedure) {\n throw new TRPCError({\n code: 'NOT_FOUND',\n message: `No procedure found on path \"${path}\"`,\n });\n }\n ctx = isFunction(ctxOrCallback)\n ? await Promise.resolve(ctxOrCallback())\n : ctxOrCallback;\n\n return await procedure({\n path: fullPath,\n getRawInput: async () => args[0],\n ctx,\n type: procedure._def.type,\n signal: opts?.signal,\n batchIndex: 0,\n });\n } catch (cause) {\n opts?.onError?.({\n ctx,\n error: getTRPCErrorFromUnknown(cause),\n input: args[0],\n path: fullPath,\n type: procedure?._def.type ?? 'unknown',\n });\n throw cause;\n }\n },\n );\n };\n };\n}\n\n/** @internal */\nexport type MergeRouters<\n TRouters extends AnyRouter[],\n TRoot extends AnyRootTypes = TRouters[0]['_def']['_config']['$types'],\n TRecord extends RouterRecord = {},\n> = TRouters extends [\n infer Head extends AnyRouter,\n ...infer Tail extends AnyRouter[],\n]\n ? MergeRouters<Tail, TRoot, Head['_def']['record'] & TRecord>\n : BuiltRouter<TRoot, TRecord>;\n\nexport function mergeRouters<TRouters extends AnyRouter[]>(\n ...routerList: [...TRouters]\n): MergeRouters<TRouters> {\n const record = mergeWithoutOverrides(\n {},\n ...routerList.map((r) => r._def.record),\n );\n const errorFormatter = routerList.reduce(\n (currentErrorFormatter, nextRouter) => {\n if (\n nextRouter._def._config.errorFormatter &&\n nextRouter._def._config.errorFormatter !== defaultFormatter\n ) {\n if (\n currentErrorFormatter !== defaultFormatter &&\n currentErrorFormatter !== nextRouter._def._config.errorFormatter\n ) {\n throw new Error('You seem to have several error formatters');\n }\n return nextRouter._def._config.errorFormatter;\n }\n return currentErrorFormatter;\n },\n defaultFormatter,\n );\n\n const transformer = routerList.reduce((prev, current) => {\n if (\n current._def._config.transformer &&\n current._def._config.transformer !== defaultTransformer\n ) {\n if (\n prev !== defaultTransformer &&\n prev !== current._def._config.transformer\n ) {\n throw new Error('You seem to have several transformers');\n }\n return current._def._config.transformer;\n }\n return prev;\n }, defaultTransformer);\n\n const router = createRouterFactory({\n errorFormatter,\n transformer,\n isDev: routerList.every((r) => r._def._config.isDev),\n allowOutsideOfServer: routerList.every(\n (r) => r._def._config.allowOutsideOfServer,\n ),\n isServer: routerList.every((r) => r._def._config.isServer),\n $types: routerList[0]?._def._config.$types,\n sse: routerList[0]?._def._config.sse,\n })(record);\n\n return router as MergeRouters<TRouters>;\n}\n","import { observable } from './observable';\nimport type { Observable, Observer } from './types';\n\nexport interface BehaviorSubject<TValue> extends Observable<TValue, never> {\n observable: Observable<TValue, never>;\n next: (value: TValue) => void;\n get: () => TValue;\n}\n\nexport interface ReadonlyBehaviorSubject<TValue> extends Omit<\n BehaviorSubject<TValue>,\n 'next'\n> {}\n\n/**\n * @internal\n * An observable that maintains and provides a \"current value\" to subscribers\n * @see https://www.learnrxjs.io/learn-rxjs/subjects/behaviorsubject\n */\nexport function behaviorSubject<TValue>(\n initialValue: TValue,\n): BehaviorSubject<TValue> {\n let value: TValue = initialValue;\n\n const observerList: Observer<TValue, never>[] = [];\n\n const addObserver = (observer: Observer<TValue, never>) => {\n if (value !== undefined) {\n observer.next(value);\n }\n observerList.push(observer);\n };\n const removeObserver = (observer: Observer<TValue, never>) => {\n observerList.splice(observerList.indexOf(observer), 1);\n };\n\n const obs = observable<TValue, never>((observer) => {\n addObserver(observer);\n return () => {\n removeObserver(observer);\n };\n }) as BehaviorSubject<TValue>;\n\n obs.next = (nextValue: TValue) => {\n if (value === nextValue) {\n return;\n }\n value = nextValue;\n for (const observer of observerList) {\n observer.next(nextValue);\n }\n };\n\n obs.get = () => value;\n\n return obs;\n}\n","import type { AnyRouter, ProcedureType } from '@trpc/server';\nimport { observable } from '@trpc/server/observable';\nimport type { TRPCErrorShape, TRPCResponse } from '@trpc/server/rpc';\nimport type { AnyClientTypes } from '@trpc/server/unstable-core-do-not-import';\nimport { jsonlStreamConsumer } from '@trpc/server/unstable-core-do-not-import';\nimport type { BatchLoader } from '../internals/dataLoader';\nimport { dataLoader } from '../internals/dataLoader';\nimport { allAbortSignals, raceAbortSignals } from '../internals/signals';\nimport type { NonEmptyArray } from '../internals/types';\nimport { TRPCClientError } from '../TRPCClientError';\nimport type { HTTPBatchLinkOptions } from './HTTPBatchLinkOptions';\nimport type { HTTPResult } from './internals/httpUtils';\nimport {\n fetchHTTPResponse,\n getBody,\n getUrl,\n resolveHTTPLinkOptions,\n} from './internals/httpUtils';\nimport type { Operation, TRPCLink } from './types';\n\nexport type HTTPBatchStreamLinkOptions<TRoot extends AnyClientTypes> =\n HTTPBatchLinkOptions<TRoot> & {\n /**\n * Which header to use to signal the server that the client wants a streaming response.\n * - `'trpc-accept'` (default): sends `trpc-accept: application/jsonl` header\n * - `'accept'`: sends `Accept: application/jsonl` header, which can avoid CORS preflight for cross-origin streaming queries. Be aware that `application/jsonl` is not an official MIME type and so this is not completely spec-compliant - you should test that your infrastructure supports this value.\n * @default 'trpc-accept'\n */\n streamHeader?: 'trpc-accept' | 'accept';\n };\n\n/**\n * @see https://trpc.io/docs/client/links/httpBatchStreamLink\n */\nexport function httpBatchStreamLink<TRouter extends AnyRouter>(\n opts: HTTPBatchStreamLinkOptions<TRouter['_def']['_config']['$types']>,\n): TRPCLink<TRouter> {\n const resolvedOpts = resolveHTTPLinkOptions(opts);\n const maxURLLength = opts.maxURLLength ?? Infinity;\n const maxItems = opts.maxItems ?? Infinity;\n\n return () => {\n const batchLoader = (\n type: ProcedureType,\n ): BatchLoader<Operation, HTTPResult> => {\n return {\n validate(batchOps) {\n if (maxURLLength === Infinity && maxItems === Infinity) {\n // escape hatch for quick calcs\n return true;\n }\n if (batchOps.length > maxItems) {\n return false;\n }\n const path = batchOps.map((op) => op.path).join(',');\n const inputs = batchOps.map((op) => op.input);\n\n const url = getUrl({\n ...resolvedOpts,\n type,\n path,\n inputs,\n signal: null,\n });\n\n return url.length <= maxURLLength;\n },\n async fetch(batchOps) {\n const path = batchOps.map((op) => op.path).join(',');\n const inputs = batchOps.map((op) => op.input);\n\n const batchSignals = allAbortSignals(\n ...batchOps.map((op) => op.signal),\n );\n const abortController = new AbortController();\n\n const responsePromise = fetchHTTPResponse({\n ...resolvedOpts,\n signal: raceAbortSignals(batchSignals, abortController.signal),\n type,\n contentTypeHeader: 'application/json',\n trpcAcceptHeader: 'application/jsonl',\n trpcAcceptHeaderKey: opts.streamHeader ?? 'trpc-accept',\n getUrl,\n getBody,\n inputs,\n path,\n headers() {\n if (!opts.headers) {\n return {};\n }\n if (typeof opts.headers === 'function') {\n return opts.headers({\n opList: batchOps as NonEmptyArray<Operation>,\n });\n }\n return opts.headers;\n },\n });\n\n const res = await responsePromise;\n\n if (!res.ok) {\n // Server returned a non-2xx response (e.g. batching disabled).\n // The body is plain JSON, not JSONL, so parse it directly and\n // propagate the same error to every operation in the batch.\n const json = (await res.json()) as TRPCResponse;\n if ('error' in json) {\n json.error = resolvedOpts.transformer.output.deserialize(\n json.error,\n );\n }\n\n return batchOps.map((): Promise<HTTPResult> =>\n Promise.resolve({\n json,\n meta: {\n response: res,\n },\n }),\n );\n }\n\n const [head] = await jsonlStreamConsumer<\n Record<string, Promise<any>>\n >({\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n from: res.body!,\n deserialize: (data) =>\n resolvedOpts.transformer.output.deserialize(data),\n // onError: console.error,\n formatError(opts) {\n const error = opts.error as TRPCErrorShape;\n return TRPCClientError.from({\n error,\n });\n },\n abortController,\n });\n const promises = Object.keys(batchOps).map(\n async (key): Promise<HTTPResult> => {\n let json: TRPCResponse = await Promise.resolve(head[key]);\n\n if ('result' in json) {\n /**\n * Not very pretty, but we need to unwrap nested data as promises\n * Our stream producer will only resolve top-level async values or async values that are directly nested in another async value\n */\n const result = await Promise.resolve(json.result);\n json = {\n result: {\n data: await Promise.resolve(result.data),\n },\n };\n }\n\n return {\n json,\n meta: {\n response: res,\n },\n };\n },\n );\n return promises;\n },\n };\n };\n\n const query = dataLoader(batchLoader('query'));\n const mutation = dataLoader(batchLoader('mutation'));\n\n const loaders = { query, mutation };\n return ({ op }) => {\n return observable((observer) => {\n /* istanbul ignore if -- @preserve */\n if (op.type === 'subscription') {\n throw new Error(\n 'Subscriptions are unsupported by `httpBatchStreamLink` - use `httpSubscriptionLink` or `wsLink`',\n );\n }\n const ac = new AbortController();\n const loader = loaders[op.type];\n const promise = loader.load({\n ...op,\n signal: raceAbortSignals(op.signal, ac.signal),\n });\n\n let isDone = false;\n let _res = undefined as HTTPResult | undefined;\n promise\n .then((res) => {\n isDone = true;\n _res = res;\n if ('error' in res.json) {\n observer.error(\n TRPCClientError.from(res.json, {\n meta: res.meta,\n }),\n );\n return;\n } else if ('result' in res.json) {\n observer.next({\n context: res.meta,\n result: res.json.result,\n });\n observer.complete();\n return;\n }\n\n observer.complete();\n })\n .catch((err) => {\n isDone = true;\n observer.error(\n TRPCClientError.from(err, {\n meta: _res?.meta,\n }),\n );\n });\n\n return () => {\n if (!isDone) {\n ac.abort();\n }\n };\n });\n };\n };\n}\n\n/**\n * @deprecated use {@link httpBatchStreamLink} instead\n */\nexport const unstable_httpBatchStreamLink = httpBatchStreamLink;\n","import { getHTTPStatusCodeFromError } from '../http/getHTTPStatusCode';\nimport type { ProcedureType } from '../procedure';\nimport type { AnyRootTypes, RootConfig } from '../rootConfig';\nimport { TRPC_ERROR_CODES_BY_KEY } from '../rpc';\nimport type { DefaultErrorShape } from './formatter';\nimport type { TRPCError } from './TRPCError';\n\n/**\n * @internal\n */\nexport function getErrorShape<TRoot extends AnyRootTypes>(opts: {\n config: RootConfig<TRoot>;\n error: TRPCError;\n type: ProcedureType | 'unknown';\n path: string | undefined;\n input: unknown;\n ctx: TRoot['ctx'] | undefined;\n}): TRoot['errorShape'] {\n const { path, error, config } = opts;\n const { code } = opts.error;\n const shape: DefaultErrorShape = {\n message: error.message,\n code: TRPC_ERROR_CODES_BY_KEY[code],\n data: {\n code,\n httpStatus: getHTTPStatusCodeFromError(error),\n },\n };\n if (config.isDev && typeof opts.error.stack === 'string') {\n shape.data.stack = opts.error.stack;\n }\n if (typeof path === 'string') {\n shape.data.path = path;\n }\n return config.errorFormatter({ ...opts, shape });\n}\n","import { behaviorSubject } from '@trpc/server/observable';\nimport type { UrlOptionsWithConnectionParams } from '../../internals/urlWithConnectionParams';\nimport type { Encoder } from './encoder';\nimport { buildConnectionMessage, prepareUrl, withResolvers } from './utils';\n\n/**\n * Opens a WebSocket connection asynchronously and returns a promise\n * that resolves when the connection is successfully established.\n * The promise rejects if an error occurs during the connection attempt.\n */\nfunction asyncWsOpen(ws: WebSocket) {\n const { promise, resolve, reject } = withResolvers<void>();\n\n ws.addEventListener('open', () => {\n ws.removeEventListener('error', reject);\n resolve();\n });\n ws.addEventListener('error', reject);\n\n return promise;\n}\n\ninterface PingPongOptions {\n /**\n * The interval (in milliseconds) between \"PING\" messages.\n */\n intervalMs: number;\n\n /**\n * The timeout (in milliseconds) to wait for a \"PONG\" response before closing the connection.\n */\n pongTimeoutMs: number;\n}\n\n/**\n * Sets up a periodic ping-pong mechanism to keep the WebSocket connection alive.\n *\n * - Sends \"PING\" messages at regular intervals defined by `intervalMs`.\n * - If a \"PONG\" response is not received within the `pongTimeoutMs`, the WebSocket is closed.\n * - The ping timer resets upon receiving any message to maintain activity.\n * - Automatically starts the ping process when the WebSocket connection is opened.\n * - Cleans up timers when the WebSocket is closed.\n *\n * @param ws - The WebSocket instance to manage.\n * @param options - Configuration options for ping-pong intervals and timeouts.\n */\nfunction setupPingInterval(\n ws: WebSocket,\n { intervalMs, pongTimeoutMs }: PingPongOptions,\n) {\n let pingTimeout: ReturnType<typeof setTimeout> | undefined;\n let pongTimeout: ReturnType<typeof setTimeout> | undefined;\n\n function start() {\n pingTimeout = setTimeout(() => {\n ws.send('PING');\n pongTimeout = setTimeout(() => {\n ws.close();\n }, pongTimeoutMs);\n }, intervalMs);\n }\n\n function reset() {\n clearTimeout(pingTimeout);\n start();\n }\n\n function pong() {\n clearTimeout(pongTimeout);\n reset();\n }\n\n ws.addEventListener('open', start);\n ws.addEventListener('message', ({ data }) => {\n clearTimeout(pingTimeout);\n start();\n\n if (data === 'PONG') {\n pong();\n }\n });\n ws.addEventListener('close', () => {\n clearTimeout(pingTimeout);\n clearTimeout(pongTimeout);\n });\n}\n\nexport interface WebSocketConnectionOptions {\n WebSocketPonyfill?: typeof WebSocket;\n urlOptions: UrlOptionsWithConnectionParams;\n keepAlive: PingPongOptions & {\n enabled: boolean;\n };\n encoder: Encoder;\n}\n\n/**\n * Manages a WebSocket connection with support for reconnection, keep-alive mechanisms,\n * and observable state tracking.\n */\nexport class WsConnection {\n static connectCount = 0;\n public id = ++WsConnection.connectCount;\n\n private readonly WebSocketPonyfill: typeof WebSocket;\n private readonly urlOptions: UrlOptionsWithConnectionParams;\n private readonly keepAliveOpts: WebSocketConnectionOptions['keepAlive'];\n private readonly encoder: Encoder;\n public readonly wsObservable = behaviorSubject<WebSocket | null>(null);\n\n constructor(opts: WebSocketConnectionOptions) {\n this.WebSocketPonyfill = opts.WebSocketPonyfill ?? WebSocket;\n if (!this.WebSocketPonyfill) {\n throw new Error(\n \"No WebSocket implementation found - you probably don't want to use this on the server, but if you do you need to pass a `WebSocket`-ponyfill\",\n );\n }\n\n this.urlOptions = opts.urlOptions;\n this.keepAliveOpts = opts.keepAlive;\n this.encoder = opts.encoder;\n }\n\n public get ws() {\n return this.wsObservable.get();\n }\n\n private set ws(ws) {\n this.wsObservable.next(ws);\n }\n\n /**\n * Checks if the WebSocket connection is open and ready to communicate.\n */\n public isOpen(): this is { ws: WebSocket } {\n return (\n !!this.ws &&\n this.ws.readyState === this.WebSocketPonyfill.OPEN &&\n !this.openPromise\n );\n }\n\n /**\n * Checks if the WebSocket connection is closed or in the process of closing.\n */\n public isClosed(): this is { ws: WebSocket } {\n return (\n !!this.ws &&\n (this.ws.readyState === this.WebSocketPonyfill.CLOSING ||\n this.ws.readyState === this.WebSocketPonyfill.CLOSED)\n );\n }\n\n /**\n * Manages the WebSocket opening process, ensuring that only one open operation\n * occurs at a time. Tracks the ongoing operation with `openPromise` to avoid\n * redundant calls and ensure proper synchronization.\n *\n * Sets up the keep-alive mechanism and necessary event listeners for the connection.\n *\n * @returns A promise that resolves once the WebSocket connection is successfully opened.\n */\n private openPromise: Promise<void> | null = null;\n public async open() {\n if (this.openPromise) return this.openPromise;\n\n this.id = ++WsConnection.connectCount;\n const wsPromise = prepareUrl(this.urlOptions).then(\n (url) => new this.WebSocketPonyfill(url),\n );\n this.openPromise = wsPromise.then(async (ws) => {\n this.ws = ws;\n\n // Set binaryType to handle both text and binary messages consistently\n ws.binaryType = 'arraybuffer';\n\n // Setup ping listener\n ws.addEventListener('message', function ({ data }) {\n if (data === 'PING') {\n this.send('PONG');\n }\n });\n\n if (this.keepAliveOpts.enabled) {\n setupPingInterval(ws, this.keepAliveOpts);\n }\n\n ws.addEventListener('close', () => {\n if (this.ws === ws) {\n this.ws = null;\n }\n });\n\n await asyncWsOpen(ws);\n\n if (this.urlOptions.connectionParams) {\n ws.send(\n await buildConnectionMessage(\n this.urlOptions.connectionParams,\n this.encoder,\n ),\n );\n }\n });\n\n try {\n await this.openPromise;\n } finally {\n this.openPromise = null;\n }\n }\n\n /**\n * Closes the WebSocket connection gracefully.\n * Waits for any ongoing open operation to complete before closing.\n */\n public async close() {\n try {\n await this.openPromise;\n } finally {\n this.ws?.close();\n }\n }\n}\n\n/**\n * Provides a backward-compatible representation of the connection state.\n */\nexport function backwardCompatibility(connection: WsConnection) {\n if (connection.isOpen()) {\n return {\n id: connection.id,\n state: 'open',\n ws: connection.ws,\n } as const;\n }\n\n if (connection.isClosed()) {\n return {\n id: connection.id,\n state: 'closed',\n ws: connection.ws,\n } as const;\n }\n\n if (!connection.ws) {\n return null;\n }\n\n return {\n id: connection.id,\n state: 'connecting',\n ws: connection.ws,\n } as const;\n}\n","import { isObject } from '../utils';\n\nexport function isAbortError(\n error: unknown,\n): error is DOMException | Error | { name: 'AbortError' } {\n return isObject(error) && error['name'] === 'AbortError';\n}\n\nexport function throwAbortError(message = 'AbortError'): never {\n throw new DOMException(message, 'AbortError');\n}\n","/*!\n * is-plain-object <https://github.com/jonschlinkert/is-plain-object>\n *\n * Copyright (c) 2014-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\nfunction isObject(o: unknown): o is Record<string, unknown> {\n return Object.prototype.toString.call(o) === '[object Object]';\n}\n \nexport function isPlainObject(o: unknown): o is Record<string, unknown> {\n var ctor,prot;\n\n if (isObject(o) === false) return false;\n\n // If has modified constructor\n ctor = o.constructor;\n if (ctor === undefined) return true;\n\n // If has modified prototype\n prot = ctor.prototype;\n if (isObject(prot) === false) return false;\n\n // If constructor does not have an Object-specific method\n if (prot.hasOwnProperty('isPrototypeOf') === false) {\n return false;\n }\n\n // Most likely a plain Object\n return true;\n};\n","export function inputWithTrackedEventId(\n input: unknown,\n lastEventId: string | undefined,\n) {\n if (!lastEventId) {\n return input;\n }\n if (input != null && typeof input !== 'object') {\n return input;\n }\n return {\n ...(input ?? {}),\n lastEventId,\n };\n}\n","/* eslint-disable @typescript-eslint/unbound-method */\n \n \n\nimport type {\n PromiseExecutor,\n PromiseWithResolvers,\n ProxyPromise,\n SubscribedPromise,\n} from \"./types\";\n\n/** Memory safe (weakmapped) cache of the ProxyPromise for each Promise,\n * which is retained for the lifetime of the original Promise.\n */\nconst subscribableCache = new WeakMap<\n PromiseLike<unknown>,\n ProxyPromise<unknown>\n>();\n\n/** A NOOP function allowing a consistent interface for settled\n * SubscribedPromises (settled promises are not subscribed - they resolve\n * immediately). */\nconst NOOP = () => {\n // noop\n};\n\n/**\n * Every `Promise<T>` can be shadowed by a single `ProxyPromise<T>`. It is\n * created once, cached and reused throughout the lifetime of the Promise. Get a\n * Promise's ProxyPromise using `Unpromise.proxy(promise)`.\n *\n * The `ProxyPromise<T>` attaches handlers to the original `Promise<T>`\n * `.then()` and `.catch()` just once. Promises derived from it use a\n * subscription- (and unsubscription-) based mechanism that monitors these\n * handlers.\n *\n * Every time you call `.subscribe()`, `.then()` `.catch()` or `.finally()` on a\n * `ProxyPromise<T>` it returns a `SubscribedPromise<T>` having an additional\n * `unsubscribe()` method. Calling `unsubscribe()` detaches reference chains\n * from the original, potentially long-lived Promise, eliminating memory leaks.\n *\n * This approach can eliminate the memory leaks that otherwise come about from\n * repeated `race()` or `any()` calls invoking `.then()` and `.catch()` multiple\n * times on the same long-lived native Promise (subscriptions which can never be\n * cleaned up).\n *\n * `Unpromise.race(promises)` is a reference implementation of `Promise.race`\n * avoiding memory leaks when using long-lived unsettled Promises.\n *\n * `Unpromise.any(promises)` is a reference implementation of `Promise.any`\n * avoiding memory leaks when using long-lived unsettled Promises.\n *\n * `Unpromise.resolve(promise)` returns an ephemeral `SubscribedPromise<T>` for\n * any given `Promise<T>` facilitating arbitrary async/await patterns. Behind\n * the scenes, `resolve` is implemented simply as\n * `Unpromise.proxy(promise).subscribe()`. Don't forget to call `.unsubscribe()`\n * to tidy up!\n *\n */\nexport class Unpromise<T> implements ProxyPromise<T> {\n /** INSTANCE IMPLEMENTATION */\n\n /** The promise shadowed by this Unpromise<T> */\n protected readonly promise: Promise<T> | PromiseLike<T>;\n\n /** Promises expecting eventual settlement (unless unsubscribed first). This list is deleted\n * after the original promise settles - no further notifications will be issued. */\n protected subscribers: ReadonlyArray<PromiseWithResolvers<T>> | null = [];\n\n /** The Promise's settlement (recorded when it fulfils or rejects). This is consulted when\n * calling .subscribe() .then() .catch() .finally() to see if an immediately-resolving Promise\n * can be returned, and therefore subscription can be bypassed. */\n protected settlement: PromiseSettledResult<T> | null = null;\n\n /** Constructor accepts a normal Promise executor function like `new\n * Unpromise((resolve, reject) => {...})` or accepts a pre-existing Promise\n * like `new Unpromise(existingPromise)`. Adds `.then()` and `.catch()`\n * handlers to the Promise. These handlers pass fulfilment and rejection\n * notifications to downstream subscribers and maintains records of value\n * or error if the Promise ever settles. */\n protected constructor(promise: Promise<T>);\n protected constructor(promise: PromiseLike<T>);\n protected constructor(executor: PromiseExecutor<T>);\n protected constructor(arg: Promise<T> | PromiseLike<T> | PromiseExecutor<T>) {\n // handle either a Promise or a Promise executor function\n if (typeof arg === \"function\") {\n this.promise = new Promise(arg);\n } else {\n this.promise = arg;\n }\n\n // subscribe for eventual fulfilment and rejection\n\n // handle PromiseLike objects (that at least have .then)\n const thenReturn = this.promise.then((value) => {\n // atomically record fulfilment and detach subscriber list\n const { subscribers } = this;\n this.subscribers = null;\n this.settlement = {\n status: \"fulfilled\",\n value,\n };\n // notify fulfilment to subscriber list\n subscribers?.forEach(({ resolve }) => {\n resolve(value);\n });\n });\n\n // handle Promise (that also have a .catch behaviour)\n if (\"catch\" in thenReturn) {\n thenReturn.catch((reason) => {\n // atomically record rejection and detach subscriber list\n const { subscribers } = this;\n this.subscribers = null;\n this.settlement = {\n status: \"rejected\",\n reason,\n };\n // notify rejection to subscriber list\n subscribers?.forEach(({ reject }) => {\n reject(reason);\n });\n });\n }\n }\n\n /** Create a promise that mitigates uncontrolled subscription to a long-lived\n * Promise via .then() and .catch() - otherwise a source of memory leaks.\n *\n * The returned promise has an `unsubscribe()` method which can be called when\n * the Promise is no longer being tracked by application logic, and which\n * ensures that there is no reference chain from the original promise to the\n * new one, and therefore no memory leak.\n *\n * If original promise has not yet settled, this adds a new unique promise\n * that listens to then/catch events, along with an `unsubscribe()` method to\n * detach it.\n *\n * If original promise has settled, then creates a new Promise.resolve() or\n * Promise.reject() and provided unsubscribe is a noop.\n *\n * If you call `unsubscribe()` before the returned Promise has settled, it\n * will never settle.\n */\n subscribe(): SubscribedPromise<T> {\n // in all cases we will combine some promise with its unsubscribe function\n let promise: Promise<T>;\n let unsubscribe: () => void;\n\n const { settlement } = this;\n if (settlement === null) {\n // not yet settled - subscribe new promise. Expect eventual settlement\n if (this.subscribers === null) {\n // invariant - it is not settled, so it must have subscribers\n throw new Error(\"Unpromise settled but still has subscribers\");\n }\n const subscriber = withResolvers<T>();\n this.subscribers = listWithMember(this.subscribers, subscriber);\n promise = subscriber.promise;\n unsubscribe = () => {\n if (this.subscribers !== null) {\n this.subscribers = listWithoutMember(this.subscribers, subscriber);\n }\n };\n } else {\n // settled - don't create subscribed promise. Just resolve or reject\n const { status } = settlement;\n if (status === \"fulfilled\") {\n promise = Promise.resolve(settlement.value);\n } else {\n promise = Promise.reject(settlement.reason);\n }\n unsubscribe = NOOP;\n }\n\n // extend promise signature with the extra method\n return Object.assign(promise, { unsubscribe });\n }\n\n /** STANDARD PROMISE METHODS (but returning a SubscribedPromise) */\n\n then<TResult1 = T, TResult2 = never>(\n onfulfilled?:\n | ((value: T) => TResult1 | PromiseLike<TResult1>)\n | null\n ,\n onrejected?:\n | ((reason: any) => TResult2 | PromiseLike<TResult2>)\n | null\n \n ): SubscribedPromise<TResult1 | TResult2> {\n const subscribed = this.subscribe();\n const { unsubscribe } = subscribed;\n return Object.assign(subscribed.then(onfulfilled, onrejected), {\n unsubscribe,\n });\n }\n\n catch<TResult = never>(\n onrejected?:\n | ((reason: any) => TResult | PromiseLike<TResult>)\n | null\n \n ): SubscribedPromise<T | TResult> {\n const subscribed = this.subscribe();\n const { unsubscribe } = subscribed;\n return Object.assign(subscribed.catch(onrejected), {\n unsubscribe,\n });\n }\n\n finally(onfinally?: (() => void) | null ): SubscribedPromise<T> {\n const subscribed = this.subscribe();\n const { unsubscribe } = subscribed;\n return Object.assign(subscribed.finally(onfinally), {\n unsubscribe,\n });\n }\n\n /** TOSTRING SUPPORT */\n\n readonly [Symbol.toStringTag] = \"Unpromise\";\n\n /** Unpromise STATIC METHODS */\n\n /** Create or Retrieve the proxy Unpromise (a re-used Unpromise for the VM lifetime\n * of the provided Promise reference) */\n static proxy<T>(promise: PromiseLike<T>): ProxyPromise<T> {\n const cached = Unpromise.getSubscribablePromise(promise);\n return typeof cached !== \"undefined\"\n ? cached\n : Unpromise.createSubscribablePromise(promise);\n }\n\n /** Create and store an Unpromise keyed by an original Promise. */\n protected static createSubscribablePromise<T>(promise: PromiseLike<T>) {\n const created = new Unpromise<T>(promise);\n subscribableCache.set(promise, created as Unpromise<unknown>); // resolve promise to unpromise\n subscribableCache.set(created, created as Unpromise<unknown>); // resolve the unpromise to itself\n return created;\n }\n\n /** Retrieve a previously-created Unpromise keyed by an original Promise. */\n protected static getSubscribablePromise<T>(promise: PromiseLike<T>) {\n return subscribableCache.get(promise) as ProxyPromise<T> | undefined;\n }\n\n /** Promise STATIC METHODS */\n\n /** Lookup the Unpromise for this promise, and derive a SubscribedPromise from\n * it (that can be later unsubscribed to eliminate Memory leaks) */\n static resolve<T>(value: T | PromiseLike<T>) {\n const promise: PromiseLike<T> =\n typeof value === \"object\" &&\n value !== null &&\n \"then\" in value &&\n typeof value.then === \"function\"\n ? value\n : Promise.resolve(value);\n return Unpromise.proxy(promise).subscribe() as SubscribedPromise<\n Awaited<T>\n >;\n }\n\n /** Perform Promise.any() via SubscribedPromises, then unsubscribe them.\n * Equivalent to Promise.any but eliminates memory leaks from long-lived\n * promises accumulating .then() and .catch() subscribers. */\n static async any<T extends readonly unknown[] | []>(\n values: T\n ): Promise<Awaited<T[number]>>;\n static async any<T>(\n values: Iterable<T | PromiseLike<T>>\n ): Promise<Awaited<T>> {\n const valuesArray = Array.isArray(values) ? values : [...values];\n const subscribedPromises = valuesArray.map(Unpromise.resolve);\n try {\n return await Promise.any(subscribedPromises);\n } finally {\n subscribedPromises.forEach(({ unsubscribe }) => {\n unsubscribe();\n });\n }\n }\n\n /** Perform Promise.race via SubscribedPromises, then unsubscribe them.\n * Equivalent to Promise.race but eliminates memory leaks from long-lived\n * promises accumulating .then() and .catch() subscribers. */\n static async race<T extends readonly unknown[] | []>(\n values: T\n ): Promise<Awaited<T[number]>>;\n static async race<T>(\n values: Iterable<T | PromiseLike<T>>\n ): Promise<Awaited<T>> {\n const valuesArray = Array.isArray(values) ? values : [...values];\n const subscribedPromises = valuesArray.map(Unpromise.resolve);\n try {\n return await Promise.race(subscribedPromises);\n } finally {\n subscribedPromises.forEach(({ unsubscribe }) => {\n unsubscribe();\n });\n }\n }\n\n /** Create a race of SubscribedPromises that will fulfil to a single winning\n * Promise (in a 1-Tuple). Eliminates memory leaks from long-lived promises\n * accumulating .then() and .catch() subscribers. Allows simple logic to\n * consume the result, like...\n * ```ts\n * const [ winner ] = await Unpromise.race([ promiseA, promiseB ]);\n * if(winner === promiseB){\n * const result = await promiseB;\n * // do the thing\n * }\n * ```\n * */\n static async raceReferences<TPromise extends Promise<unknown>>(\n promises: readonly TPromise[]\n ) {\n // map each promise to an eventual 1-tuple containing itself\n const selfPromises = promises.map(resolveSelfTuple);\n\n // now race them. They will fulfil to a readonly [P] or reject.\n try {\n return await Promise.race(selfPromises);\n } finally {\n for (const promise of selfPromises) {\n // unsubscribe proxy promises when the race is over to mitigate memory leaks\n promise.unsubscribe();\n }\n }\n }\n}\n\n/** Promises a 1-tuple containing the original promise when it resolves. Allows\n * awaiting the eventual Promise ***reference*** (easy to destructure and\n * exactly compare with ===). Avoids resolving to the Promise ***value*** (which\n * may be ambiguous and therefore hard to identify as the winner of a race).\n * You can call unsubscribe on the Promise to mitigate memory leaks.\n * */\nexport function resolveSelfTuple<TPromise extends Promise<unknown>>(\n promise: TPromise\n): SubscribedPromise<readonly [TPromise]> {\n return Unpromise.proxy(promise).then(() => [promise] as const);\n}\n\n/** VENDORED (Future) PROMISE UTILITIES */\n\n/** Reference implementation of https://github.com/tc39/proposal-promise-with-resolvers */\nfunction withResolvers<T>(): PromiseWithResolvers<T> {\n let resolve!: PromiseWithResolvers<T>[\"resolve\"];\n let reject!: PromiseWithResolvers<T>[\"reject\"];\n const promise = new Promise<T>((_resolve, _reject) => {\n resolve = _resolve;\n reject = _reject;\n });\n return {\n promise,\n resolve,\n reject,\n };\n}\n\n/** IMMUTABLE LIST OPERATIONS */\n\nfunction listWithMember<T>(arr: readonly T[], member: T): readonly T[] {\n return [...arr, member];\n}\n\nfunction listWithoutIndex<T>(arr: readonly T[], index: number) {\n return [...arr.slice(0, index), ...arr.slice(index + 1)];\n}\n\nfunction listWithoutMember<T>(arr: readonly T[], member: unknown) {\n const index = arr.indexOf(member as T);\n if (index !== -1) {\n return listWithoutIndex(arr, index);\n }\n return arr;\n}\n","import { behaviorSubject, observable } from '@trpc/server/observable';\nimport type { TRPCErrorShape, TRPCResult } from '@trpc/server/rpc';\nimport type {\n AnyClientTypes,\n EventSourceLike,\n inferClientTypes,\n InferrableClientTypes,\n} from '@trpc/server/unstable-core-do-not-import';\nimport {\n retryableRpcCodes,\n run,\n sseStreamConsumer,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { inputWithTrackedEventId } from '../internals/inputWithTrackedEventId';\nimport { raceAbortSignals } from '../internals/signals';\nimport { TRPCClientError } from '../TRPCClientError';\nimport type { TRPCConnectionState } from '../unstable-internals';\nimport { getTransformer, type TransformerOptions } from '../unstable-internals';\nimport { getUrl } from './internals/httpUtils';\nimport {\n resultOf,\n type UrlOptionsWithConnectionParams,\n} from './internals/urlWithConnectionParams';\nimport type { Operation, TRPCLink } from './types';\n\nasync function urlWithConnectionParams(\n opts: UrlOptionsWithConnectionParams,\n): Promise<string> {\n let url = await resultOf(opts.url);\n if (opts.connectionParams) {\n const params = await resultOf(opts.connectionParams);\n\n const prefix = url.includes('?') ? '&' : '?';\n url +=\n prefix + 'connectionParams=' + encodeURIComponent(JSON.stringify(params));\n }\n\n return url;\n}\n\ntype HTTPSubscriptionLinkOptions<\n TRoot extends AnyClientTypes,\n TEventSource extends EventSourceLike.AnyConstructor = typeof EventSource,\n> = {\n /**\n * EventSource ponyfill\n */\n EventSource?: TEventSource;\n /**\n * EventSource options or a callback that returns them\n */\n eventSourceOptions?:\n | EventSourceLike.InitDictOf<TEventSource>\n | ((opts: {\n op: Operation;\n }) =>\n | EventSourceLike.InitDictOf<TEventSource>\n | Promise<EventSourceLike.InitDictOf<TEventSource>>);\n} & TransformerOptions<TRoot> &\n UrlOptionsWithConnectionParams;\n\n/**\n * @see https://trpc.io/docs/client/links/httpSubscriptionLink\n */\nexport function httpSubscriptionLink<\n TInferrable extends InferrableClientTypes,\n TEventSource extends EventSourceLike.AnyConstructor,\n>(\n opts: HTTPSubscriptionLinkOptions<\n inferClientTypes<TInferrable>,\n TEventSource\n >,\n): TRPCLink<TInferrable> {\n const transformer = getTransformer(opts.transformer);\n\n return () => {\n return ({ op }) => {\n return observable((observer) => {\n const { type, path, input } = op;\n\n /* istanbul ignore if -- @preserve */\n if (type !== 'subscription') {\n throw new Error('httpSubscriptionLink only supports subscriptions');\n }\n\n let lastEventId: string | undefined = undefined;\n const ac = new AbortController();\n const signal = raceAbortSignals(op.signal, ac.signal);\n const eventSourceStream = sseStreamConsumer<{\n EventSource: TEventSource;\n data: Partial<{\n id?: string;\n data: unknown;\n }>;\n error: TRPCErrorShape;\n }>({\n url: async () =>\n getUrl({\n transformer,\n url: await urlWithConnectionParams(opts),\n input: inputWithTrackedEventId(input, lastEventId),\n path,\n type,\n signal: null,\n }),\n init: () => resultOf(opts.eventSourceOptions, { op }),\n signal,\n deserialize: (data) => transformer.output.deserialize(data),\n EventSource: opts.EventSource ?? (globalThis.EventSource as never),\n });\n\n const connectionState = behaviorSubject<\n TRPCConnectionState<TRPCClientError<any>>\n >({\n type: 'state',\n state: 'connecting',\n error: null,\n });\n\n const connectionSub = connectionState.subscribe({\n next(state) {\n observer.next({\n result: state,\n });\n },\n });\n run(async () => {\n for await (const chunk of eventSourceStream) {\n switch (chunk.type) {\n case 'ping':\n // do nothing\n break;\n case 'data':\n const chunkData = chunk.data;\n\n let result: TRPCResult<unknown>;\n if (chunkData.id) {\n // if the `tracked()`-helper is used, we always have an `id` field\n lastEventId = chunkData.id;\n result = {\n id: chunkData.id,\n data: chunkData,\n };\n } else {\n result = {\n data: chunkData.data,\n };\n }\n\n observer.next({\n result,\n context: {\n eventSource: chunk.eventSource,\n },\n });\n break;\n case 'connected': {\n observer.next({\n result: {\n type: 'started',\n },\n context: {\n eventSource: chunk.eventSource,\n },\n });\n connectionState.next({\n type: 'state',\n state: 'pending',\n error: null,\n });\n break;\n }\n case 'serialized-error': {\n const error = TRPCClientError.from({ error: chunk.error });\n\n if (retryableRpcCodes.includes(chunk.error.code)) {\n //\n connectionState.next({\n type: 'state',\n state: 'connecting',\n error,\n });\n break;\n }\n //\n // non-retryable error, cancel the subscription\n throw error;\n }\n case 'connecting': {\n const lastState = connectionState.get();\n\n const error = chunk.event && TRPCClientError.from(chunk.event);\n if (!error && lastState.state === 'connecting') {\n break;\n }\n\n connectionState.next({\n type: 'state',\n state: 'connecting',\n error,\n });\n break;\n }\n case 'timeout': {\n connectionState.next({\n type: 'state',\n state: 'connecting',\n error: new TRPCClientError(\n `Timeout of ${chunk.ms}ms reached while waiting for a response`,\n ),\n });\n }\n }\n }\n observer.next({\n result: {\n type: 'stopped',\n },\n });\n connectionState.next({\n type: 'state',\n state: 'idle',\n error: null,\n });\n observer.complete();\n }).catch((error) => {\n observer.error(TRPCClientError.from(error));\n });\n\n return () => {\n observer.complete();\n ac.abort();\n connectionSub.unsubscribe();\n };\n });\n };\n };\n}\n\n/**\n * @deprecated use {@link httpSubscriptionLink} instead\n */\nexport const unstable_httpSubscriptionLink = httpSubscriptionLink;\n","const trackedSymbol = Symbol();\n\ntype TrackedId = string & {\n __brand: 'TrackedId';\n};\nexport type TrackedEnvelope<TData> = [TrackedId, TData, typeof trackedSymbol];\n\nexport interface TrackedData<TData> {\n /**\n * The id of the message to keep track of in case the connection gets lost\n */\n id: string;\n /**\n * The data field of the message\n */\n data: TData;\n}\n/**\n * Produce a typed server-sent event message\n * @deprecated use `tracked(id, data)` instead\n */\nexport function sse<TData>(event: { id: string; data: TData }) {\n return tracked(event.id, event.data);\n}\n\nexport function isTrackedEnvelope<TData>(\n value: unknown,\n): value is TrackedEnvelope<TData> {\n return Array.isArray(value) && value[2] === trackedSymbol;\n}\n\n/**\n * Automatically track an event so that it can be resumed from a given id if the connection is lost\n */\nexport function tracked<TData>(\n id: string,\n data: TData,\n): TrackedEnvelope<TData> {\n if (id === '') {\n // This limitation could be removed by using different SSE event names / channels for tracked event and non-tracked event\n throw new Error(\n '`id` must not be an empty string as empty string is the same as not setting the id at all',\n );\n }\n return [id as TrackedId, data, trackedSymbol];\n}\n\nexport type inferTrackedOutput<TData> =\n TData extends TrackedEnvelope<infer $Data> ? TrackedData<$Data> : TData;\n","import type { AnyTRPCRouter } from '@trpc/server';\nimport type { BehaviorSubject } from '@trpc/server/observable';\nimport { behaviorSubject, observable } from '@trpc/server/observable';\nimport type {\n CombinedDataTransformer,\n TRPCClientIncomingMessage,\n TRPCClientIncomingRequest,\n TRPCClientOutgoingMessage,\n TRPCResponseMessage,\n} from '@trpc/server/unstable-core-do-not-import';\nimport {\n run,\n sleep,\n transformResult,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { TRPCClientError } from '../../../TRPCClientError';\nimport type { TRPCConnectionState } from '../../internals/subscriptions';\nimport type { Operation, OperationResultEnvelope } from '../../types';\nimport type { Encoder } from './encoder';\nimport { jsonEncoder } from './encoder';\nimport type { WebSocketClientOptions } from './options';\nimport { exponentialBackoff, keepAliveDefaults, lazyDefaults } from './options';\nimport type { TCallbacks } from './requestManager';\nimport { RequestManager } from './requestManager';\nimport { ResettableTimeout, TRPCWebSocketClosedError } from './utils';\nimport { backwardCompatibility, WsConnection } from './wsConnection';\n\n/**\n * A WebSocket client for managing TRPC operations, supporting lazy initialization,\n * reconnection, keep-alive, and request management.\n */\nexport class WsClient {\n /**\n * Observable tracking the current connection state, including errors.\n */\n public readonly connectionState: BehaviorSubject<\n TRPCConnectionState<TRPCClientError<AnyTRPCRouter>>\n >;\n\n private allowReconnect = false;\n private requestManager = new RequestManager();\n private readonly activeConnection: WsConnection;\n private readonly reconnectRetryDelay: (attemptIndex: number) => number;\n private inactivityTimeout: ResettableTimeout;\n private readonly callbacks: Pick<\n WebSocketClientOptions,\n 'onOpen' | 'onClose' | 'onError'\n >;\n private readonly lazyMode: boolean;\n private readonly encoder: Encoder;\n\n constructor(opts: WebSocketClientOptions) {\n this.encoder = opts.experimental_encoder ?? jsonEncoder;\n // Initialize callbacks, connection parameters, and options.\n this.callbacks = {\n onOpen: opts.onOpen,\n onClose: opts.onClose,\n onError: opts.onError,\n };\n\n const lazyOptions = {\n ...lazyDefaults,\n ...opts.lazy,\n };\n\n // Set up inactivity timeout for lazy connections.\n this.inactivityTimeout = new ResettableTimeout(() => {\n if (\n this.requestManager.hasOutgoingRequests() ||\n this.requestManager.hasPendingRequests()\n ) {\n this.inactivityTimeout.reset();\n return;\n }\n\n this.close().catch(() => null);\n }, lazyOptions.closeMs);\n\n // Initialize the WebSocket connection.\n this.activeConnection = new WsConnection({\n WebSocketPonyfill: opts.WebSocket,\n urlOptions: opts,\n keepAlive: {\n ...keepAliveDefaults,\n ...opts.keepAlive,\n },\n encoder: this.encoder,\n });\n this.activeConnection.wsObservable.subscribe({\n next: (ws) => {\n if (!ws) return;\n this.setupWebSocketListeners(ws);\n },\n });\n this.reconnectRetryDelay = opts.retryDelayMs ?? exponentialBackoff;\n\n this.lazyMode = lazyOptions.enabled;\n\n this.connectionState = behaviorSubject<\n TRPCConnectionState<TRPCClientError<AnyTRPCRouter>>\n >({\n type: 'state',\n state: lazyOptions.enabled ? 'idle' : 'connecting',\n error: null,\n });\n\n // Automatically open the connection if lazy mode is disabled.\n if (!this.lazyMode) {\n this.open().catch(() => null);\n }\n }\n\n /**\n * Opens the WebSocket connection. Handles reconnection attempts and updates\n * the connection state accordingly.\n */\n private async open() {\n this.allowReconnect = true;\n if (this.connectionState.get().state === 'idle') {\n this.connectionState.next({\n type: 'state',\n state: 'connecting',\n error: null,\n });\n }\n\n try {\n await this.activeConnection.open();\n } catch (error) {\n this.reconnect(\n new TRPCWebSocketClosedError({\n message: 'Initialization error',\n cause: error,\n }),\n );\n return this.reconnecting;\n }\n }\n\n /**\n * Closes the WebSocket connection and stops managing requests.\n * Ensures all outgoing and pending requests are properly finalized.\n */\n public async close() {\n this.allowReconnect = false;\n this.inactivityTimeout.stop();\n\n const requestsToAwait: Promise<void>[] = [];\n for (const request of this.requestManager.getRequests()) {\n if (request.message.method === 'subscription') {\n request.callbacks.complete();\n } else if (request.state === 'outgoing') {\n request.callbacks.error(\n TRPCClientError.from(\n new TRPCWebSocketClosedError({\n message: 'Closed before connection was established',\n }),\n ),\n );\n } else {\n requestsToAwait.push(request.end);\n }\n }\n\n await Promise.all(requestsToAwait).catch(() => null);\n await this.activeConnection.close().catch(() => null);\n\n this.connectionState.next({\n type: 'state',\n state: 'idle',\n error: null,\n });\n }\n\n /**\n * Method to request the server.\n * Handles data transformation, batching of requests, and subscription lifecycle.\n *\n * @param op - The operation details including id, type, path, input and signal\n * @param transformer - Data transformer for serializing requests and deserializing responses\n * @param lastEventId - Optional ID of the last received event for subscriptions\n *\n * @returns An observable that emits operation results and handles cleanup\n */\n public request({\n op: { id, type, path, input, signal },\n transformer,\n lastEventId,\n }: {\n op: Pick<Operation, 'id' | 'type' | 'path' | 'input' | 'signal'>;\n transformer: CombinedDataTransformer;\n lastEventId?: string;\n }) {\n return observable<\n OperationResultEnvelope<unknown, TRPCClientError<AnyTRPCRouter>>,\n TRPCClientError<AnyTRPCRouter>\n >((observer) => {\n const abort = this.batchSend(\n {\n id,\n method: type,\n params: {\n input: transformer.input.serialize(input),\n path,\n lastEventId,\n },\n },\n {\n ...observer,\n next(event) {\n const transformed = transformResult(event, transformer.output);\n\n if (!transformed.ok) {\n observer.error(TRPCClientError.from(transformed.error));\n return;\n }\n\n observer.next({\n result: transformed.result,\n });\n },\n },\n );\n\n const onAbort = () => observer.complete();\n if (signal?.aborted) {\n onAbort();\n } else {\n signal?.addEventListener('abort', onAbort, { once: true });\n }\n\n return () => {\n abort();\n\n if (type === 'subscription' && this.activeConnection.isOpen()) {\n this.send({\n id,\n method: 'subscription.stop',\n });\n }\n\n signal?.removeEventListener('abort', onAbort);\n };\n });\n }\n\n public get connection() {\n return backwardCompatibility(this.activeConnection);\n }\n\n /**\n * Manages the reconnection process for the WebSocket using retry logic.\n * Ensures that only one reconnection attempt is active at a time by tracking the current\n * reconnection state in the `reconnecting` promise.\n */\n private reconnecting: Promise<void> | null = null;\n private reconnect(closedError: TRPCWebSocketClosedError) {\n this.connectionState.next({\n type: 'state',\n state: 'connecting',\n error: TRPCClientError.from(closedError),\n });\n if (this.reconnecting) return;\n\n const tryReconnect = async (attemptIndex: number) => {\n try {\n await sleep(this.reconnectRetryDelay(attemptIndex));\n if (this.allowReconnect) {\n await this.activeConnection.close();\n await this.activeConnection.open();\n\n if (this.requestManager.hasPendingRequests()) {\n this.send(\n this.requestManager\n .getPendingRequests()\n .map(({ message }) => message),\n );\n }\n }\n this.reconnecting = null;\n } catch {\n await tryReconnect(attemptIndex + 1);\n }\n };\n\n this.reconnecting = tryReconnect(0);\n }\n\n private setupWebSocketListeners(ws: WebSocket) {\n const handleCloseOrError = (cause: unknown) => {\n const reqs = this.requestManager.getPendingRequests();\n for (const { message, callbacks } of reqs) {\n if (message.method === 'subscription') continue;\n\n callbacks.error(\n TRPCClientError.from(\n cause ??\n new TRPCWebSocketClosedError({\n message: 'WebSocket closed',\n cause,\n }),\n ),\n );\n this.requestManager.delete(message.id);\n }\n };\n\n ws.addEventListener('open', () => {\n run(async () => {\n if (this.lazyMode) {\n this.inactivityTimeout.start();\n }\n\n this.callbacks.onOpen?.();\n\n this.connectionState.next({\n type: 'state',\n state: 'pending',\n error: null,\n });\n }).catch((error) => {\n ws.close(3000);\n handleCloseOrError(error);\n });\n });\n\n ws.addEventListener('message', ({ data }) => {\n this.inactivityTimeout.reset();\n\n // Handle PING/PONG as text regardless of encoder\n if (['PING', 'PONG'].includes(data)) return;\n\n const incomingMessage = this.encoder.decode(\n data,\n ) as TRPCClientIncomingMessage;\n if ('method' in incomingMessage) {\n this.handleIncomingRequest(incomingMessage);\n return;\n }\n\n this.handleResponseMessage(incomingMessage);\n });\n\n ws.addEventListener('close', (event) => {\n handleCloseOrError(event);\n this.callbacks.onClose?.(event);\n\n if (!this.lazyMode || this.requestManager.hasPendingSubscriptions()) {\n this.reconnect(\n new TRPCWebSocketClosedError({\n message: 'WebSocket closed',\n cause: event,\n }),\n );\n }\n });\n\n ws.addEventListener('error', (event) => {\n handleCloseOrError(event);\n this.callbacks.onError?.(event);\n\n this.reconnect(\n new TRPCWebSocketClosedError({\n message: 'WebSocket closed',\n cause: event,\n }),\n );\n });\n }\n\n private handleResponseMessage(message: TRPCResponseMessage) {\n const request = this.requestManager.getPendingRequest(message.id);\n if (!request) return;\n\n request.callbacks.next(message);\n\n let completed = true;\n if ('result' in message && request.message.method === 'subscription') {\n if (message.result.type === 'data') {\n request.message.params.lastEventId = message.result.id;\n }\n\n if (message.result.type !== 'stopped') {\n completed = false;\n }\n }\n\n if (completed) {\n request.callbacks.complete();\n this.requestManager.delete(message.id);\n }\n }\n\n private handleIncomingRequest(message: TRPCClientIncomingRequest) {\n if (message.method === 'reconnect') {\n this.reconnect(\n new TRPCWebSocketClosedError({\n message: 'Server requested reconnect',\n }),\n );\n }\n }\n\n /**\n * Sends a message or batch of messages directly to the server.\n */\n private send(\n messageOrMessages: TRPCClientOutgoingMessage | TRPCClientOutgoingMessage[],\n ) {\n if (!this.activeConnection.isOpen()) {\n throw new Error('Active connection is not open');\n }\n\n const messages =\n messageOrMessages instanceof Array\n ? messageOrMessages\n : [messageOrMessages];\n this.activeConnection.ws.send(\n this.encoder.encode(messages.length === 1 ? messages[0] : messages),\n );\n }\n\n /**\n * Groups requests for batch sending.\n *\n * @returns A function to abort the batched request.\n */\n private batchSend(message: TRPCClientOutgoingMessage, callbacks: TCallbacks) {\n this.inactivityTimeout.reset();\n\n run(async () => {\n if (!this.activeConnection.isOpen()) {\n await this.open();\n }\n await sleep(0);\n\n if (!this.requestManager.hasOutgoingRequests()) return;\n\n this.send(this.requestManager.flush().map(({ message }) => message));\n }).catch((err) => {\n this.requestManager.delete(message.id);\n callbacks.error(TRPCClientError.from(err));\n });\n\n return this.requestManager.register(message, callbacks);\n }\n}\n","/* istanbul ignore file -- @preserve */\n// We're not actually exporting this link\nimport type { Unsubscribable } from '@trpc/server/observable';\nimport { observable } from '@trpc/server/observable';\nimport type { InferrableClientTypes } from '@trpc/server/unstable-core-do-not-import';\nimport { inputWithTrackedEventId } from '../internals/inputWithTrackedEventId';\nimport type { TRPCClientError } from '../TRPCClientError';\nimport type { Operation, TRPCLink } from './types';\n\ninterface RetryLinkOptions<TInferrable extends InferrableClientTypes> {\n /**\n * The retry function\n */\n retry: (opts: RetryFnOptions<TInferrable>) => boolean;\n /**\n * The delay between retries in ms (defaults to 0)\n */\n retryDelayMs?: (attempt: number) => number;\n}\n\ninterface RetryFnOptions<TInferrable extends InferrableClientTypes> {\n /**\n * The operation that failed\n */\n op: Operation;\n /**\n * The error that occurred\n */\n error: TRPCClientError<TInferrable>;\n /**\n * The number of attempts that have been made (including the first call)\n */\n attempts: number;\n}\n\n/**\n * @see https://trpc.io/docs/v11/client/links/retryLink\n */\nexport function retryLink<TInferrable extends InferrableClientTypes>(\n opts: RetryLinkOptions<TInferrable>,\n): TRPCLink<TInferrable> {\n // initialized config\n return () => {\n // initialized in app\n return (callOpts) => {\n // initialized for request\n return observable((observer) => {\n let next$: Unsubscribable;\n let callNextTimeout: ReturnType<typeof setTimeout> | undefined =\n undefined;\n\n let lastEventId: string | undefined = undefined;\n\n attempt(1);\n\n function opWithLastEventId() {\n const op = callOpts.op;\n if (!lastEventId) {\n return op;\n }\n\n return {\n ...op,\n input: inputWithTrackedEventId(op.input, lastEventId),\n };\n }\n\n function attempt(attempts: number) {\n const op = opWithLastEventId();\n\n next$ = callOpts.next(op).subscribe({\n error(error) {\n const shouldRetry = opts.retry({\n op,\n attempts,\n error,\n });\n if (!shouldRetry) {\n observer.error(error);\n return;\n }\n const delayMs = opts.retryDelayMs?.(attempts) ?? 0;\n\n if (delayMs <= 0) {\n attempt(attempts + 1);\n return;\n }\n callNextTimeout = setTimeout(\n () => attempt(attempts + 1),\n delayMs,\n );\n },\n next(envelope) {\n //\n if (\n (!envelope.result.type || envelope.result.type === 'data') &&\n envelope.result.id\n ) {\n //\n lastEventId = envelope.result.id;\n }\n\n observer.next(envelope);\n },\n complete() {\n observer.complete();\n },\n });\n }\n return () => {\n next$.unsubscribe();\n clearTimeout(callNextTimeout);\n };\n });\n };\n };\n}\n","// @ts-expect-error - polyfilling symbol\n// eslint-disable-next-line no-restricted-syntax\nSymbol.dispose ??= Symbol();\n\n// @ts-expect-error - polyfilling symbol\n// eslint-disable-next-line no-restricted-syntax\nSymbol.asyncDispose ??= Symbol();\n\n/**\n * Takes a value and a dispose function and returns a new object that implements the Disposable interface.\n * The returned object is the original value augmented with a Symbol.dispose method.\n * @param thing The value to make disposable\n * @param dispose Function to call when disposing the resource\n * @returns The original value with Symbol.dispose method added\n */\nexport function makeResource<T>(thing: T, dispose: () => void): T & Disposable {\n const it = thing as T & Partial<Disposable>;\n\n // eslint-disable-next-line no-restricted-syntax\n const existing = it[Symbol.dispose];\n\n // eslint-disable-next-line no-restricted-syntax\n it[Symbol.dispose] = () => {\n dispose();\n existing?.call(it);\n };\n\n return it as T & Disposable;\n}\n\n/**\n * Takes a value and an async dispose function and returns a new object that implements the AsyncDisposable interface.\n * The returned object is the original value augmented with a Symbol.asyncDispose method.\n * @param thing The value to make async disposable\n * @param dispose Async function to call when disposing the resource\n * @returns The original value with Symbol.asyncDispose method added\n */\nexport function makeAsyncResource<T>(\n thing: T,\n dispose: () => Promise<void>,\n): T & AsyncDisposable {\n const it = thing as T & Partial<AsyncDisposable>;\n\n // eslint-disable-next-line no-restricted-syntax\n const existing = it[Symbol.asyncDispose];\n\n // eslint-disable-next-line no-restricted-syntax\n it[Symbol.asyncDispose] = async () => {\n await dispose();\n await existing?.call(it);\n };\n\n return it as T & AsyncDisposable;\n}\n","import { makeResource } from './disposable';\n\nexport const disposablePromiseTimerResult = Symbol();\n\nexport function timerResource(ms: number) {\n let timer: ReturnType<typeof setTimeout> | null = null;\n\n return makeResource(\n {\n start() {\n if (timer) {\n throw new Error('Timer already started');\n }\n\n const promise = new Promise<typeof disposablePromiseTimerResult>(\n (resolve) => {\n timer = setTimeout(() => resolve(disposablePromiseTimerResult), ms);\n },\n );\n return promise;\n },\n },\n () => {\n if (timer) {\n clearTimeout(timer);\n }\n },\n );\n}\n","import type { Encoder } from './wsClient/encoder';\nimport { jsonEncoder } from './wsClient/encoder';\nimport type { WebSocketClientOptions } from './wsClient/options';\nimport { WsClient } from './wsClient/wsClient';\n\nexport function createWSClient(opts: WebSocketClientOptions) {\n return new WsClient(opts);\n}\n\nexport type TRPCWebSocketClient = ReturnType<typeof createWSClient>;\n\nexport { jsonEncoder, type Encoder, type WebSocketClientOptions };\n","import { observable } from '@trpc/server/observable';\nimport type {\n AnyRouter,\n inferClientTypes,\n} from '@trpc/server/unstable-core-do-not-import';\nimport type { TransformerOptions } from '../../unstable-internals';\nimport { getTransformer } from '../../unstable-internals';\nimport type { TRPCLink } from '../types';\nimport type {\n Encoder,\n TRPCWebSocketClient,\n WebSocketClientOptions,\n} from './createWsClient';\nimport { createWSClient, jsonEncoder } from './createWsClient';\n\nexport type WebSocketLinkOptions<TRouter extends AnyRouter> = {\n client: TRPCWebSocketClient;\n} & TransformerOptions<inferClientTypes<TRouter>>;\n\nexport function wsLink<TRouter extends AnyRouter>(\n opts: WebSocketLinkOptions<TRouter>,\n): TRPCLink<TRouter> {\n const { client } = opts;\n const transformer = getTransformer(opts.transformer);\n return () => {\n return ({ op }) => {\n return observable((observer) => {\n const connStateSubscription =\n op.type === 'subscription'\n ? client.connectionState.subscribe({\n next(result) {\n observer.next({\n result,\n context: op.context,\n });\n },\n })\n : null;\n\n const requestSubscription = client\n .request({\n op,\n transformer,\n })\n .subscribe(observer);\n\n return () => {\n requestSubscription.unsubscribe();\n connStateSubscription?.unsubscribe();\n };\n });\n };\n };\n}\n\nexport {\n createWSClient,\n jsonEncoder,\n type Encoder,\n type TRPCWebSocketClient,\n type WebSocketClientOptions,\n};\n","import {\n getTRPCErrorFromUnknown,\n getTRPCErrorShape,\n isTrackedEnvelope,\n} from '@trpc/server';\nimport { behaviorSubject, observable } from '@trpc/server/observable';\nimport { TRPC_ERROR_CODES_BY_KEY, type TRPCResult } from '@trpc/server/rpc';\nimport {\n callProcedure,\n isAbortError,\n isAsyncIterable,\n iteratorResource,\n makeResource,\n retryableRpcCodes,\n run,\n type AnyRouter,\n type ErrorHandlerOptions,\n type inferClientTypes,\n type inferRouterContext,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { inputWithTrackedEventId } from '../internals/inputWithTrackedEventId';\nimport { abortSignalToPromise, raceAbortSignals } from '../internals/signals';\nimport { getTransformer } from '../internals/transformer';\nimport type { TransformerOptions } from '../internals/transformer';\nimport { isTRPCClientError, TRPCClientError } from '../TRPCClientError';\nimport type { TRPCConnectionState } from './internals/subscriptions';\nimport type { TRPCLink } from './types';\n\nexport type LocalLinkOptions<TRouter extends AnyRouter> = {\n router: TRouter;\n createContext: () => Promise<inferRouterContext<TRouter>>;\n onError?: (opts: ErrorHandlerOptions<inferRouterContext<TRouter>>) => void;\n} & TransformerOptions<inferClientTypes<TRouter>>;\n\n/**\n * localLink is a terminating link that allows you to make tRPC procedure calls directly in your application without going through HTTP.\n *\n * @see https://trpc.io/docs/links/localLink\n */\nexport function unstable_localLink<TRouter extends AnyRouter>(\n opts: LocalLinkOptions<TRouter>,\n): TRPCLink<TRouter> {\n const transformer = getTransformer(opts.transformer);\n\n const transformChunk = (chunk: unknown) => {\n if (opts.transformer) {\n // assume transformer will do the right thing\n return chunk;\n }\n // Special case for undefined, because `JSON.stringify(undefined)` throws\n if (chunk === undefined) {\n return chunk;\n }\n const serialized = JSON.stringify(transformer.input.serialize(chunk));\n const deserialized = JSON.parse(transformer.output.deserialize(serialized));\n return deserialized;\n };\n\n return () =>\n ({ op }) =>\n observable((observer) => {\n let ctx: inferRouterContext<TRouter> | undefined = undefined;\n const ac = new AbortController();\n\n const signal = raceAbortSignals(op.signal, ac.signal);\n const signalPromise = abortSignalToPromise(signal);\n\n signalPromise.catch(() => {\n // prevent unhandled rejection\n });\n\n let input = op.input;\n async function runProcedure(newInput: unknown): Promise<unknown> {\n input = newInput;\n\n ctx = await opts.createContext();\n\n return callProcedure({\n router: opts.router,\n path: op.path,\n getRawInput: async () => newInput,\n ctx,\n type: op.type,\n signal,\n batchIndex: 0,\n });\n }\n\n function onErrorCallback(cause: unknown) {\n if (isAbortError(cause)) {\n return;\n }\n opts.onError?.({\n error: getTRPCErrorFromUnknown(cause),\n type: op.type,\n path: op.path,\n input,\n ctx,\n });\n }\n\n function coerceToTRPCClientError(cause: unknown) {\n if (isTRPCClientError<TRouter>(cause)) {\n return cause;\n }\n const error = getTRPCErrorFromUnknown(cause);\n\n const shape = getTRPCErrorShape({\n config: opts.router._def._config,\n ctx,\n error,\n input,\n path: op.path,\n type: op.type,\n });\n return TRPCClientError.from(\n { error: transformChunk(shape) },\n { cause: cause instanceof Error ? cause : undefined },\n );\n }\n\n run(async () => {\n switch (op.type) {\n case 'query':\n case 'mutation': {\n const result = await runProcedure(op.input);\n if (!isAsyncIterable(result)) {\n observer.next({\n result: { data: transformChunk(result) },\n });\n observer.complete();\n break;\n }\n\n observer.next({\n result: {\n data: (async function* () {\n await using iterator = iteratorResource(result);\n using _finally = makeResource({}, () => {\n observer.complete();\n });\n try {\n while (true) {\n const res = await Promise.race([\n iterator.next(),\n signalPromise,\n ]);\n if (res.done) {\n return transformChunk(res.value);\n }\n yield transformChunk(res.value);\n }\n } catch (cause) {\n onErrorCallback(cause);\n throw coerceToTRPCClientError(cause);\n }\n })(),\n },\n });\n break;\n }\n case 'subscription': {\n const connectionState = behaviorSubject<\n TRPCConnectionState<TRPCClientError<any>>\n >({\n type: 'state',\n state: 'connecting',\n error: null,\n });\n\n const connectionSub = connectionState.subscribe({\n next(state) {\n observer.next({\n result: state,\n });\n },\n });\n let lastEventId: string | undefined = undefined;\n\n using _finally = makeResource({}, async () => {\n observer.complete();\n\n connectionState.next({\n type: 'state',\n state: 'idle',\n error: null,\n });\n connectionSub.unsubscribe();\n });\n while (true) {\n const result = await runProcedure(\n inputWithTrackedEventId(op.input, lastEventId),\n );\n if (!isAsyncIterable(result)) {\n throw new Error('Expected an async iterable');\n }\n await using iterator = iteratorResource(result);\n\n observer.next({\n result: {\n type: 'started',\n },\n });\n connectionState.next({\n type: 'state',\n state: 'pending',\n error: null,\n });\n\n // Use a while loop to handle errors and reconnects\n while (true) {\n let res;\n try {\n res = await Promise.race([iterator.next(), signalPromise]);\n } catch (cause) {\n if (isAbortError(cause)) {\n return;\n }\n const error = getTRPCErrorFromUnknown(cause);\n\n if (\n !retryableRpcCodes.includes(\n TRPC_ERROR_CODES_BY_KEY[error.code],\n )\n ) {\n throw coerceToTRPCClientError(error);\n }\n\n onErrorCallback(error);\n connectionState.next({\n type: 'state',\n state: 'connecting',\n error: coerceToTRPCClientError(error),\n });\n\n break;\n }\n\n if (res.done) {\n return;\n }\n let chunk: TRPCResult<unknown>;\n if (isTrackedEnvelope(res.value)) {\n lastEventId = res.value[0];\n\n chunk = {\n id: res.value[0],\n data: {\n id: res.value[0],\n data: res.value[1],\n },\n };\n } else {\n chunk = {\n data: res.value,\n };\n }\n\n observer.next({\n result: {\n ...chunk,\n data: transformChunk(chunk.data),\n },\n });\n }\n }\n break;\n }\n }\n }).catch((cause) => {\n onErrorCallback(cause);\n observer.error(coerceToTRPCClientError(cause));\n });\n\n return () => {\n ac.abort();\n };\n });\n}\n/**\n * @deprecated Renamed to `unstable_localLink`. This alias will be removed in a future major release.\n */\nexport const experimental_localLink: typeof unstable_localLink =\n unstable_localLink;\n","import { Unpromise } from '../../../vendor/unpromise';\nimport { throwAbortError } from '../../http/abortError';\nimport { makeAsyncResource } from './disposable';\nimport { disposablePromiseTimerResult, timerResource } from './timerResource';\n\nexport function iteratorResource<TYield, TReturn, TNext>(\n iterable: AsyncIterable<TYield, TReturn, TNext>,\n): AsyncIterator<TYield, TReturn, TNext> & AsyncDisposable {\n const iterator = iterable[Symbol.asyncIterator]();\n\n // @ts-expect-error - this is added in node 24 which we don't officially support yet\n // eslint-disable-next-line no-restricted-syntax\n if (iterator[Symbol.asyncDispose]) {\n return iterator as AsyncIterator<TYield, TReturn, TNext> & AsyncDisposable;\n }\n\n return makeAsyncResource(iterator, async () => {\n await iterator.return?.();\n });\n}\n\n/**\n * Derives a new {@link AsyncGenerator} based of {@link iterable}, that yields its first\n * {@link count} values. Then, a grace period of {@link gracePeriodMs} is started in which further\n * values may still come through. After this period, the generator aborts.\n */\nexport async function* takeWithGrace<T>(\n iterable: AsyncIterable<T>,\n opts: {\n count: number;\n gracePeriodMs: number;\n },\n): AsyncGenerator<T> {\n await using iterator = iteratorResource(iterable);\n\n // declaration outside the loop for garbage collection reasons\n let result: null | IteratorResult<T> | typeof disposablePromiseTimerResult;\n\n using timer = timerResource(opts.gracePeriodMs);\n\n let count = opts.count;\n\n let timerPromise = new Promise<typeof disposablePromiseTimerResult>(() => {\n // never resolves\n });\n\n while (true) {\n result = await Unpromise.race([iterator.next(), timerPromise]);\n if (result === disposablePromiseTimerResult) {\n throwAbortError();\n }\n if (result.done) {\n return result.value;\n }\n yield result.value;\n if (--count === 0) {\n timerPromise = timer.start();\n }\n // free up reference for garbage collection\n result = null;\n }\n}\n","/* eslint-disable @typescript-eslint/no-non-null-assertion */\nexport function createDeferred<TValue = void>() {\n let resolve: (value: TValue) => void;\n let reject: (error: unknown) => void;\n const promise = new Promise<TValue>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n\n return { promise, resolve: resolve!, reject: reject! };\n}\nexport type Deferred<TValue> = ReturnType<typeof createDeferred<TValue>>;\n","import { createDeferred } from './createDeferred';\nimport { makeAsyncResource } from './disposable';\n\ntype ManagedIteratorResult<TYield, TReturn> =\n | { status: 'yield'; value: TYield }\n | { status: 'return'; value: TReturn }\n | { status: 'error'; error: unknown };\nfunction createManagedIterator<TYield, TReturn>(\n iterable: AsyncIterable<TYield, TReturn>,\n onResult: (result: ManagedIteratorResult<TYield, TReturn>) => void,\n) {\n const iterator = iterable[Symbol.asyncIterator]();\n let state: 'idle' | 'pending' | 'done' = 'idle';\n\n function cleanup() {\n state = 'done';\n onResult = () => {\n // noop\n };\n }\n\n function pull() {\n if (state !== 'idle') {\n return;\n }\n state = 'pending';\n\n const next = iterator.next();\n next\n .then((result) => {\n if (result.done) {\n state = 'done';\n onResult({ status: 'return', value: result.value });\n cleanup();\n return;\n }\n state = 'idle';\n onResult({ status: 'yield', value: result.value });\n })\n .catch((cause) => {\n onResult({ status: 'error', error: cause });\n cleanup();\n });\n }\n\n return {\n pull,\n destroy: async () => {\n cleanup();\n await iterator.return?.();\n },\n };\n}\ntype ManagedIterator<TYield, TReturn> = ReturnType<\n typeof createManagedIterator<TYield, TReturn>\n>;\n\ninterface MergedAsyncIterables<TYield> extends AsyncIterable<\n TYield,\n void,\n unknown\n> {\n add(iterable: AsyncIterable<TYield>): void;\n}\n\n/**\n * Creates a new async iterable that merges multiple async iterables into a single stream.\n * Values from the input iterables are yielded in the order they resolve, similar to Promise.race().\n *\n * New iterables can be added dynamically using the returned {@link MergedAsyncIterables.add} method, even after iteration has started.\n *\n * If any of the input iterables throws an error, that error will be propagated through the merged stream.\n * Other iterables will not continue to be processed.\n *\n * @template TYield The type of values yielded by the input iterables\n */\nexport function mergeAsyncIterables<TYield>(): MergedAsyncIterables<TYield> {\n let state: 'idle' | 'pending' | 'done' = 'idle';\n let flushSignal = createDeferred();\n\n /**\n * used while {@link state} is `idle`\n */\n const iterables: AsyncIterable<TYield, void, unknown>[] = [];\n /**\n * used while {@link state} is `pending`\n */\n const iterators = new Set<ManagedIterator<TYield, void>>();\n\n const buffer: Array<\n [\n iterator: ManagedIterator<TYield, void>,\n result: Exclude<\n ManagedIteratorResult<TYield, void>,\n { status: 'return' }\n >,\n ]\n > = [];\n\n function initIterable(iterable: AsyncIterable<TYield, void, unknown>) {\n if (state !== 'pending') {\n // shouldn't happen\n return;\n }\n const iterator = createManagedIterator(iterable, (result) => {\n if (state !== 'pending') {\n // shouldn't happen\n return;\n }\n switch (result.status) {\n case 'yield':\n buffer.push([iterator, result]);\n break;\n case 'return':\n iterators.delete(iterator);\n break;\n case 'error':\n buffer.push([iterator, result]);\n iterators.delete(iterator);\n break;\n }\n flushSignal.resolve();\n });\n iterators.add(iterator);\n iterator.pull();\n }\n\n return {\n add(iterable: AsyncIterable<TYield, void, unknown>) {\n switch (state) {\n case 'idle':\n iterables.push(iterable);\n break;\n case 'pending':\n initIterable(iterable);\n break;\n case 'done': {\n // shouldn't happen\n break;\n }\n }\n },\n async *[Symbol.asyncIterator]() {\n if (state !== 'idle') {\n throw new Error('Cannot iterate twice');\n }\n state = 'pending';\n\n await using _finally = makeAsyncResource({}, async () => {\n state = 'done';\n\n const errors: unknown[] = [];\n await Promise.all(\n Array.from(iterators.values()).map(async (it) => {\n try {\n await it.destroy();\n } catch (cause) {\n errors.push(cause);\n }\n }),\n );\n buffer.length = 0;\n iterators.clear();\n flushSignal.resolve();\n\n if (errors.length > 0) {\n throw new AggregateError(errors);\n }\n });\n\n while (iterables.length > 0) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n initIterable(iterables.shift()!);\n }\n\n while (iterators.size > 0) {\n await flushSignal.promise;\n\n while (buffer.length > 0) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const [iterator, result] = buffer.shift()!;\n\n switch (result.status) {\n case 'yield':\n yield result.value;\n iterator.pull();\n break;\n case 'error':\n throw result.error;\n }\n }\n flushSignal = createDeferred();\n }\n },\n };\n}\n","/**\n * Creates a ReadableStream from an AsyncIterable.\n *\n * @param iterable - The source AsyncIterable to stream from\n * @returns A ReadableStream that yields values from the AsyncIterable\n */\nexport function readableStreamFrom<TYield>(\n iterable: AsyncIterable<TYield, void>,\n): ReadableStream<TYield> {\n const iterator = iterable[Symbol.asyncIterator]();\n\n return new ReadableStream({\n async cancel() {\n await iterator.return?.();\n },\n\n async pull(controller) {\n const result = await iterator.next();\n\n if (result.done) {\n controller.close();\n return;\n }\n\n controller.enqueue(result.value);\n },\n });\n}\n","import { Unpromise } from '../../../vendor/unpromise';\nimport { iteratorResource } from './asyncIterable';\nimport { disposablePromiseTimerResult, timerResource } from './timerResource';\n\nexport const PING_SYM = Symbol('ping');\n\n/**\n * Derives a new {@link AsyncGenerator} based of {@link iterable}, that yields {@link PING_SYM}\n * whenever no value has been yielded for {@link pingIntervalMs}.\n */\nexport async function* withPing<TValue>(\n iterable: AsyncIterable<TValue>,\n pingIntervalMs: number,\n): AsyncGenerator<TValue | typeof PING_SYM> {\n await using iterator = iteratorResource(iterable);\n\n // declaration outside the loop for garbage collection reasons\n let result:\n null | IteratorResult<TValue> | typeof disposablePromiseTimerResult;\n\n let nextPromise = iterator.next();\n\n while (true) {\n using pingPromise = timerResource(pingIntervalMs);\n\n result = await Unpromise.race([nextPromise, pingPromise.start()]);\n\n if (result === disposablePromiseTimerResult) {\n // cancelled\n\n yield PING_SYM;\n continue;\n }\n\n if (result.done) {\n return result.value;\n }\n\n nextPromise = iterator.next();\n yield result.value;\n\n // free up reference for garbage collection\n result = null;\n }\n}\n","import { isPlainObject } from '@trpc/server/vendor/is-plain-object';\nimport {\n emptyObject,\n isAsyncIterable,\n isFunction,\n isObject,\n run,\n} from '../utils';\nimport { iteratorResource } from './utils/asyncIterable';\nimport type { Deferred } from './utils/createDeferred';\nimport { createDeferred } from './utils/createDeferred';\nimport { makeResource } from './utils/disposable';\nimport { mergeAsyncIterables } from './utils/mergeAsyncIterables';\nimport { readableStreamFrom } from './utils/readableStreamFrom';\nimport { PING_SYM, withPing } from './utils/withPing';\n\n/**\n * A subset of the standard ReadableStream properties needed by tRPC internally.\n * @see ReadableStream from lib.dom.d.ts\n */\nexport type WebReadableStreamEsque = {\n getReader: () => ReadableStreamDefaultReader<Uint8Array>;\n};\n\nexport type NodeJSReadableStreamEsque = {\n on(\n eventName: string | symbol,\n listener: (...args: any[]) => void,\n ): NodeJSReadableStreamEsque;\n};\n\n// ---------- types\nconst CHUNK_VALUE_TYPE_PROMISE = 0;\ntype CHUNK_VALUE_TYPE_PROMISE = typeof CHUNK_VALUE_TYPE_PROMISE;\nconst CHUNK_VALUE_TYPE_ASYNC_ITERABLE = 1;\ntype CHUNK_VALUE_TYPE_ASYNC_ITERABLE = typeof CHUNK_VALUE_TYPE_ASYNC_ITERABLE;\n\nconst PROMISE_STATUS_FULFILLED = 0;\ntype PROMISE_STATUS_FULFILLED = typeof PROMISE_STATUS_FULFILLED;\nconst PROMISE_STATUS_REJECTED = 1;\ntype PROMISE_STATUS_REJECTED = typeof PROMISE_STATUS_REJECTED;\n\nconst ASYNC_ITERABLE_STATUS_RETURN = 0;\ntype ASYNC_ITERABLE_STATUS_RETURN = typeof ASYNC_ITERABLE_STATUS_RETURN;\nconst ASYNC_ITERABLE_STATUS_YIELD = 1;\ntype ASYNC_ITERABLE_STATUS_YIELD = typeof ASYNC_ITERABLE_STATUS_YIELD;\nconst ASYNC_ITERABLE_STATUS_ERROR = 2;\ntype ASYNC_ITERABLE_STATUS_ERROR = typeof ASYNC_ITERABLE_STATUS_ERROR;\n\ntype ChunkDefinitionKey =\n // root should be replaced\n | null\n // at array path\n | number\n // at key path\n | string;\n\ntype ChunkIndex = number & { __chunkIndex: true };\ntype ChunkValueType =\n CHUNK_VALUE_TYPE_PROMISE | CHUNK_VALUE_TYPE_ASYNC_ITERABLE;\ntype ChunkDefinition = [\n key: ChunkDefinitionKey,\n type: ChunkValueType,\n chunkId: ChunkIndex,\n];\ntype EncodedValue = [\n // data\n [unknown] | [],\n // chunk descriptions\n ...ChunkDefinition[],\n];\n\ntype Head = Record<string, EncodedValue>;\ntype PromiseChunk =\n | [\n chunkIndex: ChunkIndex,\n status: PROMISE_STATUS_FULFILLED,\n value: EncodedValue,\n ]\n | [chunkIndex: ChunkIndex, status: PROMISE_STATUS_REJECTED, error: unknown];\ntype IterableChunk =\n | [\n chunkIndex: ChunkIndex,\n status: ASYNC_ITERABLE_STATUS_RETURN,\n value: EncodedValue,\n ]\n | [\n chunkIndex: ChunkIndex,\n status: ASYNC_ITERABLE_STATUS_YIELD,\n value: EncodedValue,\n ]\n | [\n chunkIndex: ChunkIndex,\n status: ASYNC_ITERABLE_STATUS_ERROR,\n error: unknown,\n ];\ntype ChunkData = PromiseChunk | IterableChunk;\ntype PlaceholderValue = 0 & { __placeholder: true };\nexport function isPromise(value: unknown): value is Promise<unknown> {\n return (\n (isObject(value) || isFunction(value)) &&\n typeof value?.['then'] === 'function' &&\n typeof value?.['catch'] === 'function'\n );\n}\n\ntype Serialize = (value: any) => any;\ntype Deserialize = (value: any) => any;\n\ntype PathArray = readonly (string | number)[];\nexport type ProducerOnError = (opts: {\n error: unknown;\n path: PathArray;\n}) => void;\nexport interface JSONLProducerOptions {\n serialize?: Serialize;\n data: Record<string, unknown> | unknown[];\n onError?: ProducerOnError;\n formatError?: (opts: { error: unknown; path: PathArray }) => unknown;\n maxDepth?: number;\n /**\n * Interval in milliseconds to send a ping to the client to keep the connection alive\n * This will be sent as a whitespace character\n * @default undefined\n */\n pingMs?: number;\n}\n\nclass MaxDepthError extends Error {\n constructor(public path: (string | number)[]) {\n super('Max depth reached at path: ' + path.join('.'));\n }\n}\n\nasync function* createBatchStreamProducer(\n opts: JSONLProducerOptions,\n): AsyncIterable<Head | ChunkData | typeof PING_SYM, void> {\n const { data } = opts;\n let counter = 0 as ChunkIndex;\n const placeholder = 0 as PlaceholderValue;\n\n const mergedIterables = mergeAsyncIterables<ChunkData>();\n function registerAsync(\n callback: (idx: ChunkIndex) => AsyncIterable<ChunkData, void>,\n ) {\n const idx = counter++ as ChunkIndex;\n\n const iterable = callback(idx);\n mergedIterables.add(iterable);\n\n return idx;\n }\n\n function encodePromise(promise: Promise<unknown>, path: (string | number)[]) {\n return registerAsync(async function* (idx) {\n const error = checkMaxDepth(path);\n if (error) {\n // Catch any errors from the original promise to ensure they're reported\n promise.catch((cause) => {\n opts.onError?.({ error: cause, path });\n });\n // Replace the promise with a rejected one containing the max depth error\n promise = Promise.reject(error);\n }\n try {\n const next = await promise;\n yield [idx, PROMISE_STATUS_FULFILLED, encode(next, path)];\n } catch (cause) {\n opts.onError?.({ error: cause, path });\n yield [\n idx,\n PROMISE_STATUS_REJECTED,\n opts.formatError?.({ error: cause, path }),\n ];\n }\n });\n }\n function encodeAsyncIterable(\n iterable: AsyncIterable<unknown>,\n path: (string | number)[],\n ) {\n return registerAsync(async function* (idx) {\n const error = checkMaxDepth(path);\n if (error) {\n throw error;\n }\n await using iterator = iteratorResource(iterable);\n\n try {\n while (true) {\n const next = await iterator.next();\n if (next.done) {\n yield [idx, ASYNC_ITERABLE_STATUS_RETURN, encode(next.value, path)];\n break;\n }\n yield [idx, ASYNC_ITERABLE_STATUS_YIELD, encode(next.value, path)];\n }\n } catch (cause) {\n opts.onError?.({ error: cause, path });\n\n yield [\n idx,\n ASYNC_ITERABLE_STATUS_ERROR,\n opts.formatError?.({ error: cause, path }),\n ];\n }\n });\n }\n function checkMaxDepth(path: (string | number)[]) {\n if (opts.maxDepth && path.length > opts.maxDepth) {\n return new MaxDepthError(path);\n }\n return null;\n }\n function encodeAsync(\n value: unknown,\n path: (string | number)[],\n ): null | [type: ChunkValueType, chunkId: ChunkIndex] {\n if (isPromise(value)) {\n return [CHUNK_VALUE_TYPE_PROMISE, encodePromise(value, path)];\n }\n if (isAsyncIterable(value)) {\n if (opts.maxDepth && path.length >= opts.maxDepth) {\n throw new Error('Max depth reached');\n }\n return [\n CHUNK_VALUE_TYPE_ASYNC_ITERABLE,\n encodeAsyncIterable(value, path),\n ];\n }\n return null;\n }\n function encode(value: unknown, path: (string | number)[]): EncodedValue {\n if (value === undefined) {\n return [[]];\n }\n const reg = encodeAsync(value, path);\n if (reg) {\n return [[placeholder], [null, ...reg]];\n }\n\n if (!isPlainObject(value)) {\n return [[value]];\n }\n\n const newObj: Record<string, unknown> = emptyObject();\n const asyncValues: ChunkDefinition[] = [];\n for (const [key, item] of Object.entries(value)) {\n const transformed = encodeAsync(item, [...path, key]);\n if (!transformed) {\n newObj[key] = item;\n continue;\n }\n newObj[key] = placeholder;\n asyncValues.push([key, ...transformed]);\n }\n return [[newObj], ...asyncValues];\n }\n\n const newHead: Head = emptyObject();\n for (const [key, item] of Object.entries(data)) {\n newHead[key] = encode(item, [key]);\n }\n\n yield newHead;\n\n let iterable: AsyncIterable<ChunkData | typeof PING_SYM, void> =\n mergedIterables;\n if (opts.pingMs) {\n iterable = withPing(mergedIterables, opts.pingMs);\n }\n\n for await (const value of iterable) {\n yield value;\n }\n}\n/**\n * JSON Lines stream producer\n * @see https://jsonlines.org/\n */\nexport function jsonlStreamProducer(opts: JSONLProducerOptions) {\n let stream = readableStreamFrom(createBatchStreamProducer(opts));\n\n const { serialize } = opts;\n if (serialize) {\n stream = stream.pipeThrough(\n new TransformStream({\n transform(chunk, controller) {\n if (chunk === PING_SYM) {\n controller.enqueue(PING_SYM);\n } else {\n controller.enqueue(serialize(chunk));\n }\n },\n }),\n );\n }\n\n return stream\n .pipeThrough(\n new TransformStream({\n transform(chunk, controller) {\n if (chunk === PING_SYM) {\n controller.enqueue(' ');\n } else {\n controller.enqueue(JSON.stringify(chunk) + '\\n');\n }\n },\n }),\n )\n .pipeThrough(new TextEncoderStream());\n}\n\nclass AsyncError extends Error {\n constructor(public readonly data: unknown) {\n super('Received error from server');\n }\n}\nexport type ConsumerOnError = (opts: { error: unknown }) => void;\n\nconst nodeJsStreamToReaderEsque = (source: NodeJSReadableStreamEsque) => {\n return {\n getReader() {\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n source.on('data', (chunk) => {\n controller.enqueue(chunk);\n });\n source.on('end', () => {\n controller.close();\n });\n source.on('error', (error) => {\n controller.error(error);\n });\n },\n });\n return stream.getReader();\n },\n };\n};\n\nfunction createLineAccumulator(\n from: NodeJSReadableStreamEsque | WebReadableStreamEsque,\n) {\n const reader =\n 'getReader' in from\n ? from.getReader()\n : nodeJsStreamToReaderEsque(from).getReader();\n\n let lineAggregate = '';\n\n return new ReadableStream({\n async pull(controller) {\n const { done, value } = await reader.read();\n\n if (done) {\n controller.close();\n } else {\n controller.enqueue(value);\n }\n },\n cancel() {\n return reader.cancel();\n },\n })\n .pipeThrough(new TextDecoderStream())\n .pipeThrough(\n new TransformStream<string, string>({\n transform(chunk, controller) {\n lineAggregate += chunk;\n const parts = lineAggregate.split('\\n');\n lineAggregate = parts.pop() ?? '';\n for (const part of parts) {\n controller.enqueue(part);\n }\n },\n }),\n );\n}\nfunction createConsumerStream<THead>(\n from: NodeJSReadableStreamEsque | WebReadableStreamEsque,\n) {\n const stream = createLineAccumulator(from);\n\n let sentHead = false;\n return stream.pipeThrough(\n new TransformStream<string, ChunkData | THead>({\n transform(line, controller) {\n if (!sentHead) {\n const head = JSON.parse(line);\n controller.enqueue(head as THead);\n sentHead = true;\n } else {\n const chunk: ChunkData = JSON.parse(line);\n controller.enqueue(chunk);\n }\n },\n }),\n );\n}\n\n/**\n * Creates a handler for managing stream controllers and their lifecycle\n */\nfunction createStreamsManager(abortController: AbortController) {\n const controllerMap = new Map<\n ChunkIndex,\n ReturnType<typeof createStreamController>\n >();\n\n /**\n * Checks if there are no pending controllers or deferred promises\n */\n function isEmpty() {\n return Array.from(controllerMap.values()).every((c) => c.closed);\n }\n\n /**\n * Creates a stream controller\n */\n function createStreamController() {\n let originalController: ReadableStreamDefaultController<ChunkData>;\n const stream = new ReadableStream<ChunkData>({\n start(controller) {\n originalController = controller;\n },\n });\n\n const streamController = {\n enqueue: (v: ChunkData) => originalController.enqueue(v),\n close: () => {\n originalController.close();\n\n clear();\n\n if (isEmpty()) {\n abortController.abort();\n }\n },\n closed: false,\n getReaderResource: () => {\n const reader = stream.getReader();\n\n return makeResource(reader, () => {\n streamController.close();\n reader.releaseLock();\n });\n },\n error: (reason: unknown) => {\n originalController.error(reason);\n\n clear();\n },\n };\n function clear() {\n Object.assign(streamController, {\n closed: true,\n close: () => {\n // noop\n },\n enqueue: () => {\n // noop\n },\n getReaderResource: null,\n error: () => {\n // noop\n },\n });\n }\n\n return streamController;\n }\n\n /**\n * Gets or creates a stream controller\n */\n function getOrCreate(chunkId: ChunkIndex) {\n let c = controllerMap.get(chunkId);\n if (!c) {\n c = createStreamController();\n controllerMap.set(chunkId, c);\n }\n return c;\n }\n\n /**\n * Cancels all pending controllers and rejects deferred promises\n */\n function cancelAll(reason: unknown) {\n for (const controller of controllerMap.values()) {\n controller.error(reason);\n }\n }\n\n /**\n * Closes all pending controllers to preserve buffered data\n */\n function closeAll() {\n for (const controller of controllerMap.values()) {\n controller.close();\n }\n }\n\n return {\n getOrCreate,\n cancelAll,\n closeAll,\n };\n}\n\n/**\n * JSON Lines stream consumer\n * @see https://jsonlines.org/\n */\nexport async function jsonlStreamConsumer<THead>(opts: {\n from: NodeJSReadableStreamEsque | WebReadableStreamEsque;\n deserialize?: Deserialize;\n onError?: ConsumerOnError;\n formatError?: (opts: { error: unknown }) => Error;\n /**\n * This `AbortController` will be triggered when there are no more listeners to the stream.\n */\n abortController: AbortController;\n}) {\n const { deserialize = (v) => v } = opts;\n\n let source = createConsumerStream<Head>(opts.from);\n if (deserialize) {\n source = source.pipeThrough(\n new TransformStream({\n transform(chunk, controller) {\n controller.enqueue(deserialize(chunk));\n },\n }),\n );\n }\n let headDeferred: null | Deferred<THead> = createDeferred();\n\n const streamManager = createStreamsManager(opts.abortController);\n\n function decodeChunkDefinition(value: ChunkDefinition) {\n const [_path, type, chunkId] = value;\n\n const controller = streamManager.getOrCreate(chunkId);\n\n switch (type) {\n case CHUNK_VALUE_TYPE_PROMISE: {\n return run(async () => {\n using reader = controller.getReaderResource();\n\n const { value } = await reader.read();\n const [_chunkId, status, data] = value as PromiseChunk;\n switch (status) {\n case PROMISE_STATUS_FULFILLED:\n return decode(data);\n case PROMISE_STATUS_REJECTED:\n throw opts.formatError?.({ error: data }) ?? new AsyncError(data);\n }\n });\n }\n case CHUNK_VALUE_TYPE_ASYNC_ITERABLE: {\n return run(async function* () {\n using reader = controller.getReaderResource();\n\n while (true) {\n const { value } = await reader.read();\n\n const [_chunkId, status, data] = value as IterableChunk;\n\n switch (status) {\n case ASYNC_ITERABLE_STATUS_YIELD:\n yield decode(data);\n break;\n case ASYNC_ITERABLE_STATUS_RETURN:\n return decode(data);\n case ASYNC_ITERABLE_STATUS_ERROR:\n throw (\n opts.formatError?.({ error: data }) ?? new AsyncError(data)\n );\n }\n }\n });\n }\n }\n }\n\n function decode(value: EncodedValue): unknown {\n const [[data], ...asyncProps] = value;\n\n for (const value of asyncProps) {\n const [key] = value;\n const decoded = decodeChunkDefinition(value);\n\n if (key === null) {\n return decoded;\n }\n\n (data as any)[key] = decoded;\n }\n return data;\n }\n\n const handleClose = () => {\n // If the stream closes before emitting any head data,\n // we need to reject the headDeferred to prevent hanging\n if (headDeferred) {\n headDeferred.reject(new Error('Stream closed before head was received'));\n headDeferred = null;\n }\n // Close stream controllers (not error them)\n // to preserve any buffered chunks\n streamManager.closeAll();\n };\n\n const handleAbort = (reason?: unknown) => {\n headDeferred?.reject(reason);\n headDeferred = null;\n streamManager.cancelAll(reason);\n };\n\n source\n .pipeTo(\n new WritableStream({\n write(chunkOrHead) {\n if (headDeferred) {\n const head = chunkOrHead as Record<number | string, unknown>;\n\n for (const [key, value] of Object.entries(chunkOrHead)) {\n const parsed = decode(value as any);\n head[key] = parsed;\n }\n headDeferred.resolve(head as THead);\n headDeferred = null;\n\n return;\n }\n const chunk = chunkOrHead as ChunkData;\n const [idx] = chunk;\n\n const controller = streamManager.getOrCreate(idx);\n controller.enqueue(chunk);\n },\n close: handleClose,\n abort: handleAbort,\n }),\n )\n .catch((error) => {\n opts.onError?.({ error });\n handleAbort(error);\n });\n\n return [await headDeferred.promise] as const;\n}\n","import { Unpromise } from '../../vendor/unpromise';\nimport { getTRPCErrorFromUnknown } from '../error/TRPCError';\nimport { isAbortError } from '../http/abortError';\nimport type { MaybePromise } from '../types';\nimport { emptyObject, identity, run } from '../utils';\nimport type { EventSourceLike } from './sse.types';\nimport type { inferTrackedOutput } from './tracked';\nimport { isTrackedEnvelope } from './tracked';\nimport { takeWithGrace } from './utils/asyncIterable';\nimport { makeAsyncResource } from './utils/disposable';\nimport { readableStreamFrom } from './utils/readableStreamFrom';\nimport {\n disposablePromiseTimerResult,\n timerResource,\n} from './utils/timerResource';\nimport { PING_SYM, withPing } from './utils/withPing';\n\ntype Serialize = (value: any) => any;\ntype Deserialize = (value: any) => any;\n\n/**\n * @internal\n */\nexport interface SSEPingOptions {\n /**\n * Enable ping comments sent from the server\n * @default false\n */\n enabled: boolean;\n /**\n * Interval in milliseconds\n * @default 1000\n */\n intervalMs?: number;\n}\n\nexport interface SSEClientOptions {\n /**\n * Timeout and reconnect after inactivity in milliseconds\n * @default undefined\n */\n reconnectAfterInactivityMs?: number;\n}\n\nexport interface SSEStreamProducerOptions<TValue = unknown> {\n serialize?: Serialize;\n data: AsyncIterable<TValue>;\n\n maxDepth?: number;\n ping?: SSEPingOptions;\n /**\n * Maximum duration in milliseconds for the request before ending the stream\n * @default undefined\n */\n maxDurationMs?: number;\n /**\n * End the request immediately after data is sent\n * Only useful for serverless runtimes that do not support streaming responses\n * @default false\n */\n emitAndEndImmediately?: boolean;\n formatError?: (opts: { error: unknown }) => unknown;\n /**\n * Client-specific options - these will be sent to the client as part of the first message\n * @default {}\n */\n client?: SSEClientOptions;\n}\n\nconst PING_EVENT = 'ping';\nconst SERIALIZED_ERROR_EVENT = 'serialized-error';\nconst CONNECTED_EVENT = 'connected';\nconst RETURN_EVENT = 'return';\n\ninterface SSEvent {\n id?: string;\n data: unknown;\n comment?: string;\n event?: string;\n}\n/**\n *\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html\n */\nexport function sseStreamProducer<TValue = unknown>(\n opts: SSEStreamProducerOptions<TValue>,\n) {\n const { serialize = identity } = opts;\n\n const ping: Required<SSEPingOptions> = {\n enabled: opts.ping?.enabled ?? false,\n intervalMs: opts.ping?.intervalMs ?? 1000,\n };\n const client: SSEClientOptions = opts.client ?? {};\n\n if (\n ping.enabled &&\n client.reconnectAfterInactivityMs &&\n ping.intervalMs > client.reconnectAfterInactivityMs\n ) {\n throw new Error(\n `Ping interval must be less than client reconnect interval to prevent unnecessary reconnection - ping.intervalMs: ${ping.intervalMs} client.reconnectAfterInactivityMs: ${client.reconnectAfterInactivityMs}`,\n );\n }\n\n async function* generator(): AsyncIterable<SSEvent, void> {\n yield {\n event: CONNECTED_EVENT,\n data: JSON.stringify(client),\n };\n\n type TIteratorValue = Awaited<TValue> | typeof PING_SYM;\n\n let iterable: AsyncIterable<TValue | typeof PING_SYM> = opts.data;\n\n if (opts.emitAndEndImmediately) {\n iterable = takeWithGrace(iterable, {\n count: 1,\n gracePeriodMs: 1,\n });\n }\n\n if (ping.enabled && ping.intervalMs !== Infinity && ping.intervalMs > 0) {\n iterable = withPing(iterable, ping.intervalMs);\n }\n\n // We need those declarations outside the loop for garbage collection reasons. If they were\n // declared inside, they would not be freed until the next value is present.\n let value: null | TIteratorValue;\n let chunk: null | SSEvent;\n\n for await (value of iterable) {\n if (value === PING_SYM) {\n yield { event: PING_EVENT, data: '' };\n continue;\n }\n\n chunk = isTrackedEnvelope(value)\n ? { id: value[0], data: value[1] }\n : { data: value };\n\n chunk.data = JSON.stringify(serialize(chunk.data));\n\n yield chunk;\n\n // free up references for garbage collection\n value = null;\n chunk = null;\n }\n }\n\n async function* generatorWithErrorHandling(): AsyncIterable<SSEvent, void> {\n try {\n yield* generator();\n\n yield {\n event: RETURN_EVENT,\n data: '',\n };\n } catch (cause) {\n if (isAbortError(cause)) {\n // ignore abort errors, send any other errors\n return;\n }\n // `err` must be caused by `opts.data`, `JSON.stringify` or `serialize`.\n // So, a user error in any case.\n const error = getTRPCErrorFromUnknown(cause);\n const data = opts.formatError?.({ error }) ?? null;\n yield {\n event: SERIALIZED_ERROR_EVENT,\n data: JSON.stringify(serialize(data)),\n };\n }\n }\n\n const stream = readableStreamFrom(generatorWithErrorHandling());\n\n return stream\n .pipeThrough(\n new TransformStream({\n transform(chunk, controller: TransformStreamDefaultController<string>) {\n if ('event' in chunk) {\n controller.enqueue(`event: ${chunk.event}\\n`);\n }\n if ('data' in chunk) {\n controller.enqueue(`data: ${chunk.data}\\n`);\n }\n if ('id' in chunk) {\n controller.enqueue(`id: ${chunk.id}\\n`);\n }\n if ('comment' in chunk) {\n controller.enqueue(`: ${chunk.comment}\\n`);\n }\n controller.enqueue('\\n\\n');\n },\n }),\n )\n .pipeThrough(new TextEncoderStream());\n}\n\ninterface ConsumerStreamResultBase<TConfig extends ConsumerConfig> {\n eventSource: InstanceType<TConfig['EventSource']> | null;\n}\n\ninterface ConsumerStreamResultData<\n TConfig extends ConsumerConfig,\n> extends ConsumerStreamResultBase<TConfig> {\n type: 'data';\n data: inferTrackedOutput<TConfig['data']>;\n}\n\ninterface ConsumerStreamResultError<\n TConfig extends ConsumerConfig,\n> extends ConsumerStreamResultBase<TConfig> {\n type: 'serialized-error';\n error: TConfig['error'];\n}\n\ninterface ConsumerStreamResultConnecting<\n TConfig extends ConsumerConfig,\n> extends ConsumerStreamResultBase<TConfig> {\n type: 'connecting';\n event: EventSourceLike.EventOf<TConfig['EventSource']> | null;\n}\ninterface ConsumerStreamResultTimeout<\n TConfig extends ConsumerConfig,\n> extends ConsumerStreamResultBase<TConfig> {\n type: 'timeout';\n ms: number;\n}\ninterface ConsumerStreamResultPing<\n TConfig extends ConsumerConfig,\n> extends ConsumerStreamResultBase<TConfig> {\n type: 'ping';\n}\n\ninterface ConsumerStreamResultConnected<\n TConfig extends ConsumerConfig,\n> extends ConsumerStreamResultBase<TConfig> {\n type: 'connected';\n options: SSEClientOptions;\n}\n\ntype ConsumerStreamResult<TConfig extends ConsumerConfig> =\n | ConsumerStreamResultData<TConfig>\n | ConsumerStreamResultError<TConfig>\n | ConsumerStreamResultConnecting<TConfig>\n | ConsumerStreamResultTimeout<TConfig>\n | ConsumerStreamResultPing<TConfig>\n | ConsumerStreamResultConnected<TConfig>;\n\nexport interface SSEStreamConsumerOptions<TConfig extends ConsumerConfig> {\n url: () => MaybePromise<string>;\n init: () =>\n | MaybePromise<EventSourceLike.InitDictOf<TConfig['EventSource']>>\n | undefined;\n signal: AbortSignal;\n deserialize?: Deserialize;\n EventSource: TConfig['EventSource'];\n}\n\ninterface ConsumerConfig {\n data: unknown;\n error: unknown;\n EventSource: EventSourceLike.AnyConstructor;\n}\n\nasync function withTimeout<T>(opts: {\n promise: Promise<T>;\n timeoutMs: number;\n onTimeout: () => Promise<NoInfer<T>>;\n}): Promise<T> {\n using timeoutPromise = timerResource(opts.timeoutMs);\n const res = await Unpromise.race([opts.promise, timeoutPromise.start()]);\n\n if (res === disposablePromiseTimerResult) {\n return await opts.onTimeout();\n }\n return res;\n}\n\n/**\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html\n */\nexport function sseStreamConsumer<TConfig extends ConsumerConfig>(\n opts: SSEStreamConsumerOptions<TConfig>,\n): AsyncIterable<ConsumerStreamResult<TConfig>> {\n const { deserialize = (v) => v } = opts;\n\n let clientOptions: SSEClientOptions = emptyObject();\n\n const signal = opts.signal;\n\n let _es: InstanceType<TConfig['EventSource']> | null = null;\n\n const createStream = () =>\n new ReadableStream<ConsumerStreamResult<TConfig>>({\n async start(controller) {\n const [url, init] = await Promise.all([opts.url(), opts.init()]);\n const eventSource = (_es = new opts.EventSource(\n url,\n init,\n ) as InstanceType<TConfig['EventSource']>);\n\n controller.enqueue({\n type: 'connecting',\n eventSource: _es,\n event: null,\n });\n\n eventSource.addEventListener(CONNECTED_EVENT, (_msg) => {\n const msg = _msg as EventSourceLike.MessageEvent;\n\n const options: SSEClientOptions = JSON.parse(msg.data);\n\n clientOptions = options;\n controller.enqueue({\n type: 'connected',\n options,\n eventSource,\n });\n });\n\n eventSource.addEventListener(SERIALIZED_ERROR_EVENT, (_msg) => {\n const msg = _msg as EventSourceLike.MessageEvent;\n\n controller.enqueue({\n type: 'serialized-error',\n error: deserialize(JSON.parse(msg.data)),\n eventSource,\n });\n });\n eventSource.addEventListener(PING_EVENT, () => {\n controller.enqueue({\n type: 'ping',\n eventSource,\n });\n });\n eventSource.addEventListener(RETURN_EVENT, () => {\n eventSource.close();\n controller.close();\n _es = null;\n });\n eventSource.addEventListener('error', (event) => {\n if (eventSource.readyState === eventSource.CLOSED) {\n controller.error(event);\n } else {\n controller.enqueue({\n type: 'connecting',\n eventSource,\n event,\n });\n }\n });\n eventSource.addEventListener('message', (_msg) => {\n const msg = _msg as EventSourceLike.MessageEvent;\n\n const chunk = deserialize(JSON.parse(msg.data));\n\n const def: SSEvent = {\n data: chunk,\n };\n if (msg.lastEventId) {\n def.id = msg.lastEventId;\n }\n controller.enqueue({\n type: 'data',\n data: def as inferTrackedOutput<TConfig['data']>,\n eventSource,\n });\n });\n\n const onAbort = () => {\n try {\n eventSource.close();\n controller.close();\n } catch {\n // ignore errors in case the controller is already closed\n }\n };\n if (signal.aborted) {\n onAbort();\n } else {\n signal.addEventListener('abort', onAbort);\n }\n },\n cancel() {\n _es?.close();\n },\n });\n\n const getStreamResource = () => {\n let stream = createStream();\n let reader = stream.getReader();\n\n async function dispose() {\n await reader.cancel();\n _es = null;\n }\n\n return makeAsyncResource(\n {\n read() {\n return reader.read();\n },\n async recreate() {\n await dispose();\n\n stream = createStream();\n reader = stream.getReader();\n },\n },\n dispose,\n );\n };\n\n return run(async function* () {\n await using stream = getStreamResource();\n\n while (true) {\n let promise = stream.read();\n\n const timeoutMs = clientOptions.reconnectAfterInactivityMs;\n if (timeoutMs) {\n promise = withTimeout({\n promise,\n timeoutMs,\n onTimeout: async () => {\n const res: Awaited<typeof promise> = {\n value: {\n type: 'timeout',\n ms: timeoutMs,\n eventSource: _es,\n },\n done: false,\n };\n // Close and release old reader\n await stream.recreate();\n\n return res;\n },\n });\n }\n\n const result = await promise;\n\n if (result.done) {\n return result.value;\n }\n yield result.value;\n }\n });\n}\n\nexport const sseHeaders = {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache, no-transform',\n 'X-Accel-Buffering': 'no',\n Connection: 'keep-alive',\n} as const;\n","/* eslint-disable @typescript-eslint/no-non-null-assertion */\nimport {\n isObservable,\n observableToAsyncIterable,\n} from '../../observable/observable';\nimport { getErrorShape } from '../error/getErrorShape';\nimport { getTRPCErrorFromUnknown, TRPCError } from '../error/TRPCError';\nimport type { ProcedureType } from '../procedure';\nimport {\n type AnyRouter,\n type inferRouterContext,\n type inferRouterError,\n} from '../router';\nimport type { TRPCResponse } from '../rpc';\nimport { isPromise, jsonlStreamProducer } from '../stream/jsonl';\nimport { sseHeaders, sseStreamProducer } from '../stream/sse';\nimport { transformTRPCResponse } from '../transformer';\nimport {\n abortSignalsAnyPonyfill,\n isAsyncIterable,\n isObject,\n run,\n} from '../utils';\nimport { getAcceptHeader, getRequestInfo } from './contentType';\nimport { getHTTPStatusCode } from './getHTTPStatusCode';\nimport type {\n HTTPBaseHandlerOptions,\n ResolveHTTPRequestOptionsContextFn,\n TRPCRequestInfo,\n} from './types';\n\nfunction errorToAsyncIterable(err: TRPCError): AsyncIterable<never> {\n return run(async function* () {\n throw err;\n });\n}\ntype HTTPMethods =\n 'GET' | 'POST' | 'HEAD' | 'OPTIONS' | 'PUT' | 'DELETE' | 'PATCH';\n\nfunction combinedAbortController(signal: AbortSignal) {\n const controller = new AbortController();\n const combinedSignal = abortSignalsAnyPonyfill([signal, controller.signal]);\n return {\n signal: combinedSignal,\n controller,\n };\n}\n\nconst TYPE_ACCEPTED_METHOD_MAP: Record<ProcedureType, HTTPMethods[]> = {\n mutation: ['POST'],\n query: ['GET'],\n subscription: ['GET'],\n};\nconst TYPE_ACCEPTED_METHOD_MAP_WITH_METHOD_OVERRIDE: Record<\n ProcedureType,\n HTTPMethods[]\n> = {\n // never allow GET to do a mutation\n mutation: ['POST'],\n query: ['GET', 'POST'],\n subscription: ['GET', 'POST'],\n};\n\ninterface ResolveHTTPRequestOptions<\n TRouter extends AnyRouter,\n> extends HTTPBaseHandlerOptions<TRouter, Request> {\n createContext: ResolveHTTPRequestOptionsContextFn<TRouter>;\n req: Request;\n path: string;\n /**\n * If the request had an issue before reaching the handler\n */\n error: TRPCError | null;\n}\n\nfunction initResponse<TRouter extends AnyRouter, TRequest>(initOpts: {\n ctx: inferRouterContext<TRouter> | undefined;\n info: TRPCRequestInfo | undefined;\n responseMeta?: HTTPBaseHandlerOptions<TRouter, TRequest>['responseMeta'];\n untransformedJSON:\n | TRPCResponse<unknown, inferRouterError<TRouter>>\n | TRPCResponse<unknown, inferRouterError<TRouter>>[]\n | null;\n errors: TRPCError[];\n headers: Headers;\n}) {\n const {\n ctx,\n info,\n responseMeta,\n untransformedJSON,\n errors = [],\n headers,\n } = initOpts;\n\n let status = untransformedJSON ? getHTTPStatusCode(untransformedJSON) : 200;\n\n const eagerGeneration = !untransformedJSON;\n const data = eagerGeneration\n ? []\n : Array.isArray(untransformedJSON)\n ? untransformedJSON\n : [untransformedJSON];\n\n const meta =\n responseMeta?.({\n ctx,\n info,\n paths: info?.calls.map((call) => call.path),\n data,\n errors,\n eagerGeneration,\n type:\n info?.calls.find((call) => call.procedure?._def.type)?.procedure?._def\n .type ?? 'unknown',\n }) ?? {};\n\n if (meta.headers) {\n if (meta.headers instanceof Headers) {\n for (const [key, value] of meta.headers.entries()) {\n headers.append(key, value);\n }\n } else {\n /**\n * @deprecated, delete in v12\n */\n for (const [key, value] of Object.entries(meta.headers)) {\n if (Array.isArray(value)) {\n for (const v of value) {\n headers.append(key, v);\n }\n } else if (typeof value === 'string') {\n headers.set(key, value);\n }\n }\n }\n }\n if (meta.status) {\n status = meta.status;\n }\n\n return {\n status,\n };\n}\n\nfunction caughtErrorToData<TRouter extends AnyRouter>(\n cause: unknown,\n errorOpts: {\n opts: Pick<\n ResolveHTTPRequestOptions<TRouter>,\n 'onError' | 'req' | 'router'\n >;\n ctx: inferRouterContext<TRouter> | undefined;\n type: ProcedureType | 'unknown';\n path?: string;\n input?: unknown;\n },\n) {\n const { router, req, onError } = errorOpts.opts;\n const error = getTRPCErrorFromUnknown(cause);\n onError?.({\n error,\n path: errorOpts.path,\n input: errorOpts.input,\n ctx: errorOpts.ctx,\n type: errorOpts.type,\n req,\n });\n const untransformedJSON = {\n error: getErrorShape({\n config: router._def._config,\n error,\n type: errorOpts.type,\n path: errorOpts.path,\n input: errorOpts.input,\n ctx: errorOpts.ctx,\n }),\n };\n const transformedJSON = transformTRPCResponse(\n router._def._config,\n untransformedJSON,\n );\n const body = JSON.stringify(transformedJSON);\n return {\n error,\n untransformedJSON,\n body,\n };\n}\n\n/**\n * Check if a value is a stream-like object\n * - if it's an async iterable\n * - if it's an object with async iterables or promises\n */\nfunction isDataStream(v: unknown) {\n if (!isObject(v)) {\n return false;\n }\n\n if (isAsyncIterable(v)) {\n return true;\n }\n\n return (\n Object.values(v).some(isPromise) || Object.values(v).some(isAsyncIterable)\n );\n}\n\ntype ResultTuple<T> = [undefined, T] | [TRPCError, undefined];\n\nexport async function resolveResponse<TRouter extends AnyRouter>(\n opts: ResolveHTTPRequestOptions<TRouter>,\n): Promise<Response> {\n const { router, req } = opts;\n const headers = new Headers([['vary', 'trpc-accept, accept']]);\n const config = router._def._config;\n\n const url = new URL(req.url);\n\n if (req.method === 'HEAD') {\n // can be used for lambda warmup\n return new Response(null, {\n status: 204,\n });\n }\n\n const allowBatching = opts.allowBatching ?? opts.batching?.enabled ?? true;\n const allowMethodOverride =\n (opts.allowMethodOverride ?? false) && req.method === 'POST';\n\n type $Context = inferRouterContext<TRouter>;\n\n const infoTuple: ResultTuple<TRPCRequestInfo> = await run(async () => {\n try {\n return [\n undefined,\n await getRequestInfo({\n req,\n path: decodeURIComponent(opts.path),\n router,\n searchParams: url.searchParams,\n headers: opts.req.headers,\n url,\n maxBatchSize: opts.maxBatchSize,\n }),\n ];\n } catch (cause) {\n return [getTRPCErrorFromUnknown(cause), undefined];\n }\n });\n\n interface ContextManager {\n valueOrUndefined: () => $Context | undefined;\n value: () => $Context;\n create: (info: TRPCRequestInfo) => Promise<void>;\n }\n const ctxManager: ContextManager = run(() => {\n let result: ResultTuple<$Context> | undefined = undefined;\n return {\n valueOrUndefined: () => {\n if (!result) {\n return undefined;\n }\n return result[1];\n },\n value: () => {\n const [err, ctx] = result!;\n if (err) {\n throw err;\n }\n return ctx;\n },\n create: async (info) => {\n if (result) {\n throw new Error(\n 'This should only be called once - report a bug in tRPC',\n );\n }\n try {\n const ctx = await opts.createContext({\n info,\n });\n result = [undefined, ctx];\n } catch (cause) {\n result = [getTRPCErrorFromUnknown(cause), undefined];\n }\n },\n };\n });\n\n const methodMapper = allowMethodOverride\n ? TYPE_ACCEPTED_METHOD_MAP_WITH_METHOD_OVERRIDE\n : TYPE_ACCEPTED_METHOD_MAP;\n\n /**\n * @deprecated\n */\n const isStreamCall = getAcceptHeader(req.headers) === 'application/jsonl';\n\n const experimentalSSE = config.sse?.enabled ?? true;\n try {\n const [infoError, info] = infoTuple;\n if (infoError) {\n throw infoError;\n }\n if (info.isBatchCall && !allowBatching) {\n throw new TRPCError({\n code: 'BAD_REQUEST',\n message: `Batching is not enabled on the server`,\n });\n }\n /* istanbul ignore if -- @preserve */\n if (isStreamCall && !info.isBatchCall) {\n throw new TRPCError({\n message: `Streaming requests must be batched (you can do a batch of 1)`,\n code: 'BAD_REQUEST',\n });\n }\n await ctxManager.create(info);\n\n interface RPCResultOk {\n data: unknown;\n signal?: AbortSignal;\n }\n type RPCResult = ResultTuple<RPCResultOk>;\n const rpcCalls = info.calls.map(async (call): Promise<RPCResult> => {\n const proc = call.procedure;\n const combinedAbort = combinedAbortController(opts.req.signal);\n try {\n if (opts.error) {\n throw opts.error;\n }\n\n if (!proc) {\n throw new TRPCError({\n code: 'NOT_FOUND',\n message: `No procedure found on path \"${call.path}\"`,\n });\n }\n\n if (!methodMapper[proc._def.type].includes(req.method as HTTPMethods)) {\n throw new TRPCError({\n code: 'METHOD_NOT_SUPPORTED',\n message: `Unsupported ${req.method}-request to ${proc._def.type} procedure at path \"${call.path}\"`,\n });\n }\n\n if (proc._def.type === 'subscription') {\n /* istanbul ignore if -- @preserve */\n if (info.isBatchCall) {\n throw new TRPCError({\n code: 'BAD_REQUEST',\n message: `Cannot batch subscription calls`,\n });\n }\n\n if (config.sse?.maxDurationMs) {\n function cleanup() {\n clearTimeout(timer);\n combinedAbort.signal.removeEventListener('abort', cleanup);\n\n combinedAbort.controller.abort();\n }\n const timer = setTimeout(cleanup, config.sse.maxDurationMs);\n combinedAbort.signal.addEventListener('abort', cleanup);\n }\n }\n const data: unknown = await proc({\n path: call.path,\n getRawInput: call.getRawInput,\n ctx: ctxManager.value(),\n type: proc._def.type,\n signal: combinedAbort.signal,\n batchIndex: call.batchIndex,\n });\n return [\n undefined,\n {\n data,\n signal:\n proc._def.type === 'subscription'\n ? combinedAbort.signal\n : undefined,\n },\n ];\n } catch (cause) {\n const error = getTRPCErrorFromUnknown(cause);\n const input = call.result();\n\n opts.onError?.({\n error,\n path: call.path,\n input,\n ctx: ctxManager.valueOrUndefined(),\n type: call.procedure?._def.type ?? 'unknown',\n req: opts.req,\n });\n\n return [error, undefined];\n }\n });\n\n // ----------- response handlers -----------\n if (!info.isBatchCall) {\n const [call] = info.calls;\n const [error, result] = await rpcCalls[0]!;\n\n switch (info.type) {\n case 'unknown':\n case 'mutation':\n case 'query': {\n // httpLink\n headers.set('content-type', 'application/json');\n\n if (isDataStream(result?.data)) {\n throw new TRPCError({\n code: 'UNSUPPORTED_MEDIA_TYPE',\n message:\n 'Cannot use stream-like response in non-streaming request - use httpBatchStreamLink',\n });\n }\n const res: TRPCResponse<unknown, inferRouterError<TRouter>> = error\n ? {\n error: getErrorShape({\n config,\n ctx: ctxManager.valueOrUndefined(),\n error,\n input: call!.result(),\n path: call!.path,\n type: info.type,\n }),\n }\n : { result: { data: result.data } };\n\n const headResponse = initResponse({\n ctx: ctxManager.valueOrUndefined(),\n info,\n responseMeta: opts.responseMeta,\n errors: error ? [error] : [],\n headers,\n untransformedJSON: [res],\n });\n return new Response(\n JSON.stringify(transformTRPCResponse(config, res)),\n {\n status: headResponse.status,\n headers,\n },\n );\n }\n case 'subscription': {\n // httpSubscriptionLink\n\n const iterable: AsyncIterable<unknown> = run(() => {\n if (error) {\n return errorToAsyncIterable(error);\n }\n if (!experimentalSSE) {\n return errorToAsyncIterable(\n new TRPCError({\n code: 'METHOD_NOT_SUPPORTED',\n message: 'Missing experimental flag \"sseSubscriptions\"',\n }),\n );\n }\n\n if (!isObservable(result.data) && !isAsyncIterable(result.data)) {\n return errorToAsyncIterable(\n new TRPCError({\n message: `Subscription ${\n call!.path\n } did not return an observable or a AsyncGenerator`,\n code: 'INTERNAL_SERVER_ERROR',\n }),\n );\n }\n const dataAsIterable = isObservable(result.data)\n ? observableToAsyncIterable(result.data, opts.req.signal)\n : result.data;\n return dataAsIterable;\n });\n\n const stream = sseStreamProducer({\n ...config.sse,\n data: iterable,\n serialize: (v) => config.transformer.output.serialize(v),\n formatError(errorOpts) {\n const error = getTRPCErrorFromUnknown(errorOpts.error);\n const input = call?.result();\n const path = call?.path;\n const type = call?.procedure?._def.type ?? 'unknown';\n\n opts.onError?.({\n error,\n path,\n input,\n ctx: ctxManager.valueOrUndefined(),\n req: opts.req,\n type,\n });\n\n const shape = getErrorShape({\n config,\n ctx: ctxManager.valueOrUndefined(),\n error,\n input,\n path,\n type,\n });\n\n return shape;\n },\n });\n for (const [key, value] of Object.entries(sseHeaders)) {\n headers.set(key, value);\n }\n\n const headResponse = initResponse({\n ctx: ctxManager.valueOrUndefined(),\n info,\n responseMeta: opts.responseMeta,\n errors: [],\n headers,\n untransformedJSON: null,\n });\n\n const abortSignal = result?.signal;\n let responseBody: ReadableStream<Uint8Array> = stream;\n\n // Fixes: https://github.com/trpc/trpc/issues/7094\n if (abortSignal) {\n const reader = stream.getReader();\n const onAbort = () => void reader.cancel();\n if (abortSignal.aborted) {\n onAbort();\n } else {\n abortSignal.addEventListener('abort', onAbort, { once: true });\n }\n\n responseBody = new ReadableStream({\n async pull(controller) {\n const chunk = await reader.read();\n if (chunk.done) {\n abortSignal.removeEventListener('abort', onAbort);\n controller.close();\n } else {\n controller.enqueue(chunk.value);\n }\n },\n cancel() {\n abortSignal.removeEventListener('abort', onAbort);\n return reader.cancel();\n },\n });\n }\n\n return new Response(responseBody, {\n headers,\n status: headResponse.status,\n });\n }\n }\n }\n\n // batch response handlers\n if (info.accept === 'application/jsonl') {\n // httpBatchStreamLink\n headers.set('content-type', 'application/json');\n headers.set('transfer-encoding', 'chunked');\n const headResponse = initResponse({\n ctx: ctxManager.valueOrUndefined(),\n info,\n responseMeta: opts.responseMeta,\n errors: [],\n headers,\n untransformedJSON: null,\n });\n const stream = jsonlStreamProducer({\n ...config.jsonl,\n /**\n * Example structure for `maxDepth: 4`:\n * {\n * // 1\n * 0: {\n * // 2\n * result: {\n * // 3\n * data: // 4\n * }\n * }\n * }\n */\n maxDepth: Infinity,\n data: rpcCalls.map(async (res, index) => {\n const [error, result] = await res;\n\n const call = info.calls[index];\n\n if (error) {\n return {\n error: getErrorShape({\n config,\n ctx: ctxManager.valueOrUndefined(),\n error,\n input: call!.result(),\n path: call!.path,\n type: call!.procedure?._def.type ?? 'unknown',\n }),\n };\n }\n\n /**\n * Not very pretty, but we need to wrap nested data in promises\n * Our stream producer will only resolve top-level async values or async values that are directly nested in another async value\n */\n const iterable = isObservable(result.data)\n ? observableToAsyncIterable(result.data, opts.req.signal)\n : Promise.resolve(result.data);\n return {\n result: Promise.resolve({\n data: iterable,\n }),\n };\n }),\n serialize: (data) => config.transformer.output.serialize(data),\n onError: (cause) => {\n opts.onError?.({\n error: getTRPCErrorFromUnknown(cause.error),\n path: undefined,\n input: undefined,\n ctx: ctxManager.valueOrUndefined(),\n req: opts.req,\n type: info?.type ?? 'unknown',\n });\n },\n\n formatError(errorOpts) {\n const call = info?.calls[errorOpts.path[0] as any];\n\n const error = getTRPCErrorFromUnknown(errorOpts.error);\n const input = call?.result();\n const path = call?.path;\n const type = call?.procedure?._def.type ?? 'unknown';\n\n // no need to call `onError` here as it will be propagated through the stream itself\n\n const shape = getErrorShape({\n config,\n ctx: ctxManager.valueOrUndefined(),\n error,\n input,\n path,\n type,\n });\n\n return shape;\n },\n });\n\n return new Response(stream, {\n headers,\n status: headResponse.status,\n });\n }\n\n // httpBatchLink\n /**\n * Non-streaming response:\n * - await all responses in parallel, blocking on the slowest one\n * - create headers with known response body\n * - return a complete HTTPResponse\n */\n headers.set('content-type', 'application/json');\n const results: RPCResult[] = (await Promise.all(rpcCalls)).map(\n (res): RPCResult => {\n const [error, result] = res;\n if (error) {\n return res;\n }\n\n if (isDataStream(result.data)) {\n return [\n new TRPCError({\n code: 'UNSUPPORTED_MEDIA_TYPE',\n message:\n 'Cannot use stream-like response in non-streaming request - use httpBatchStreamLink',\n }),\n undefined,\n ];\n }\n return res;\n },\n );\n const resultAsRPCResponse = results.map(\n (\n [error, result],\n index,\n ): TRPCResponse<unknown, inferRouterError<TRouter>> => {\n const call = info.calls[index]!;\n if (error) {\n return {\n error: getErrorShape({\n config,\n ctx: ctxManager.valueOrUndefined(),\n error,\n input: call.result(),\n path: call.path,\n type: call.procedure?._def.type ?? 'unknown',\n }),\n };\n }\n return {\n result: { data: result.data },\n };\n },\n );\n\n const errors = results\n .map(([error]) => error)\n .filter(Boolean) as TRPCError[];\n\n const headResponse = initResponse({\n ctx: ctxManager.valueOrUndefined(),\n info,\n responseMeta: opts.responseMeta,\n untransformedJSON: resultAsRPCResponse,\n errors,\n headers,\n });\n\n return new Response(\n JSON.stringify(transformTRPCResponse(config, resultAsRPCResponse)),\n {\n status: headResponse.status,\n headers,\n },\n );\n } catch (cause) {\n const [_infoError, info] = infoTuple;\n const ctx = ctxManager.valueOrUndefined();\n // we get here if\n // - batching is called when it's not enabled\n // - `createContext()` throws\n // - `router._def._config.transformer.output.serialize()` throws\n // - post body is too large\n // - input deserialization fails\n // - `errorFormatter` return value is malformed\n const { error, untransformedJSON, body } = caughtErrorToData(cause, {\n opts,\n ctx: ctxManager.valueOrUndefined(),\n type: info?.type ?? 'unknown',\n });\n\n const headResponse = initResponse({\n ctx,\n info,\n responseMeta: opts.responseMeta,\n untransformedJSON,\n errors: [error],\n headers,\n });\n\n return new Response(body, {\n status: headResponse.status,\n headers,\n });\n }\n}\n","export * from '../client/components/navigation.react-server'\n","import {\n HTTP_ERROR_FALLBACK_ERROR_CODE,\n type HTTPAccessFallbackError,\n} from './http-access-fallback/http-access-fallback'\n\n// TODO: Add `forbidden` docs\n/**\n * @experimental\n * This function allows you to render the [forbidden.js file](https://nextjs.org/docs/app/api-reference/file-conventions/forbidden)\n * within a route segment as well as inject a tag.\n *\n * `forbidden()` can be used in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).\n *\n * Read more: [Next.js Docs: `forbidden`](https://nextjs.org/docs/app/api-reference/functions/forbidden)\n */\n\nconst DIGEST = `${HTTP_ERROR_FALLBACK_ERROR_CODE};403`\n\nexport function forbidden(): never {\n if (!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS) {\n throw new Error(\n `\\`forbidden()\\` is experimental and only allowed to be enabled when \\`experimental.authInterrupts\\` is enabled.`\n )\n }\n\n const error = new Error(DIGEST) as HTTPAccessFallbackError\n ;(error as HTTPAccessFallbackError).digest = DIGEST\n throw error\n}\n","export const HTTPAccessErrorStatus = {\n NOT_FOUND: 404,\n FORBIDDEN: 403,\n UNAUTHORIZED: 401,\n}\n\nconst ALLOWED_CODES = new Set(Object.values(HTTPAccessErrorStatus))\n\nexport const HTTP_ERROR_FALLBACK_ERROR_CODE = 'NEXT_HTTP_ERROR_FALLBACK'\n\nexport type HTTPAccessFallbackError = Error & {\n digest: `${typeof HTTP_ERROR_FALLBACK_ERROR_CODE};${string}`\n}\n\n/**\n * Checks an error to determine if it's an error generated by\n * the HTTP navigation APIs `notFound()`, `forbidden()` or `unauthorized()`.\n *\n * @param error the error that may reference a HTTP access error\n * @returns true if the error is a HTTP access error\n */\nexport function isHTTPAccessFallbackError(\n error: unknown\n): error is HTTPAccessFallbackError {\n if (\n typeof error !== 'object' ||\n error === null ||\n !('digest' in error) ||\n typeof error.digest !== 'string'\n ) {\n return false\n }\n const [prefix, httpStatus] = error.digest.split(';')\n\n return (\n prefix === HTTP_ERROR_FALLBACK_ERROR_CODE &&\n ALLOWED_CODES.has(Number(httpStatus))\n )\n}\n\nexport function getAccessFallbackHTTPStatus(\n error: HTTPAccessFallbackError\n): number {\n const httpStatus = error.digest.split(';')[1]\n return Number(httpStatus)\n}\n\nexport function getAccessFallbackErrorTypeByStatus(\n status: number\n): 'not-found' | 'forbidden' | 'unauthorized' | undefined {\n switch (status) {\n case 401:\n return 'unauthorized'\n case 403:\n return 'forbidden'\n case 404:\n return 'not-found'\n default:\n return\n }\n}\n","import {\n isHTTPAccessFallbackError,\n type HTTPAccessFallbackError,\n} from './http-access-fallback/http-access-fallback'\nimport { isRedirectError, type RedirectError } from './redirect-error'\n\n/**\n * Returns true if the error is a navigation signal error. These errors are\n * thrown by user code to perform navigation operations and interrupt the React\n * render.\n */\nexport function isNextRouterError(\n error: unknown\n): error is RedirectError | HTTPAccessFallbackError {\n return isRedirectError(error) || isHTTPAccessFallbackError(error)\n}\n","import { ReadonlyURLSearchParams } from './readonly-url-search-params'\n\nexport function unstable_isUnrecognizedActionError(): boolean {\n throw new Error(\n '`unstable_isUnrecognizedActionError` can only be used on the client.'\n )\n}\n\nexport { redirect, permanentRedirect } from './redirect'\nexport { notFound } from './not-found'\nexport { forbidden } from './forbidden'\nexport { unauthorized } from './unauthorized'\nexport { unstable_rethrow } from './unstable-rethrow'\nexport { ReadonlyURLSearchParams }\n\nexport const RedirectType = {\n push: 'push',\n replace: 'replace',\n} as const\n","import {\n HTTP_ERROR_FALLBACK_ERROR_CODE,\n type HTTPAccessFallbackError,\n} from './http-access-fallback/http-access-fallback'\n\n/**\n * This function allows you to render the [not-found.js file](https://nextjs.org/docs/app/api-reference/file-conventions/not-found)\n * within a route segment as well as inject a tag.\n *\n * `notFound()` can be used in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).\n *\n * - In a Server Component, this will insert a `<meta name=\"robots\" content=\"noindex\" />` meta tag and set the status code to 404.\n * - In a Route Handler or Server Action, it will serve a 404 to the caller.\n *\n * Read more: [Next.js Docs: `notFound`](https://nextjs.org/docs/app/api-reference/functions/not-found)\n */\n\nconst DIGEST = `${HTTP_ERROR_FALLBACK_ERROR_CODE};404`\n\nexport function notFound(): never {\n const error = new Error(DIGEST) as HTTPAccessFallbackError\n ;(error as HTTPAccessFallbackError).digest = DIGEST\n\n throw error\n}\n","/**\n * ReadonlyURLSearchParams implementation shared between client and server.\n * This file is intentionally not marked as 'use client' or 'use server'\n * so it can be imported by both environments.\n */\n\n/** @internal */\nclass ReadonlyURLSearchParamsError extends Error {\n constructor() {\n super(\n 'Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams'\n )\n }\n}\n\n/**\n * A read-only version of URLSearchParams that throws errors when mutation methods are called.\n * This ensures that the URLSearchParams returned by useSearchParams() cannot be mutated.\n */\nexport class ReadonlyURLSearchParams extends URLSearchParams {\n /** @deprecated Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams */\n append() {\n throw new ReadonlyURLSearchParamsError()\n }\n /** @deprecated Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams */\n delete() {\n throw new ReadonlyURLSearchParamsError()\n }\n /** @deprecated Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams */\n set() {\n throw new ReadonlyURLSearchParamsError()\n }\n /** @deprecated Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams */\n sort() {\n throw new ReadonlyURLSearchParamsError()\n }\n}\n","import { RedirectStatusCode } from './redirect-status-code'\n\nexport const REDIRECT_ERROR_CODE = 'NEXT_REDIRECT'\n\nexport type RedirectType = 'push' | 'replace'\n\nexport type RedirectError = Error & {\n digest: `${typeof REDIRECT_ERROR_CODE};${RedirectType};${string};${RedirectStatusCode};`\n}\n\n/**\n * Checks an error to determine if it's an error generated by the\n * `redirect(url)` helper.\n *\n * @param error the error that may reference a redirect error\n * @returns true if the error is a redirect error\n */\nexport function isRedirectError(error: unknown): error is RedirectError {\n if (\n typeof error !== 'object' ||\n error === null ||\n !('digest' in error) ||\n typeof error.digest !== 'string'\n ) {\n return false\n }\n\n const digest = error.digest.split(';')\n const [errorCode, type] = digest\n const destination = digest.slice(2, -2).join(';')\n const status = digest.at(-2)\n\n const statusCode = Number(status)\n\n return (\n errorCode === REDIRECT_ERROR_CODE &&\n (type === 'replace' || type === 'push') &&\n typeof destination === 'string' &&\n !isNaN(statusCode) &&\n statusCode in RedirectStatusCode\n )\n}\n","export enum RedirectStatusCode {\n SeeOther = 303,\n TemporaryRedirect = 307,\n PermanentRedirect = 308,\n}\n","import { RedirectStatusCode } from './redirect-status-code'\nimport {\n type RedirectType,\n type RedirectError,\n isRedirectError,\n REDIRECT_ERROR_CODE,\n} from './redirect-error'\nimport { actionAsyncStorage } from './server-async-storage'\n\nexport function getRedirectError(\n url: string,\n type: RedirectType,\n statusCode: RedirectStatusCode = RedirectStatusCode.TemporaryRedirect\n): RedirectError {\n const error = new Error(REDIRECT_ERROR_CODE) as RedirectError\n error.digest = `${REDIRECT_ERROR_CODE};${type};${url};${statusCode};`\n return error\n}\n\n/**\n * This function allows you to redirect the user to another URL. It can be used in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).\n *\n * - In a Server Component, this will insert a meta tag to redirect the user to the target page.\n * - In a Route Handler, it will serve a 307 to the caller.\n * - In a Server Action, it will perform a client-side navigation when JavaScript is available or serve a 303 for a progressive enhancement form submission.\n * - In a Server Action, type defaults to 'push' and 'replace' elsewhere.\n *\n * Read more: [Next.js Docs: `redirect`](https://nextjs.org/docs/app/api-reference/functions/redirect)\n */\nexport function redirect(\n /** The URL to redirect to */\n url: string,\n type?: RedirectType\n): never {\n type ??= actionAsyncStorage?.getStore()?.isAction ? 'push' : 'replace'\n\n throw getRedirectError(url, type, RedirectStatusCode.TemporaryRedirect)\n}\n\n/**\n * This function allows you to redirect the user to another URL. It can be used in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).\n *\n * - In a Server Component, this will insert a meta tag to redirect the user to the target page.\n * - In a Route Handler, it will serve a 308 to the caller.\n * - In a Server Action, it will perform a client-side navigation when JavaScript is available or serve a 303 for a progressive enhancement form submission.\n *\n * Read more: [Next.js Docs: `redirect`](https://nextjs.org/docs/app/api-reference/functions/redirect)\n */\nexport function permanentRedirect(\n /** The URL to redirect to */\n url: string,\n type: RedirectType = 'replace'\n): never {\n throw getRedirectError(url, type, RedirectStatusCode.PermanentRedirect)\n}\n\n/**\n * Returns the encoded URL from the error if it's a RedirectError, null\n * otherwise. Note that this does not validate the URL returned.\n *\n * @param error the error that may be a redirect error\n * @return the url if the error was a redirect error\n */\nexport function getURLFromRedirectError(error: RedirectError): string\nexport function getURLFromRedirectError(error: unknown): string | null {\n if (!isRedirectError(error)) return null\n\n // Slices off the beginning of the digest that contains the code and the\n // separating ';'.\n return error.digest.split(';').slice(2, -2).join(';')\n}\n\nexport function getRedirectTypeFromError(error: RedirectError): RedirectType {\n if (!isRedirectError(error)) {\n throw new Error('Not a redirect error')\n }\n\n return error.digest.split(';', 2)[1] as RedirectType\n}\n\nexport function getRedirectStatusCodeFromError(error: RedirectError): number {\n if (!isRedirectError(error)) {\n throw new Error('Not a redirect error')\n }\n\n return Number(error.digest.split(';').at(-2))\n}\n","// Client-safe access to the server-only async-storage singletons. On the\n// server these re-export the real storages; in the browser bundle this module\n// is aliased to `./server-async-storage.browser` (see\n// scripts/generate-browser-variant-aliases.mjs), which exports `undefined`\n// stubs so the AsyncLocalStorage modules are never bundled into the client.\n// Consumers must guard usage so the stubs are not dereferenced in the browser.\nexport { actionAsyncStorage } from '../../server/app-render/action-async-storage.external'\nexport { workAsyncStorage } from '../../server/app-render/work-async-storage.external'\nexport { workUnitAsyncStorage } from '../../server/app-render/work-unit-async-storage.external'\n","import {\n HTTP_ERROR_FALLBACK_ERROR_CODE,\n type HTTPAccessFallbackError,\n} from './http-access-fallback/http-access-fallback'\n\n// TODO: Add `unauthorized` docs\n/**\n * @experimental\n * This function allows you to render the [unauthorized.js file](https://nextjs.org/docs/app/api-reference/file-conventions/unauthorized)\n * within a route segment as well as inject a tag.\n *\n * `unauthorized()` can be used in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).\n *\n *\n * Read more: [Next.js Docs: `unauthorized`](https://nextjs.org/docs/app/api-reference/functions/unauthorized)\n */\n\nconst DIGEST = `${HTTP_ERROR_FALLBACK_ERROR_CODE};401`\n\nexport function unauthorized(): never {\n if (!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS) {\n throw new Error(\n `\\`unauthorized()\\` is experimental and only allowed to be used when \\`experimental.authInterrupts\\` is enabled.`\n )\n }\n\n const error = new Error(DIGEST) as HTTPAccessFallbackError\n ;(error as HTTPAccessFallbackError).digest = DIGEST\n throw error\n}\n","import { isHangingPromiseRejectionError } from '../../server/dynamic-rendering-utils'\nimport { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'\nimport { isNextRouterError } from './is-next-router-error'\nimport { isPrerenderInterruptedError } from '../../server/app-render/dynamic-rendering'\nimport { isDynamicServerError } from './hooks-server-context'\n\n/**\n * This function should be used to rethrow internal Next.js errors so that they can be handled by the framework.\n * When wrapping an API that uses errors to interrupt control flow, you should use this function before you do any error handling.\n * This function will rethrow the error if it is a Next.js error so it can be handled, otherwise it will do nothing.\n *\n * In the browser bundle this module is aliased to `./unstable-rethrow.browser`, which performs a\n * subset of these checks (the server-only ones can never occur in the browser). This default\n * module holds the full server logic and is used on every server runtime (Node, edge) and in any\n * context where the alias does not apply.\n *\n * Read more: [Next.js Docs: `unstable_rethrow`](https://nextjs.org/docs/app/api-reference/functions/unstable_rethrow)\n */\nexport function unstable_rethrow(error: unknown): void {\n if (\n isNextRouterError(error) ||\n isBailoutToCSRError(error) ||\n isDynamicServerError(error) ||\n isHangingPromiseRejectionError(error) ||\n isPrerenderInterruptedError(error)\n ) {\n throw error\n }\n\n if (error instanceof Error && 'cause' in error) {\n unstable_rethrow(error.cause)\n }\n}\n","// This has to be a shared module which is shared between client component error boundary and dynamic component\nconst BAILOUT_TO_CSR = 'BAILOUT_TO_CLIENT_SIDE_RENDERING'\n\n/** An error that should be thrown when we want to bail out to client-side rendering. */\nexport class BailoutToCSRError extends Error {\n public readonly digest = BAILOUT_TO_CSR\n\n constructor(public readonly reason: string) {\n super(`Bail out to client-side rendering: ${reason}`)\n }\n}\n\n/** Checks if a passed argument is an error that is thrown if we want to bail out to client-side rendering. */\nexport function isBailoutToCSRError(err: unknown): err is BailoutToCSRError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === BAILOUT_TO_CSR\n}\n","import { globalConfig } from \"./core.js\";\n// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function toZod() {\n return (schema) => schema;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\n// the accessor lives on a shared prototype: an own accessor makes every box a dictionary-mode object (~360 B and a slow load per read against ~100 B and an inlined getter here)\nclass Cached {\n constructor(getter) {\n this._getter = getter;\n this._value = undefined;\n }\n get value() {\n const getter = this._getter;\n if (getter !== undefined) {\n this._value = getter();\n this._getter = undefined;\n }\n return this._value;\n }\n}\nexport function cached(getter) {\n return new Cached(getter);\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const ratio = val / step;\n const roundedRatio = Math.round(ratio);\n // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin.\n const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1);\n if (Math.abs(ratio - roundedRatio) < tolerance)\n return 0;\n return ratio - roundedRatio;\n}\nconst EVALUATING = /* @__PURE__*/ Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\n/**\n * Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it.\n *\n * Its keys and descriptors read without invoking anything, which is what lets a discriminated union check its discriminator, and the cycle walk read a shape, without resolving a getter that references the schema being constructed. A def that answers `shape` from an accessor of its own has none.\n */\nexport function rawShape(def) {\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n return desc?.get ? desc.get.raw : desc?.value;\n}\n// where a builder reads its source's keys and descriptors, resolving only a shape a def answers for itself. A shape resolves by object spread, so only its enumerable keys are ever part of it.\nfunction sourceShape(schema) {\n return rawShape(schema._zod.def) ?? schema._zod.def.shape;\n}\n// a key whose value is not settled yet, self-caching so every read after the first gets the same one\nfunction deferProp(target, key, getter) {\n Object.defineProperty(target, key, {\n get() {\n const value = getter();\n assignProp(this, key, value);\n return value;\n },\n enumerable: true,\n configurable: true,\n });\n}\n// Writes a settled key. A plain assignment is much cheaper than `defineProperty` and produces the same descriptor, but it runs whatever setter already answers to the key — an accessor this shape deferred, or an inherited one, which `__proto__` has on every object and prototype pollution can add for any name.\nfunction putProp(target, key, value) {\n if (key in target)\n assignProp(target, key, value);\n else\n target[key] = value;\n}\n/**\n * Copies `keys` of `source`'s shape onto `target`, each value passed through `wrap`.\n *\n * A key the source has resolved is copied through now, so the derived shape states it outright and nothing has to resolve it to learn what it holds. A key the source still defers stays deferred, and reads back through the source's own `shape`, so it resolves once and both shapes get that one schema.\n */\nfunction mirrorShape(target, source, keys, wrap) {\n const raw = sourceShape(source);\n for (const key of keys) {\n const desc = Object.getOwnPropertyDescriptor(raw, key);\n if (!desc.enumerable)\n continue;\n if (desc.get) {\n deferProp(target, key, () => {\n const value = source._zod.def.shape[key];\n return wrap ? wrap(value, key) : value;\n });\n }\n else\n putProp(target, key, wrap ? wrap(desc.value, key) : desc.value);\n }\n}\n// same, for a plain shape a caller passed rather than a schema's\nfunction mirrorProps(target, source) {\n for (const key of Reflect.ownKeys(source)) {\n const desc = Object.getOwnPropertyDescriptor(source, key);\n if (!desc.enumerable)\n continue;\n if (desc.get)\n deferProp(target, key, () => source[key]);\n else\n putProp(target, key, desc.value);\n }\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = /* @__PURE__*/ cached(() => {\n // Skip the probe under `jitless`: strict CSPs report the caught `new Function` as a `securitypolicyviolation` even though the throw is swallowed.\n if (globalConfig.jitless) {\n return false;\n }\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n if (o instanceof Map)\n return new Map(o);\n if (o instanceof Set)\n return new Set(o);\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = /* @__PURE__*/ new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = /* @__PURE__*/ new Set([\n \"string\",\n \"number\",\n \"bigint\",\n \"boolean\",\n \"symbol\",\n \"undefined\",\n]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === \"optional\";\n });\n}\n// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle.\nexport const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n}))();\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const newShape = {};\n mirrorShape(newShape, schema, maskedKeys(schema, mask));\n return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));\n}\n// the mask keys that select something, checked against the source's shape without resolving it\nfunction maskedKeys(schema, mask) {\n const raw = sourceShape(schema);\n const keys = [];\n // `for...in` skips symbols, so a symbol in the mask would select nothing\n for (const key of Reflect.ownKeys(mask)) {\n if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) {\n throw new Error(`Unrecognized key: \"${String(key)}\"`);\n }\n if (mask[key])\n keys.push(key);\n }\n return keys;\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const omitted = new Set(maskedKeys(schema, mask));\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key)));\n return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape. Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = sourceShape(schema);\n for (const key of Reflect.ownKeys(shape)) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));\n}\n// the source's keys, then the caller's overlaid on top\nfunction extended(schema, shape) {\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)));\n mirrorProps(newShape, shape);\n return newShape;\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));\n}\nexport function merge(a, b) {\n if (!b?._zod?.def) {\n throw new Error(\"Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.\");\n }\n if (a._zod.def.checks?.length) {\n throw new Error(\".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.\");\n }\n const newShape = {};\n mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a)));\n mirrorShape(newShape, b, Reflect.ownKeys(sourceShape(b)));\n const def = mergeDefs(a._zod.def, {\n shape: newShape,\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: b._zod.def.checks ?? [],\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask, name = \"partial\") {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(`.${name}() cannot be used on object schemas containing refinements`);\n }\n const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class &&\n ((value, key) => (selected && !selected.has(key) ? value : new Class({ type: \"optional\", innerType: value }))));\n return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] }));\n}\nexport function required(Class, schema, mask) {\n const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => \n // overwrite with non-optional\n selected && !selected.has(key) ? value : new Class({ type: \"nonoptional\", innerType: value }));\n return clone(schema, mergeDefs(schema._zod.def, { shape: newShape }));\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\n// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined). Used to respect `abort: true` in .refine() even for checks that have a `when` function.\nexport function explicitlyAborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue === false) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\n/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */\n/** The leading size checks of `defChecks` that set an upper bound, each paired with it. */\nexport function sizeCaps(defChecks) {\n const caps = [];\n for (const ch of defChecks ?? []) {\n const d = ch._zod.def;\n // a later check may rewrite the value\n if (!/_(length|size)$|_equals$/.test(d.check))\n break;\n const max = d.maximum ?? d.length ?? d.size;\n if (max >= 0)\n caps.push([max, ch]);\n }\n return caps;\n}\nexport function attachSchema(issues, start, inst) {\n var _a;\n for (let i = start; i < issues.length; i++) {\n (_a = issues[i]).schema ?? (_a.schema = inst);\n }\n}\nexport function finalizeIssue(iss, ctx, config) {\n var _a;\n // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead.\n const traits = iss.inst?._zod?.traits;\n if (traits?.has(\"$ZodType\")) {\n if (traits.has(\"$ZodCheck\"))\n (_a = iss).schema ?? (_a.schema = iss.inst);\n else\n iss.schema = iss.inst;\n }\n // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's.\n const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined;\n const message = iss.message\n ? iss.message\n : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(schemaError?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\");\n // an explicit own-key copy beats object rest with excluded keys, which v8 routes through a generic runtime call; Object.keys rather than for-in so an issue pushed with a prototype does not leak inherited keys, and an own __proto__ key is dropped rather than assigned through the setter\n const full = {};\n for (const k of Object.keys(iss)) {\n if (k === \"inst\" || k === \"schema\" || k === \"continue\" || k === \"input\" || k === \"__proto__\")\n continue;\n full[k] = iss[k];\n }\n full.path ?? (full.path = []);\n full.message = message;\n if (ctx?.reportInput) {\n full.input = iss.input;\n }\n return full;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nconst highSurrogate = /[\\uD800-\\uDBFF]/;\n// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters.\nexport function codePointLength(str) {\n const units = str.length;\n if (!highSurrogate.test(str))\n return units;\n let count = units;\n for (let i = 0; i < units - 1; i++) {\n if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n count--;\n i++;\n }\n }\n return count;\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n////////// PROTOTYPE INSTALLERS //////////\n//\n// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see \"The three axes\" in AGENTS.md.\n/**\n * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working.\n *\n * Call this from a `proto` initializer, which runs once per prototype — never per instance.\n */\nexport function members(proto, table) {\n for (const key in table) {\n const desc = Object.getOwnPropertyDescriptor(table, key);\n // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was\n if (desc.get)\n Object.defineProperty(proto, key, { ...desc, enumerable: false });\n // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()`\n else\n defineBound(proto, key, desc.value);\n }\n}\n/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */\nexport function own(inst, key, value, enumerable = true) {\n Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value });\n return value;\n}\n/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */\nexport function hide(inst, key, value) {\n return own(inst, key, value, false);\n}\n/** Adds members a table derives from the instance: each builds on first read and shadows as own data, and assignment shadows the same way, as when these were own properties. */\nexport /*@__NO_SIDE_EFFECTS__*/ function derived(computes, table) {\n for (const key in computes) {\n const compute = computes[key];\n // an object literal's accessor is configurable and enumerable, and `members` copies the descriptor as written\n Object.defineProperty(table, key, {\n configurable: true,\n enumerable: true,\n get() {\n return own(this, key, compute(this));\n },\n set(value) {\n own(this, key, value);\n },\n });\n }\n return table;\n}\nfunction defineBound(proto, key, fn) {\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method\n return this == null ? fn : own(this, key, fn.bind(this));\n },\n set(value) {\n own(this, key, value);\n },\n });\n}\n/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */\nfunction claim(inst, sentinel) {\n const proto = Object.getPrototypeOf(inst);\n // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines.\n return sentinel in proto ? undefined : proto;\n}\n// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped.\nlet installing;\n// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation.\nlet broke = false;\nconst breaker = {\n configurable: true,\n get() {\n broke = true;\n return undefined;\n },\n};\n/**\n * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s\n * constructor, computed from the internals object itself and cached there on\n * first read. One accessor per constructor rather than one per instance.\n */\nexport function defineLazyInternal(inst, key, compute) {\n const proto = Object.getPrototypeOf(inst._zod);\n if (key in proto && installing !== inst._zod) {\n // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type.\n installing = undefined;\n return;\n }\n installing = inst._zod;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again.\n Object.defineProperty(this, key, breaker);\n const outer = broke;\n broke = false;\n try {\n const value = compute(this);\n // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included.\n if (broke)\n delete this[key];\n else\n Object.defineProperty(this, key, { configurable: true, writable: true, value });\n broke = broke || outer;\n return value;\n }\n catch (err) {\n // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read.\n delete this[key];\n broke = broke || outer;\n throw err;\n }\n },\n set(value) {\n Object.defineProperty(this, key, { configurable: true, writable: true, value });\n },\n });\n}\n/**\n * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own\n * data property. One accessor per constructor rather than one per instance, because an own accessor\n * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel.\n */\nexport function installLazyProp(inst, key, make, enumerable) {\n const proto = claim(inst, key);\n if (!proto)\n return;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid.\n const desc = { configurable: true, writable: true, enumerable, value: undefined };\n Object.defineProperty(this, key, desc);\n // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches\n desc.value = make(this);\n Object.defineProperty(this, key, desc);\n return desc.value;\n },\n set(value) {\n Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value });\n },\n });\n}\n/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */\nexport const CONSTANT_CATCH = \"~constantCatch\";\n/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */\nexport function constantCatch(value) {\n const fn = () => value;\n fn[CONSTANT_CATCH] = true;\n return fn;\n}\n","var _a;\nimport { members as installMembers } from \"./util.js\";\n/** A special constant with type `never` */\nexport const NEVER = /*@__PURE__*/ Object.freeze({\n status: \"aborted\",\n});\n/* Shared descriptor for installing `_zod`; defineProperty reads it\n * synchronously, so reusing one object avoids a per-instance allocation. */\nconst _zodDesc = { value: undefined, enumerable: false };\n// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error\nlet _E = \"captureStackTrace\" in Error ? Error : null;\n// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot\nfunction newError(Definition) {\n const E = _E;\n if (E) {\n const saved = E.stackTraceLimit;\n if (typeof saved === \"number\") {\n try {\n E.stackTraceLimit = 0;\n }\n catch {\n _E = null;\n return new Definition();\n }\n try {\n return new Definition();\n }\n finally {\n E.stackTraceLimit = saved;\n }\n }\n }\n return new Definition();\n}\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, \n/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */\nproto, params) {\n // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance.\n const zodProto = {};\n // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy.\n function Internals(def) {\n this.def = def;\n this.constr = _;\n this.traits = new Set();\n }\n Internals.prototype = zodProto;\n const protoMembers = proto;\n // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait.\n const initialized = protoMembers && new WeakSet();\n function init(inst, def) {\n if (!inst._zod) {\n _zodDesc.value = new Internals(def);\n try {\n Object.defineProperty(inst, \"_zod\", _zodDesc);\n }\n finally {\n // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next.\n _zodDesc.value = undefined;\n }\n }\n else if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n if (initialized) {\n // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before.\n const own = Object.getPrototypeOf(inst);\n const ctorProto = inst._zod.constr.prototype;\n let up = own;\n while (up && up !== ctorProto)\n up = Object.getPrototypeOf(up);\n const target = up ?? own;\n if (!initialized.has(target)) {\n initialized.add(target);\n installMembers(target, protoMembers);\n }\n }\n // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype\n const proto = _.prototype;\n for (const k in proto) {\n if (!Object.prototype.hasOwnProperty.call(proto, k))\n continue;\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n const inst = params?.Parent ? newError(Definition) : this;\n init(inst, def);\n const deferred = inst._zod.deferred;\n if (deferred) {\n for (const fn of deferred) {\n fn();\n }\n // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime.\n inst._zod.deferred = undefined;\n }\n // Global post-processor hook. Internal: installed by `import \"zod/compile\"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation.\n const pp = globalThis.__zod_globalConfig?.postProcessor;\n if (pp)\n pp(inst);\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = /*@__PURE__*/ Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\n(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});\nexport const globalConfig = globalThis.__zod_globalConfig;\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","import * as util from \"./util.js\";\nexport class $ZodCyclicError extends Error {\n constructor() {\n super(`Cannot parse a reference cycle that closes through a transform`);\n this.name = \"ZodCyclicError\";\n }\n}\n/** Keyed off the context object every schema in one parse call already shares. */\nconst STATE = \"~memo\";\nconst NO_ISSUES = [];\n// a value a cycle can close through\nfunction isRef(value) {\n return value !== null && typeof value === \"object\";\n}\n// Receivers prefix paths in place, so the cache and every hand-out need their own copies.\nfunction cloneIssues(issues) {\n return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss }));\n}\nconst recursive = /*@__PURE__*/ new WeakMap();\n/** What the walk established, in order of certainty: ordered so the strongest answer among children wins. */\nconst NONE = 0;\nconst ASSUMED = 1;\nconst PROVEN = 2;\n/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */\nfunction isRecursive(inst, stack, resolve) {\n const cached = recursive.get(inst);\n if (cached !== undefined)\n return cached ? PROVEN : NONE;\n // Relative to the walk in progress, so not cached.\n if (stack.has(inst))\n return PROVEN;\n stack.add(inst);\n let result = NONE;\n const check = (child) => {\n if (result !== PROVEN && child?._zod) {\n const answer = isRecursive(child, stack, resolve);\n if (answer > result)\n result = answer;\n }\n };\n // `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen\n const shape = (sh, spread) => {\n let answer = NONE;\n for (const key of Reflect.ownKeys(sh)) {\n const desc = Object.getOwnPropertyDescriptor(sh, key);\n // an object resolves its shape by spread, so a key it does not enumerate is never parsed; `z.properties` reads every own key and so keeps them all\n if (spread && !desc.enumerable)\n continue;\n // resolving runs user code, and a factory mints a fresh subtree per read, so an edge the walk can't follow counts as a cycle\n const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve) : NONE;\n if (child > answer)\n answer = child;\n }\n return answer;\n };\n const merge = (answer) => {\n if (answer > result)\n result = answer;\n };\n const def = inst._zod.def;\n const kind = def.type;\n switch (kind) {\n case \"object\": {\n const raw = util.rawShape(def);\n // a def with no raw shape answers `shape` from an accessor of its own, and running that can mint a whole fresh subtree\n merge(raw ? shape(raw, true) : ASSUMED);\n check(def.catchall);\n break;\n }\n case \"array\":\n check(def.element);\n break;\n case \"tuple\":\n for (const el of def.items)\n check(el);\n check(def.rest);\n break;\n case \"record\":\n case \"map\":\n check(def.keyType);\n check(def.valueType);\n break;\n case \"set\":\n check(def.valueType);\n break;\n case \"union\":\n for (const el of def.options)\n check(el);\n break;\n case \"intersection\":\n check(def.left);\n check(def.right);\n break;\n case \"optional\":\n case \"nullable\":\n case \"default\":\n case \"prefault\":\n case \"catch\":\n case \"readonly\":\n case \"nonoptional\":\n case \"promise\":\n case \"success\":\n check(def.innerType);\n break;\n case \"pipe\":\n check(def.in);\n check(def.out);\n break;\n case \"function\":\n check(def.input);\n check(def.output);\n break;\n // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly\n case \"lazy\": {\n const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : undefined);\n // walked with resolution off: one hop sees past the deferral, and a lazy that yields only another unresolved lazy is generative, so it stops there\n merge(inner ? isRecursive(inner, stack, false) : ASSUMED);\n break;\n }\n // a leaf by choice: `parts` are regex fragments, not data positions\n case \"template_literal\":\n // leaves\n case \"string\":\n case \"number\":\n case \"int\":\n case \"boolean\":\n case \"bigint\":\n case \"symbol\":\n case \"undefined\":\n case \"null\":\n case \"void\":\n case \"never\":\n case \"any\":\n case \"unknown\":\n case \"date\":\n case \"nan\":\n case \"enum\":\n case \"literal\":\n case \"file\":\n case \"transform\":\n case \"custom\":\n break;\n default: {\n // a new built-in kind becomes a compile error here\n kind;\n // a user-defined kind can still hold children, and only its author knows where, so fall back to scanning the def — skipping accessors, since reading one can run user code\n for (const key in def) {\n const desc = Object.getOwnPropertyDescriptor(def, key);\n if (!desc || desc.get)\n continue;\n const value = desc.value;\n if (!value || typeof value !== \"object\")\n continue;\n if (value._zod)\n check(value);\n else if (Array.isArray(value))\n for (const el of value)\n check(el);\n }\n }\n }\n stack.delete(inst);\n return settle(inst, result);\n}\n/** An assumed answer must not outlive the resolution that settles it, so only a certain one is cached. */\nfunction settle(inst, answer) {\n if (answer !== ASSUMED)\n recursive.set(inst, answer === PROVEN);\n return answer;\n}\n/**\n * Whether one parse can re-enter this schema, i.e. its subtree contains a cycle.\n * Exported for `z.compile`, which refuses to compile such a schema: cycle\n * breaking is driven from here off state keyed on the parse context, and a\n * generated fast path has no context to key on.\n */\nexport function isRecursiveSchema(inst) {\n // z.compile never parses, so nothing would ever resolve a lazy for it; it runs once and already treats a throw here as recursive\n return isRecursive(inst, new Set(), true) !== NONE;\n}\nfunction bucketFor(state, inst) {\n let bucket = state.buckets.get(inst);\n if (!bucket) {\n bucket = new WeakMap();\n state.buckets.set(inst, bucket);\n }\n return bucket;\n}\n// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving.\nlet handoff;\n// Allocated but unfinished entries. `alloc` and the matching pop both happen in the synchronous part of a parse, so they nest even when children are async, and one stack serves every schema.\nconst open = [];\nconst memo = {\n alloc(_inst, payload, empty) {\n const bucket = handoff;\n if (!bucket)\n return empty;\n handoff = undefined;\n const entry = { value: empty, issues: null };\n bucket.set(payload.value, entry);\n open.push(entry);\n return empty;\n },\n guard(inst) {\n var _a;\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred.push(() => {\n const base = inst._zod.parse;\n const wrapped = (payload, ctx) => {\n // The value is a placeholder a back-edge is still waiting on, so the cycle closes through this transform. Its output can't exist in time to bind.\n if (ctx.direction !== \"backward\" && isBackEdge(ctx, payload.value))\n throw new $ZodCyclicError();\n return base(payload, ctx);\n };\n inst._zod.parse = wrapped;\n if (inst._zod.run === base)\n inst._zod.run = wrapped;\n });\n },\n attach(inst) {\n var _a;\n let isRecursiveInst;\n let rechecked = false;\n // a recursive schema is re-entered many times per parse and its bucket never changes\n let lastCtx;\n let lastBucket;\n // Wraps `parse` in a deferred so it sees the container's final parse. Core's own deferred copies `parse` into `run` when there are no checks, and it ran first, so `run` is patched to match; with checks, `run` reads `parse` dynamically.\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred.push(() => {\n const base = inst._zod.parse;\n const wrapped = (payload, ctx) => {\n if (isRecursiveInst === undefined) {\n const walked = isRecursive(inst, new Set(), false);\n if (walked === NONE) {\n // Nothing here can ever fire, so take it back out.\n inst._zod.parse = base;\n if (inst._zod.run === wrapped)\n inst._zod.run = base;\n return base(payload, ctx);\n }\n // this parse resolves the deferred edges on its own path, so ask once more before latching\n if (walked === PROVEN || rechecked)\n isRecursiveInst = true;\n else\n rechecked = true;\n }\n const input = payload.value;\n if (!isRef(input))\n return base(payload, ctx);\n let state = ctx[STATE];\n if (!state) {\n state = { buckets: new WeakMap(), backEdges: undefined };\n ctx[STATE] = state;\n }\n let bucket;\n if (lastCtx === ctx) {\n bucket = lastBucket;\n }\n else {\n bucket = bucketFor(state, inst);\n lastCtx = ctx;\n lastBucket = bucket;\n }\n const hit = bucket.get(input);\n if (hit) {\n payload.value = hit.value;\n if (hit.issues) {\n if (hit.issues.length)\n payload.issues.push(...cloneIssues(hit.issues));\n }\n else {\n // Still being parsed: its own checks cover it, so skip them here.\n payload.memo = true;\n state.backEdges ?? (state.backEdges = new WeakSet());\n state.backEdges.add(hit.value);\n }\n return payload;\n }\n handoff = bucket;\n const depth = open.length;\n const result = base(payload, ctx);\n handoff = undefined;\n // A container that rejected its input outright allocated nothing.\n const entry = open.length > depth ? open.pop() : undefined;\n // Both paths written out so the sync one allocates no closure. It runs once per node, and capturing here cost more than everything else combined.\n if (result instanceof Promise) {\n return result.then((r) => {\n if (entry)\n entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES;\n return r;\n });\n }\n if (entry)\n entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES;\n return result;\n };\n inst._zod.parse = wrapped;\n if (inst._zod.run === base)\n inst._zod.run = wrapped;\n });\n },\n};\n/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */\nexport function memoizer() {\n return memo;\n}\n/** Whether this value is a node a back-edge resolved to before it finished. */\nexport function isBackEdge(ctx, value) {\n const backEdges = ctx[STATE]?.backEdges;\n return backEdges !== undefined && isRef(value) && backEdges.has(value);\n}\n","var _a;\nexport const $output = /*@__PURE__*/ Symbol(\"ZodOutput\");\nexport const $input = /*@__PURE__*/ Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n constructor() {\n this._map = new WeakMap();\n this._idmap = new Map();\n }\n add(schema, ..._meta) {\n const meta = _meta[0];\n this._map.set(schema, meta);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.set(meta.id, schema);\n }\n return this;\n }\n clear() {\n this._map = new WeakMap();\n this._idmap = new Map();\n return this;\n }\n remove(schema) {\n const meta = this._map.get(schema);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.delete(meta.id);\n }\n this._map.delete(schema);\n return this;\n }\n get(schema) {\n // return this._map.get(schema) as any;\n // inherit metadata\n const p = schema._zod.parent;\n if (p) {\n const pm = { ...(this.get(p) ?? {}) };\n delete pm.id; // do not inherit id\n const f = { ...pm, ...this._map.get(schema) };\n return Object.keys(f).length ? f : undefined;\n }\n return this._map.get(schema);\n }\n has(schema) {\n return this._map.has(schema);\n }\n}\n// registries\nexport function registry() {\n return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n","import * as util from \"./util.js\";\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const cuid = /^[cC][0-9a-z]{6,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\nexport function nanoidOfLength(length) {\n return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`);\n}\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n if (!version)\n return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;\n return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport const rfc5322Email = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = unicodeEmail;\nexport const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\n// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match. The leading lookahead then demands one anchor — a pictograph, a regional indicator, or the enclosing keycap — because `\\p{Emoji_Component}` on its own covers ASCII digits, `#`, `*`, ZWJ, variation selectors and skin tone modifiers, none of which is an emoji without a base.\nconst _emoji = `^(?=[\\\\s\\\\S]*[\\\\p{Extended_Pictographic}\\\\p{Regional_Indicator}\\\\u20E3])[\\\\p{Extended_Pictographic}\\\\p{Emoji_Component}]+$`;\nexport function emoji() {\n return new RegExp(_emoji, \"u\");\n}\nexport const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nexport const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;\nexport const mac = (delimiter) => {\n const escapedDelim = util.escapeRegex(delimiter ?? \":\");\n return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);\n};\nexport const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/;\nexport const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const hostname = /^(?=.{1,253}\\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\\.?$/;\nexport const domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,63}$/;\nexport const httpProtocol = /^https?$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro).\nexport const creditCard = /^\\d(?:[ -]?\\d){11,18}$/;\n// ISO 4217 alpha codes from the SIX list, regenerated by scripts/update-iso-4217.ts\nexport const currencyCode = /^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/;\n// iban electronic format: 2-letter country, check digits 02-98 (the only values `98 - remainder` can produce), 11-30 bban characters\nexport const iban = /^[A-Z]{2}(?!00|01|99)\\d{2}[A-Z0-9]{11,30}$/;\nconst dateSource = `(?:(?:\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\\\d|30)|(?:02)-(?:0[1-9]|1\\\\d|2[0-8])))`;\n/** Anchors a pattern source. The interpolation lives here rather than at the call site because\n * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it\n * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */\nfunction anchor(source) {\n return new RegExp(`^${source}$`);\n}\nexport const date = /*@__PURE__*/ anchor(dateSource);\nfunction timeSource(args) {\n const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n const regex = typeof args.precision === \"number\"\n ? args.precision === -1\n ? `${hhmm}`\n : args.precision === 0\n ? `${hhmm}:[0-5]\\\\d`\n : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n : args.seconds\n ? `${hhmm}:[0-5]\\\\d(?:\\\\.\\\\d+)?`\n : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n return regex;\n}\nexport function time(args) {\n return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n const opts = [\"Z\"];\n // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n if (args.offset)\n opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them\n const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join(\"|\")})`;\n const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\n// the unbounded form of `string()` as a literal, so every plain string shares one instance instead of building its own\nexport const anyString = /^[\\s\\S]{0,}$/;\nexport const string = (params) => {\n const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^-?\\d+n?$/;\nexport const integer = /^-?\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?$/;\nexport const boolean = /^(?:true|false)$/i;\nconst _null = /^null$/i;\nexport { _null as null };\nconst _undefined = /^undefined$/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n","// import { $ZodType } from \"./schemas.js\";\nimport * as core from \"./core.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nexport const $ZodCheck = /*@__PURE__*/ core.$constructor(\"$ZodCheck\", (inst, def) => {\n var _a;\n inst._zod ?? (inst._zod = {});\n inst._zod.def = def;\n (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\n/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */\nconst _whenHasSize = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n};\n/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */\nconst _whenHasLength = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n};\nconst numericOriginMap = {\n number: \"number\",\n bigint: \"bigint\",\n object: \"date\",\n};\nexport const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckLessThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n return;\n }\n payload.issues.push({\n origin: numericOriginMap[typeof payload.value] ?? origin,\n code: \"too_big\",\n maximum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckGreaterThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n return;\n }\n payload.issues.push({\n origin: numericOriginMap[typeof payload.value] ?? origin,\n code: \"too_small\",\n minimum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMultipleOf = \n/*@__PURE__*/ core.$constructor(\"$ZodCheckMultipleOf\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n if (typeof payload.value !== typeof def.value)\n throw new Error(\"Cannot mix number and bigint in multiple_of check.\");\n const isMultiple = typeof payload.value === \"bigint\"\n ? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN\n def.value !== BigInt(0) && payload.value % def.value === BigInt(0)\n : util.floatSafeRemainder(payload.value, def.value) === 0;\n if (isMultiple)\n return;\n payload.issues.push({\n origin: typeof payload.value,\n code: \"not_multiple_of\",\n divisor: def.value,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckNumberFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n def.format = def.format || \"float64\";\n const isInt = def.format?.includes(\"int\");\n const origin = isInt ? \"int\" : \"number\";\n const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (isInt) {\n if (!Number.isInteger(input)) {\n // invalid_format issue\n // payload.issues.push({\n // expected: def.format,\n // format: def.format,\n // code: \"invalid_format\",\n // input,\n // inst,\n // });\n // invalid_type issue\n payload.issues.push({\n expected: origin,\n format: def.format,\n code: \"invalid_type\",\n continue: false,\n input,\n inst,\n });\n return;\n // not_multiple_of issue\n // payload.issues.push({\n // code: \"not_multiple_of\",\n // origin: \"number\",\n // input,\n // inst,\n // divisor: 1,\n // });\n }\n if (!Number.isSafeInteger(input)) {\n if (input > 0) {\n // too_big\n payload.issues.push({\n input,\n code: \"too_big\",\n maximum: Number.MAX_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n else {\n // too_small\n payload.issues.push({\n input,\n code: \"too_small\",\n minimum: Number.MIN_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n return;\n }\n }\n if (input < minimum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_small\",\n minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckBigIntFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (input < minimum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_small\",\n minimum: minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size <= def.maximum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size >= def.minimum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckSizeEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size === def.size)\n return;\n const tooBig = size > def.size;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n ...(tooBig ? { code: \"too_big\", maximum: def.size } : { code: \"too_small\", minimum: def.size }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // Strings are measured in Unicode code points, not UTF-16 units. A code point is at most two units, so a string that already fits in units fits in code points; only an overflow has to be counted.\n const length = typeof input === \"string\" && units > def.maximum ? util.codePointLength(input) : units;\n if (length <= def.maximum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // A code point is one or two UTF-16 units, so fewer units than the floor can never reach it and twice the floor always clears it. Only in between is the exact count in doubt.\n const length = typeof input === \"string\" && units >= def.minimum && units < def.minimum * 2\n ? util.codePointLength(input)\n : units;\n if (length >= def.minimum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckLengthEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // A code point is one or two UTF-16 units, so outside `[length, length * 2]` units the target is missed either way — and missed in the same direction in both measures.\n const length = typeof input === \"string\" && units >= def.length && units <= def.length * 2\n ? util.codePointLength(input)\n : units;\n if (length === def.length)\n return;\n const origin = util.getLengthableOrigin(input);\n const tooBig = length > def.length;\n payload.issues.push({\n origin,\n ...(tooBig ? { code: \"too_big\", maximum: def.length } : { code: \"too_small\", minimum: def.length }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckStringFormat\", (inst, def) => {\n var _a, _b;\n $ZodCheck.init(inst, def);\n if (def.pattern)\n (_a = inst._zod).check ?? (_a.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n ...(def.pattern ? { pattern: def.pattern.toString() } : {}),\n inst,\n continue: !def.abort,\n });\n });\n else\n (_b = inst._zod).check ?? (_b.check = () => { });\n});\nexport const $ZodCheckRegex = /*@__PURE__*/ core.$constructor(\"$ZodCheckRegex\", (inst, def) => {\n $ZodCheckStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"regex\",\n input: payload.value,\n pattern: def.pattern.toString(),\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckLowerCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.lowercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckUpperCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.uppercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor(\"$ZodCheckIncludes\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const escapedRegex = util.escapeRegex(def.includes);\n // `String.prototype.includes(sub, position)` matches `sub` at `position`\n // OR LATER, so the pattern must allow at least `position` leading chars\n // (`{N,}`), not exactly `position` chars (`{N}`).\n const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position},}${escapedRegex}` : escapedRegex);\n def.pattern = pattern;\n inst._zod.check = (payload) => {\n if (payload.value.includes(def.includes, def.position))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"includes\",\n includes: def.includes,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckStartsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.check = (payload) => {\n if (payload.value.startsWith(def.prefix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"starts_with\",\n prefix: def.prefix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckEndsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.check = (payload) => {\n if (payload.value.endsWith(def.suffix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"ends_with\",\n suffix: def.suffix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n///////////////////////////////////\n///// $ZodCheckProperty /////\n///////////////////////////////////\nfunction handleCheckPropertyResult(result, payload, property) {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(property, result.issues));\n }\n}\nexport const $ZodCheckProperty = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperty\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n const result = def.schema._zod.run({\n value: payload.value[def.property],\n issues: [],\n }, {});\n if (result instanceof Promise) {\n return result.then((result) => handleCheckPropertyResult(result, payload, def.property));\n }\n handleCheckPropertyResult(result, payload, def.property);\n return;\n };\n});\nexport const $ZodCheckProperties = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperties\", (inst, def) => {\n $ZodCheck.init(inst, def);\n util.hide(inst, Symbol.iterator, function* () {\n yield inst;\n });\n // key and schema snapshotted together: reading one live and the other cached lets a later mutation of the caller's shape object pair a stale key with a missing schema\n let entries;\n inst._zod.check = (payload) => {\n // the base schema already typed the value, so only a nullish one is rejected here: the properties read on a primitive too, matching z.property() on a string's length\n if (payload.value == null) {\n payload.issues.push({ expected: \"object\", code: \"invalid_type\", input: payload.value, inst });\n return undefined;\n }\n entries ?? (entries = Reflect.ownKeys(def.shape).map((key) => [key, def.shape[key]]));\n const input = payload.value;\n let proms;\n for (const [key, schema] of entries) {\n const result = schema._zod.run({ value: input[key], issues: [] }, {});\n if (result instanceof Promise) {\n proms ?? (proms = []);\n proms.push(result.then((result) => handleCheckPropertyResult(result, payload, key)));\n }\n else {\n handleCheckPropertyResult(result, payload, key);\n }\n }\n if (proms)\n return Promise.all(proms).then(() => undefined);\n return undefined;\n };\n});\nexport const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const mimeSet = new Set(def.mime);\n inst._zod.check = (payload) => {\n if (mimeSet.has(payload.value.type))\n return;\n payload.issues.push({\n code: \"invalid_value\",\n values: def.mime,\n input: payload.value.type,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor(\"$ZodCheckOverwrite\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n payload.value = def.tx(payload.value);\n };\n});\n","export class Doc {\n constructor(args = [], closed = {}) {\n this.content = [];\n this.indent = 0;\n this.args = args;\n this.closed = closed;\n }\n // the compiler catches a child's throw and keeps writing into this doc, so the indent has to unwind with it\n indented(fn) {\n this.indent += 1;\n try {\n fn(this);\n }\n finally {\n this.indent -= 1;\n }\n }\n write(arg) {\n if (typeof arg === \"function\") {\n arg(this, { execution: \"sync\" });\n arg(this, { execution: \"async\" });\n return;\n }\n const content = arg;\n const lines = content.split(\"\\n\").filter((x) => x);\n const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));\n const dedented = lines.map((x) => x.slice(minIndent)).map((x) => \" \".repeat(this.indent * 2) + x);\n for (const line of dedented) {\n this.content.push(line);\n }\n }\n compile() {\n const F = Function;\n const content = this?.content ?? [``];\n const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(\", \")}) {\\n${content.join(\"\\n\")}\\n};`);\n return factory(...Object.values(this.closed));\n }\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\n/* Computing the message eagerly is expensive (pretty-printed JSON of all\n * issues), so defer it until first read. The accessor functions and\n * descriptors are shared across instances to keep error construction\n * cheap; the computed message is cached on the internals object. The\n * setter preserves plain assignment semantics for consumers that\n * overwrite `message`. */\nfunction _getMessage() {\n const internals = this._zod;\n internals.message ?? (internals.message = JSON.stringify(internals.def, util.jsonStringifyReplacer, 2));\n return internals.message;\n}\nfunction _setMessage(value) {\n this._zod.message = value;\n}\nconst _messageDesc = {\n get: _getMessage,\n set: _setMessage,\n enumerable: true,\n configurable: true,\n};\nconst _issuesDesc = { value: undefined, enumerable: false };\n/* Prototypes that already carry the lazy `toString`. Seeded with the\n * intrinsics so that `init` on a foreign object — it accepts any object —\n * can never install an accessor onto a prototype we do not own. */\nconst _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n // `_zod` is already non-enumerable: $constructor's init defined it with this same descriptor\n _issuesDesc.value = def;\n Object.defineProperty(inst, \"issues\", _issuesDesc);\n // Clear the shared slot; a retained `value` pins the last error's issues.\n _issuesDesc.value = undefined;\n Object.defineProperty(inst, \"message\", _messageDesc);\n /* `toString` lives as a non-enumerable lazy getter on the shared\n * prototype; on first access it caches a per-instance closure so\n * detached usage still works. */\n const proto = Object.getPrototypeOf(inst);\n if (!_installedToString.has(proto)) {\n _installedToString.add(proto);\n Object.defineProperty(proto, \"toString\", {\n configurable: true,\n enumerable: false,\n get() {\n const value = () => this.message;\n Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n return value;\n },\n set(value) {\n Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n },\n });\n }\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, undefined, {\n Parent: Error,\n});\n/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member\n * (\"toString\", \"constructor\") would otherwise read through to the prototype, and assigning\n * \"__proto__\" would hit the setter instead of creating a key. */\nfunction node(obj, key, make) {\n if (!Object.prototype.hasOwnProperty.call(obj, key)) {\n if (key === \"__proto__\") {\n Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true });\n }\n else {\n obj[key] = make();\n }\n }\n return obj[key];\n}\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n node(fieldErrors, sub.path[0], () => []).push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error, path = []) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n // `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child.\n if (el === \"_errors\") {\n if (terminal)\n curr._errors.push(mapper(issue));\n i++;\n continue;\n }\n // A path element may collide with an inherited property name such as\n // \"__proto__\" or \"constructor\". Truthiness checks read the prototype\n // (so no node is created, then ._errors.push throws), and bracket\n // assignment of \"__proto__\" hits the setter instead of creating an\n // own key. Guard the read with hasOwnProperty and create the node\n // with defineProperty so any path element becomes a real own key.\n if (!Object.prototype.hasOwnProperty.call(curr, el)) {\n Object.defineProperty(curr, el, {\n value: { _errors: [] },\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n const node = curr[el];\n if (terminal) {\n node._errors.push(mapper(issue));\n }\n curr = node;\n i++;\n }\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n // el may collide with an inherited property name (\"__proto__\",\n // \"constructor\", ...); ??= reads the prototype so the node is never\n // created and curr.errors.push throws. Guard with hasOwnProperty and\n // create the node with defineProperty so \"__proto__\" becomes a real\n // own key rather than invoking the prototype setter.\n if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) {\n Object.defineProperty(curr.properties, el, {\n value: { errors: [] },\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_a = curr.items)[el] ?? (_a[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\n// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two.\nfunction finalizeParams(callee, params) {\n return { callee: params?.callee ?? callee, Err: params?.Err };\n}\nexport const _parse = (_Err) => {\n const fn = (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, _params?.callee ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => {\n const fn = async (schema, value, _ctx, params) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, params?.callee ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\n// the error is built on the first read of `error`: finalizing the issues and constructing the instance is most of a failing parse, and a caller that only branches on `success` never pays it. a getter in the literal keeps this small; the alternative, one shared accessor descriptor plus a hidden state slot, reads ~15% faster but costs ~75 B gzipped in every bundle\nfunction failure(Err, issues, ctx) {\n let error;\n return {\n success: false,\n get error() {\n if (!error) {\n error = new Err(issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n // finalizeIssue drops `input`, so the built error holds nothing; keeping the raw issues past this point pins the parsed value for the life of the result\n issues = undefined;\n ctx = undefined;\n }\n return error;\n },\n set error(e) {\n error = e;\n // a replacement makes the getter's branch unreachable, so the captures have to go here too\n issues = undefined;\n ctx = undefined;\n },\n };\n}\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\n// registry mirrors of the compiler's sentinels, so this module never imports the compiler\nconst COMPILE_INVALID = /* @__PURE__ */ Symbol.for(\"zod.compile.invalid\");\nconst COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for(\"zod.compile.fallback\");\n// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema.\nexport const validate = ((schema, value, _ctx) => {\n const validator = schema._zod.bag.validator;\n if (validator !== undefined) {\n if (validator(value) !== COMPILE_INVALID)\n return true;\n // a definite sentinel means the runtime would reject, so skip the re-parse; a ctx can still change the answer\n if (validator.definite === true && _ctx === undefined)\n return false;\n }\n return validateFallback(schema, value, _ctx);\n});\nfunction validateFallback(schema, value, _ctx) {\n const ctx = _ctx\n ? { ..._ctx, async: false, abortEarly: true }\n : { async: false, abortEarly: true };\n const fallbackRun = schema._zod.bag.fallbackRun;\n let result;\n if (fallbackRun) {\n // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound\n ctx[COMPILE_FALLBACK] = true;\n result = fallbackRun({ value, issues: [] }, ctx);\n }\n else {\n result = schema._zod.run({ value, issues: [] }, ctx);\n }\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length === 0;\n}\n// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw\nexport const validateAsync = async (schema, value, _ctx) => {\n const ctx = _ctx\n ? { ..._ctx, async: true, abortEarly: true }\n : { async: true, abortEarly: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length === 0;\n};\nexport const _encode = (_Err) => {\n const parse = _parse(_Err);\n const fn = (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return parse(schema, value, ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => {\n const parse = _parse(_Err);\n const fn = (schema, value, _ctx, _params) => {\n return parse(schema, value, _ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => {\n const parseAsync = _parseAsync(_Err);\n const fn = async (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params)));\n };\n return fn;\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => {\n const parseAsync = _parseAsync(_Err);\n const fn = async (schema, value, _ctx, _params) => {\n return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n","export const version = {\n major: 4,\n minor: 6,\n patch: 7,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def; // set _def property\n inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n inst._zod.version = version;\n const defChecks = inst._zod.def.checks;\n // if inst is itself a checks.$ZodCheck, run it as a check\n const checks = inst._zod.traits.has(\"$ZodCheck\")\n ? [inst, ...(defChecks ?? [])]\n : defChecks?.length\n ? [...defChecks]\n : [];\n for (const ch of checks) {\n for (const fn of ch._zod.onattach) {\n fn(inst);\n }\n }\n if (checks.length === 0) {\n // deferred initializer inst._zod.parse is not yet defined\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n }\n else {\n const runChecks = (payload, checks, ctx) => {\n if (payload.memo)\n return payload;\n let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n if (util.explicitlyAborted(payload))\n continue;\n const shouldRun = ch._zod.def.when(payload);\n if (!shouldRun)\n continue;\n }\n else if (isAborted) {\n continue;\n }\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) {\n throw new core.$ZodAsyncError();\n }\n if (asyncResult || _ instanceof Promise) {\n asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n return;\n util.attachSchema(payload.issues, currLen, inst);\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n });\n }\n else {\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n continue;\n util.attachSchema(payload.issues, currLen, inst);\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n }\n }\n if (asyncResult) {\n return asyncResult.then(() => {\n return payload;\n });\n }\n return payload;\n };\n const handleCanaryResult = (canary, payload, ctx) => {\n // abort if the canary is aborted\n if (util.aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n // run checks first, then\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) {\n return inst._zod.parse(payload, ctx);\n }\n if (ctx.direction === \"backward\") {\n // run canary initial pass (no checks)\n const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n if (canary instanceof Promise) {\n return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n }\n return handleCanaryResult(canary, payload, ctx);\n }\n // forward\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n}, {\n // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness.\n get \"~standard\"() {\n return util.hide(this, \"~standard\", standardProps(this));\n },\n set \"~standard\"(value) {\n util.own(this, \"~standard\", value);\n },\n});\n/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */\n// a Standard Schema result only reports issues, so a failure finalizes them straight off the raw payload: no ZodError, and no lazy result to read through\nconst toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())) } : { value: r.value };\nasync function validateAsync(inst, value) {\n const ctx = { async: true };\n return toStandardResult((await inst._zod.run({ value, issues: [] }, ctx)), ctx);\n}\nexport function standardProps(inst) {\n return {\n validate: (value) => {\n const ctx = { async: false };\n try {\n const r = inst._zod.run({ value, issues: [] }, ctx);\n if (!(r instanceof Promise))\n return toStandardResult(r, ctx);\n }\n catch (_) { }\n // async function so a synchronously throwing check rejects instead of escaping validate\n return validateAsync(inst, value);\n },\n vendor: \"zod\",\n version: 1,\n };\n}\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n // a format's own pattern, else unbounded; a template literal derives the check-aware form itself\n inst._zod.pattern = def.pattern ?? regexes.anyString;\n inst._zod.parse = (payload, _) => {\n if (def.coerce)\n try {\n payload.value = String(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"string\")\n return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n // check initialization must come first\n checks.$ZodCheckStringFormat.init(inst, def);\n $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.guid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n if (def.version) {\n const versionMap = {\n v1: 1,\n v2: 2,\n v3: 3,\n v4: 4,\n v5: 5,\n v6: 6,\n v7: 7,\n v8: 8,\n };\n const v = versionMap[def.version];\n if (v === undefined)\n throw new Error(`Invalid UUID version: \"${def.version}\"`);\n def.pattern ?? (def.pattern = regexes.uuid(v));\n }\n else\n def.pattern ?? (def.pattern = regexes.uuid());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.email);\n $ZodStringFormat.init(inst, def);\n});\n/** The `://` guard rejected the input before the URL constructor saw it. */\nexport const URL_BAD_FORMAT = 1;\n/** The URL parser rejected the input. */\nexport const URL_UNPARSEABLE = 2;\nexport function canParseURL(input) {\n try {\n if (typeof URL !== \"undefined\" && typeof URL.canParse === \"function\")\n return URL.canParse(input);\n new URL(input);\n return true;\n }\n catch {\n return false;\n }\n}\nexport function validateURL(trimmed, def) {\n if (!(\"normalize\" in def) && !(\"hostname\" in def) && !(\"protocol\" in def)) {\n return canParseURL(trimmed) || URL_UNPARSEABLE;\n }\n return parseURLObject(trimmed, def);\n}\n/** Parses a URL while preserving the non-normalizing HTTP guard. */\nexport function parseURLObject(trimmed, def) {\n // When normalize is off, require :// for http/https URLs. This prevents strings like \"http:example.com\" or \"https:/path\" from being silently accepted\n if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source && !/^https?:\\/\\//i.test(trimmed)) {\n return URL_BAD_FORMAT;\n }\n try {\n if (typeof URL !== \"undefined\") {\n const URLStatic = URL;\n if (typeof URLStatic.parse === \"function\")\n return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE;\n }\n // @ts-ignore\n return new URL(trimmed);\n }\n catch {\n return URL_UNPARSEABLE;\n }\n}\nconst asciiTabOrNewline = /[\\t\\n\\r]/g;\n/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL(\"https://exa\\nmple.com\")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */\nexport function stripTabAndNewline(value) {\n return value.replace(asciiTabOrNewline, \"\");\n}\nexport function urlHostnameOk(url, hostname) {\n hostname.lastIndex = 0;\n return hostname.test(url.hostname);\n}\nexport function urlProtocolOk(url, protocol) {\n protocol.lastIndex = 0;\n return protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol);\n}\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n try {\n // Trim whitespace from input\n const trimmed = payload.value.trim();\n const url = validateURL(trimmed, def);\n if (url === URL_BAD_FORMAT) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid URL format\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n if (url === URL_UNPARSEABLE) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n if (url === true) {\n payload.value = stripTabAndNewline(trimmed);\n return;\n }\n if (def.hostname && !urlHostnameOk(url, def.hostname)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid hostname\",\n pattern: def.hostname.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n if (def.protocol && !urlProtocolOk(url, def.protocol)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid protocol\",\n pattern: def.protocol.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n // Set the output value based on normalize flag\n payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed);\n return;\n }\n catch (_) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.emoji());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1))\n throw new Error(`Invalid nanoid length: ${def.length}`);\n def.pattern ?? (def.pattern = def.length === undefined ? regexes.nanoid : regexes.nanoidOfLength(def.length));\n $ZodStringFormat.init(inst, def);\n});\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid2);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ulid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.xid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ksuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.datetime(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.date);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.time(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.duration);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv4);\n $ZodStringFormat.init(inst, def);\n});\n/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL(\"http://[...]\")` parses an authority, not an address, so `@` and `\\` re-delimit it and `\"::@1\\\\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `\"::1\\n\"` validated as `::1`. */\nconst ipv6Alphabet = /^[0-9a-fA-F:.]+$/;\nexport function isValidIPv6(value) {\n if (!ipv6Alphabet.test(value))\n return false;\n return canParseURL(`http://[${value}]`);\n}\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv6);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (!isValidIPv6(payload.value)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"ipv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport function isValidCIDRv6(value) {\n const parts = value.split(\"/\");\n if (parts.length !== 2)\n return false;\n const [address, prefix] = parts;\n if (!prefix)\n return false;\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n return false;\n if (prefixNum < 0 || prefixNum > 128)\n return false;\n return isValidIPv6(address);\n}\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (!isValidCIDRv6(payload.value)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"cidrv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64(data) {\n if (data === \"\")\n return true;\n // atob ignores whitespace, so reject it up front.\n if (/\\s/.test(data))\n return false;\n if (data.length % 4 !== 0)\n return false;\n try {\n // @ts-ignore\n atob(data);\n return true;\n }\n catch {\n return false;\n }\n}\n// lax on purpose: the quantified regexes.base64 overflows the regex stack on multi-MB input and its leading ^$| alternation leaks through template-literal composition; isValidBase64 enforces length and padding\nexport const base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/;\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = base64Charset);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidBase64(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodBase64URL //////////////////////////////\n// lax on purpose: the quantified regexes.base64url overflows the regex stack on multi-MB input; isValidBase64 enforces length on the padded string\nexport const base64urlCharset = /^[A-Za-z0-9_-]*$/;\nexport function isValidBase64URL(data) {\n if (!base64urlCharset.test(data))\n return false;\n const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n def.pattern ?? (def.pattern = base64urlCharset);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidBase64URL(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.e164);\n $ZodStringFormat.init(inst, def);\n});\n////////////////////////////// ZodCreditCard //////////////////////////////\nconst CC_SANITIZE = /[- ]/g;\n/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */\nfunction isLuhnAlgo(digits) {\n let length = digits.length;\n let bit = 1;\n let sum = 0;\n while (length) {\n const value = digits.charCodeAt(--length) - 48;\n bit ^= 1;\n sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value;\n }\n return sum % 10 === 0;\n}\nexport function isValidCreditCard(input) {\n if (!regexes.creditCard.test(input))\n return false;\n return isLuhnAlgo(input.replace(CC_SANITIZE, \"\"));\n}\nexport const $ZodCreditCard = /*@__PURE__*/ core.$constructor(\"$ZodCreditCard\", (inst, def) => {\n // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone.\n def.pattern ?? (def.pattern = regexes.creditCard);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidCreditCard(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"credit_card\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodIBAN //////////////////////////////\n// iso 7064 mod 97-10 checksum without BigInt\nfunction isIso7064Mod97(iban) {\n let remainder = 0;\n const len = iban.length;\n for (let i = 4; i < len; i++) {\n const code = iban.charCodeAt(i);\n remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;\n }\n for (let i = 0; i < 4; i++) {\n const code = iban.charCodeAt(i);\n remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;\n }\n return remainder === 1;\n}\nexport function isValidIBAN(input) {\n if (!regexes.iban.test(input))\n return false;\n return isIso7064Mod97(input);\n}\nexport const $ZodIBAN = /*@__PURE__*/ core.$constructor(\"$ZodIBAN\", (inst, def) => {\n // shape only — checksum is not expressible as a pattern\n def.pattern ?? (def.pattern = regexes.iban);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidIBAN(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"iban\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodJWT //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n try {\n const tokensParts = token.split(\".\");\n if (tokensParts.length !== 3)\n return false;\n const [header] = tokensParts;\n if (!header)\n return false;\n // @ts-ignore\n const parsedHeader = JSON.parse(atob(header));\n if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n return false;\n if (!parsedHeader.alg)\n return false;\n if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidJWT(payload.value, def.alg))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"jwt\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (def.fn(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.number;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Number(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n return payload;\n }\n const received = typeof input === \"number\"\n ? Number.isNaN(input)\n ? \"NaN\"\n : !Number.isFinite(input)\n ? String(input)\n : undefined\n : undefined;\n payload.issues.push({\n expected: \"number\",\n code: \"invalid_type\",\n input,\n inst,\n ...(received ? { received } : {}),\n });\n return payload;\n };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n checks.$ZodCheckNumberFormat.init(inst, def);\n $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.boolean;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Boolean(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"boolean\")\n return payload;\n payload.issues.push({\n expected: \"boolean\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.bigint;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = BigInt(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"bigint\")\n return payload;\n payload.issues.push({\n expected: \"bigint\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n checks.$ZodCheckBigIntFormat.init(inst, def);\n $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"symbol\")\n return payload;\n payload.issues.push({\n expected: \"symbol\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.undefined;\n inst._zod.values = new Set([undefined]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"undefined\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.null;\n inst._zod.values = new Set([null]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input === null)\n return payload;\n payload.issues.push({\n expected: \"null\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.issues.push({\n expected: \"never\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"void\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce) {\n try {\n payload.value = new Date(payload.value);\n }\n catch (_err) { }\n }\n const input = payload.value;\n const isDate = input instanceof Date;\n const isValidDate = isDate && !Number.isNaN(input.getTime());\n if (isValidDate)\n return payload;\n payload.issues.push({\n expected: \"date\",\n code: \"invalid_type\",\n input,\n ...(isDate ? { received: \"Invalid Date\" } : {}),\n inst,\n });\n return payload;\n };\n});\n// an oversized container fails its leading size checks before any element is parsed\nfunction capSize(inst, size) {\n const caps = util.sizeCaps(inst._zod.def.checks);\n if (!caps.length)\n return;\n const cap = Math.min(...caps.map((c) => c[0]));\n const parse = inst._zod.parse;\n inst._zod.parse = (payload, ctx) => {\n const n = size(payload.value);\n if (n > cap && !ctx?.skipChecks && ctx?.direction !== \"backward\") {\n for (const [max, ch] of util.sizeCaps(inst._zod.def.checks)) {\n if (n > max && ch._zod.def.when(payload)) {\n const start = payload.issues.length;\n ch._zod.check(payload);\n // the value is still the raw input, so no later check may read it\n payload.issues[start].continue = false;\n util.attachSchema(payload.issues, start, inst);\n return payload;\n }\n }\n }\n return parse(payload, ctx);\n };\n}\nconst arraySize = (input) => (Array.isArray(input) ? input.length : -1);\nconst mapSize = (input) => (input instanceof Map ? input.size : -1);\nconst setSize = (input) => (input instanceof Set ? input.size : -1);\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length);\n const proms = [];\n const abortEarly = ctx?.abortEarly;\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n }\n else {\n handleArrayResult(result, payload, i);\n // the element's payload is authoritative here, since handleArrayResult forwards every issue; an object's is not, because it drops a failed absent optional\n if (abortEarly && result.issues.length !== 0 && util.aborted(result))\n break;\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n capSize(inst, arraySize);\n});\nfunction handlePropertyResult(result, final, key, input, optin, optout) {\n const isPresent = key in input;\n const isOptionalOut = optout === \"optional\";\n // The middle rung means \"absence permitted, nothing supplied in its place\", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key.\n if (!isPresent && isOptionalOut && optin === \"optional\") {\n return;\n }\n if (result.issues.length) {\n // For optional-in/out schemas, ignore errors on absent keys.\n if (optin !== undefined && isOptionalOut && !isPresent) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (!isPresent && optin === undefined) {\n if (!result.issues.length) {\n final.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [key],\n });\n }\n return;\n }\n if (result.value === undefined) {\n if (isPresent || (optin === \"defaulted\" && !isOptionalOut)) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\n// one shared instance; a fresh [] per schema cost 56 bytes retained\nconst NO_SYMBOL_KEYS = [];\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n const ownSymbols = Object.getOwnPropertySymbols(def.shape);\n const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS;\n // aliases `keys` when there are no symbols, so a string-only shape keeps one array\n const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys;\n for (const k of allKeys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${String(k)}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n allKeys,\n symbolKeys,\n // string-only: handleCatchall matches it against `for...in`, which never yields a symbol\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst, abortEarly) {\n const unrecognized = [];\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const optin = _catchall.optin;\n const optout = _catchall.optout;\n // starts at 0, not the current length: the shape phase already ran and may have aborted\n let seen = 0;\n for (const key in input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output.\n if (keySet.has(key))\n continue;\n // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping.\n if (key === \"__proto__\") {\n if (t === \"never\")\n unrecognized.push(key);\n continue;\n }\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n }\n else {\n handlePropertyResult(r, payload, key, input, optin, optout);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand.\n continue: true,\n });\n }\n if (!proms.length)\n return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodType.init(inst, def);\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n // a cloned def carries its source's accessor, which knows the shape it answers from; adopting that keeps the clone's keys readable without running it\n const sh = desc?.get ? desc.get.raw : (def.shape ?? {});\n if (sh) {\n // Freezes the shape on first read, so its getters resolve once and every later read sees the same schemas.\n const get = () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", { value: newSh });\n get.raw = newSh;\n return newSh;\n };\n get.raw = sh;\n Object.defineProperty(def, \"shape\", { get });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazyInternal(inst, \"propValues\", (zod) => {\n const shape = zod.def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n if (!Object.prototype.hasOwnProperty.call(propValues, key)) {\n util.assignProp(propValues, key, new Set());\n }\n for (const v of field.values)\n propValues[key].add(v);\n // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it.\n if (field.optin !== undefined)\n propValues[key].add(undefined);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const proms = [];\n const shape = value.shape;\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const key of value.allKeys) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n if (key === \"__proto__\")\n continue;\n const el = shape[key];\n const optin = el._zod.optin;\n const optout = el._zod.optout;\n const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n }\n else {\n handlePropertyResult(r, payload, key, input, optin, optout);\n }\n }\n if (!catchall) {\n return proms.length ? Promise.all(proms).then(() => payload) : payload;\n }\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst, abortEarly === true);\n };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodObject.init(inst, def);\n const superParse = inst._zod.parse;\n const _normalized = util.cached(() => normalizeDef(def));\n const memo = core.globalConfig.memoizer;\n const generateFastpass = (shape) => {\n const normalized = _normalized.value;\n const syms = normalized.symbolKeys;\n // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope\n const doc = new Doc([\"payload\", \"ctx\"], { shape, inst, memo, syms });\n const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n // prefixes in place, like util.prefixIssues. newResult must land before the early return: a catchall runs after this and would otherwise write onto the caller's input\n const prefixStr = (id, k) => `\n let ${id}_ab = false;\n for (let i = 0; i < ${id}.issues.length; i++) {\n const iss = ${id}.issues[i];\n iss.path = iss.path ? [${k}, ...iss.path] : [${k}];\n payload.issues.push(iss);\n if (iss.continue !== true) ${id}_ab = true;\n }\n if (${id}_ab && ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }`;\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.allKeys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`);\n for (const key of normalized.allKeys) {\n if (key === \"__proto__\")\n continue;\n const id = ids[key];\n const k = typeof key === \"symbol\" ? `syms[${syms.indexOf(key)}]` : util.esc(key);\n const isPresent = `${k} in input`;\n const schema = shape[key];\n const optin = schema?._zod?.optin;\n const isOptionalIn = optin !== undefined;\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(k)};`);\n if (isOptionalIn && isOptionalOut) {\n // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all.\n const assign = optin === \"optional\" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`;\n doc.write(`\n const ${id}_present = ${isPresent};\n if (!${id}.issues.length || ${id}_present) {\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n\n if (${assign}) {\n newResult[${k}] = ${id}.value;\n }\n }\n\n `);\n }\n else if (!isOptionalIn) {\n doc.write(`\n const ${id}_present = ${isPresent};\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n if (!${id}_present && !${id}.issues.length) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [${k}]\n });\n if (ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }\n }\n\n if (${id}_present) {\n newResult[${k}] = ${id}.value;\n }\n\n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n `);\n if (optin === \"defaulted\") {\n doc.write(`newResult[${k}] = ${id}.value;`);\n }\n else {\n doc.write(`\n if (${id}.value !== undefined || ${isPresent}) {\n newResult[${k}] = ${id}.value;\n }\n `);\n }\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone\n return doc.compile();\n };\n let fastpass;\n const isObject = util.isObject;\n const jit = !core.globalConfig.jitless;\n const allowsEval = util.allowsEval;\n const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n // always synchronous\n if (!fastpass)\n fastpass = generateFastpass(def.shape);\n payload = fastpass(payload, ctx);\n if (!catchall)\n return payload;\n return handleCatchall([], input, payload, ctx, value, inst, ctx?.abortEarly === true);\n }\n return superParse(payload, ctx);\n };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n for (const result of results) {\n if (result.issues.length === 0) {\n final.value = result.value;\n return final;\n }\n }\n const nonaborted = results.filter((r) => !util.aborted(r));\n if (nonaborted.length === 1) {\n final.value = nonaborted[0].value;\n return nonaborted[0];\n }\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.options.some((o) => o._zod.optin === \"defaulted\")\n ? \"defaulted\"\n : zod.def.options.some((o) => o._zod.optin !== undefined)\n ? \"optional\"\n : undefined);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazyInternal(inst, \"values\", (zod) => {\n if (zod.def.options.every((o) => o._zod.values)) {\n return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n if (zod.def.options.every((o) => o._zod.pattern)) {\n const patterns = zod.def.options.map((o) => o._zod.pattern);\n return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n }\n return undefined;\n });\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n if (result.issues.length === 0)\n return result;\n results.push(result);\n }\n }\n if (!async)\n return handleUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleUnionResults(results, payload, inst, ctx);\n });\n };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n const matches = [];\n for (let i = 0; i < results.length; i++) {\n if (results[i].issues.length === 0)\n matches.push(i);\n }\n if (matches.length === 1) {\n final.value = results[matches[0]].value;\n return final;\n }\n if (matches.length === 0) {\n // No matches - same as regular union\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n }\n else {\n // Multiple matches - exclusive union failure\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: [],\n inclusive: false,\n matches,\n });\n }\n return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n $ZodUnion.init(inst, def);\n def.inclusive = false;\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n results.push(result);\n }\n }\n if (!async)\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n });\n };\n});\n/** Returns the option whose discriminator claims `value`, or throws if ambiguous. */\nexport function getDiscriminatedOption(union, value) {\n const internals = union._zod;\n let map = internals.bag.optionsMap;\n if (!map) {\n map = discriminatorMap(internals.def);\n internals.bag.optionsMap = map;\n }\n const option = map.get(value);\n if (option === null)\n throw new Error(`Ambiguous discriminator value \"${String(value)}\"`);\n return option;\n}\nfunction discriminatorMap(def) {\n const map = new Map();\n for (const option of def.options) {\n const values = option._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const value of values) {\n if (map.has(value)) {\n if (value !== undefined)\n throw new Error(`Duplicate discriminator value \"${String(value)}\"`);\n // keep the collision marked so a later member cannot reclaim it\n map.set(value, null);\n }\n else {\n map.set(value, option);\n }\n }\n }\n return map;\n}\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n def.inclusive = false;\n $ZodUnion.init(inst, def);\n const _super = inst._zod.parse;\n util.defineLazyInternal(inst, \"propValues\", (zod) => {\n const propValues = {};\n let undefinedCount = 0;\n for (const option of zod.def.options) {\n const pv = option._zod.propValues;\n if (!pv || Object.keys(pv).length === 0)\n throw new Error(`Invalid discriminated union option at index \"${zod.def.options.indexOf(option)}\"`);\n if (pv[zod.def.discriminator]?.has(undefined))\n undefinedCount++;\n for (const [k, v] of Object.entries(pv)) {\n if (!Object.prototype.hasOwnProperty.call(propValues, k)) {\n util.assignProp(propValues, k, new Set());\n }\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n if (!zod.def.unionFallback && undefinedCount > 1)\n propValues[zod.def.discriminator]?.delete(undefined);\n return propValues;\n });\n // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes and lazies — are left to the map.\n def.options.forEach((option, i) => {\n const propShape = util.rawShape(option._zod.def);\n if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) {\n throw new Error(`Invalid discriminated union option at index \"${i}\"`);\n }\n });\n const disc = util.cached(() => discriminatorMap(def));\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isObject(input)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"object\",\n input,\n inst,\n });\n return payload;\n }\n const value = input?.[def.discriminator];\n const opt = disc.value.get(value);\n // forward metadata cannot choose an encoder for an absent tag\n if (opt && (value !== undefined || ctx.direction !== \"backward\")) {\n return opt._zod.run(payload, ctx);\n }\n // Fall back to union matching when the fast discriminator path fails:\n // - explicitly enabled via unionFallback, or\n // - during backward direction (encode), since codec-based discriminators have different values in forward vs backward directions\n if (def.unionFallback || ctx.direction === \"backward\") {\n return _super(payload, ctx);\n }\n // no matching discriminator\n payload.issues.push({\n code: \"invalid_union\",\n errors: [],\n note: \"No matching discriminator\",\n discriminator: def.discriminator,\n options: Array.from(disc.value.keys()).filter((value) => disc.value.get(value) !== null),\n input,\n path: [def.discriminator],\n inst,\n });\n return payload;\n };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n const async = left instanceof Promise || right instanceof Promise;\n if (async) {\n return Promise.all([left, right]).then(([left, right]) => {\n return handleIntersectionResults(payload, left, right);\n });\n }\n return handleIntersectionResults(payload, left, right);\n };\n});\nexport function mergeValues(a, b) {\n // const aType = parse.t(a);\n // const bType = parse.t(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n if (a instanceof Date && b instanceof Date && +a === +b) {\n return { valid: true, data: a };\n }\n if (util.isPlainObject(a) && util.isPlainObject(b)) {\n const bKeys = Object.keys(b);\n const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n if (Object.prototype.hasOwnProperty.call(newObj, \"__proto__\"))\n delete newObj.__proto__;\n for (const key of sharedKeys) {\n if (key === \"__proto__\")\n continue;\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return { valid: false, mergeErrorPath: [] };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n // Track which side(s) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key.\n const unrecKeys = new Map();\n let unrecIssue;\n const keyIssues = new Map();\n const collect = (iss, side) => {\n let keys;\n if (iss.code === \"unrecognized_keys\" && !iss.path?.length) {\n unrecIssue ?? (unrecIssue = iss);\n keys = iss.keys;\n }\n else if (iss.code === \"invalid_key\" && iss.origin === \"record\" && iss.path?.length === 1) {\n const k = String(iss.path[0]);\n if (!keyIssues.has(k))\n keyIssues.set(k, iss);\n keys = [k];\n }\n else {\n return false;\n }\n for (const k of keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k)[side] = true;\n }\n return true;\n };\n for (const iss of left.issues) {\n if (!collect(iss, \"l\"))\n result.issues.push(iss);\n }\n for (const iss of right.issues) {\n if (!collect(iss, \"r\"))\n result.issues.push(iss);\n }\n // Report only keys rejected by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length) {\n const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : [];\n if (aggregated.length)\n result.issues.push({ ...unrecIssue, keys: aggregated });\n for (const k of bothKeys) {\n if (!aggregated.includes(k) && keyIssues.has(k))\n result.issues.push(keyIssues.get(k));\n }\n }\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n if (util.aborted(result))\n return result;\n throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n }\n result.value = merged.data;\n return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n $ZodType.init(inst, def);\n const items = def.items;\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n input,\n inst,\n expected: \"tuple\",\n code: \"invalid_type\",\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, [], ctx) : [];\n const proms = [];\n const optinStart = getTupleOptStart(items, \"optin\");\n const optoutStart = getTupleOptStart(items, \"optout\");\n if (!def.rest) {\n if (input.length < optinStart) {\n payload.issues.push({\n code: \"too_small\",\n minimum: optinStart,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n if (input.length > items.length) {\n payload.issues.push({\n code: \"too_big\",\n maximum: items.length,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n }\n }\n // Run every item in parallel, collecting results into an indexed array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output.\n const itemResults = new Array(items.length);\n // only tracked when there is a rest loop to skip\n const abortEarly = def.rest ? ctx?.abortEarly : undefined;\n let itemAborted = false;\n for (let i = 0; i < items.length; i++) {\n const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((rr) => {\n itemResults[i] = rr;\n }));\n }\n else {\n itemResults[i] = r;\n if (abortEarly && !itemAborted && r.issues.length)\n itemAborted = util.aborted(r);\n }\n }\n // sound because rest is non-empty exactly when every fixed index is present, the one case handleTupleResults cannot discard an item's issues\n if (def.rest && !itemAborted) {\n let i = items.length - 1;\n const rest = input.slice(items.length);\n let seen = payload.issues.length;\n for (const el of rest) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n i++;\n const result = def.rest._zod.run({ value: el, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((r) => handleTupleResult(r, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));\n }\n return handleTupleResults(itemResults, payload, items, input, optoutStart);\n };\n});\nfunction getTupleOptStart(items, key) {\n for (let i = items.length - 1; i >= 0; i--) {\n // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued.\n const omittable = key === \"optin\" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === \"optional\";\n if (!omittable)\n return i + 1;\n }\n return 0;\n}\nfunction handleTupleResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nfunction handleTupleResults(itemResults, final, items, input, optoutStart) {\n // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional rule, but only after `optoutStart`: the first index where the output tuple tail can be absent.\n for (let i = 0; i < items.length; i++) {\n const r = itemResults[i];\n const isPresent = i < input.length;\n // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`.\n if (!isPresent && i >= optoutStart && items[i]._zod.optin === \"optional\") {\n final.value.length = i;\n break;\n }\n if (r.issues.length) {\n if (!isPresent && i >= optoutStart) {\n final.value.length = i;\n break;\n }\n final.issues.push(...util.prefixIssues(i, r.issues));\n }\n final.value[i] = r.value;\n }\n // Drop trailing slots that produced `undefined` for absent input\n // (the array analog of an absent optional key on an object). The\n // `i >= input.length` floor is critical: an explicit `undefined`\n // *inside* the input must be preserved even when the schema is\n // optional-out (e.g. `z.string().or(z.undefined())` accepting an\n // explicit undefined value).\n for (let i = final.value.length - 1; i >= input.length; i--) {\n if (items[i]._zod.optout === \"optional\" && final.value[i] === undefined) {\n final.value.length = i;\n }\n else {\n break;\n }\n }\n return final;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n // no guard in either loop below: a record's invalid_key aborts but an enclosing intersection can reconcile it, so a stopped loop hides keys the sibling does not own and the intersection then rejects nothing\n const proms = [];\n const values = def.keyType._zod.values;\n if (values && !def.partial) {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const recordKeys = new Set();\n for (const key of values) {\n if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n // A declared __proto__ is stripped but is not an unrecognized key.\n if (key === \"__proto__\")\n continue;\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (keyResult.issues.length) {\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n continue;\n }\n const outKey = keyResult.value;\n if (outKey === \"__proto__\")\n continue;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!recordKeys.has(key)) {\n if (def.mode === \"loose\") {\n // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into\n if (key === \"__proto__\")\n continue;\n payload.value[key] = input[key];\n }\n else {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true,\n });\n }\n }\n else {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection.\n let unrecognized;\n // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\n continue;\n if (!Object.prototype.propertyIsEnumerable.call(input, key))\n continue;\n let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n // Numeric string fallback: if key is a numeric string and failed, retry with Number(key). This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals\n const checkNumericKey = typeof key === \"string\" && regexes.number.test(key) && keyResult.issues.length;\n if (checkNumericKey) {\n const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n if (retryResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (retryResult.issues.length === 0) {\n keyResult = retryResult;\n }\n }\n if (keyResult.issues.length) {\n if (def.mode === \"loose\") {\n // Pass through unchanged\n payload.value[key] = input[key];\n }\n else if (values) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n else {\n // Default \"strict\" behavior: error on invalid key\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n }\n continue;\n }\n // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under\n const outKey = keyResult.value;\n if (outKey === \"__proto__\")\n continue;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true,\n });\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload;\n };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Map)) {\n payload.issues.push({\n expected: \"map\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n payload.value = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map();\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const [key, value] of input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n if (keyResult instanceof Promise || valueResult instanceof Promise) {\n proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }));\n }\n else {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n capSize(inst, mapSize);\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n if (keyResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, keyResult.issues));\n }\n else {\n final.issues.push({\n code: \"invalid_key\",\n origin: \"map\",\n input,\n inst,\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n if (valueResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, valueResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_element\",\n input,\n inst,\n key: key,\n issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Set)) {\n payload.issues.push({\n input,\n inst,\n expected: \"set\",\n code: \"invalid_type\",\n });\n return payload;\n }\n const proms = [];\n payload.value = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set();\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const item of input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleSetResult(result, payload)));\n }\n else\n handleSetResult(result, payload);\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n capSize(inst, setSize);\n});\nfunction handleSetResult(result, final) {\n if (result.issues.length) {\n final.issues.push(...result.issues);\n }\n final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = util.getEnumValues(def.entries);\n const valuesSet = new Set(values);\n inst._zod.values = valuesSet;\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const patternValues = util.getEnumValues(zod.def.entries).filter((k) => util.propertyKeyTypes.has(typeof k));\n // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n return new RegExp(patternValues.length ? `^(${patternValues.map((o) => util.escapeRegex(o.toString())).join(\"|\")})$` : \"^[^\\\\s\\\\S]$\");\n });\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (valuesSet.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = new Set(def.values);\n inst._zod.values = values;\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const vals = zod.def.values;\n // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n return new RegExp(vals.length\n ? `^(${vals\n .map((o) => typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o))\n .join(\"|\")})$`\n : \"^[^\\\\s\\\\S]$\");\n });\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values: def.values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n // @ts-ignore\n if (input instanceof File)\n return payload;\n payload.issues.push({\n expected: \"file\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n core.globalConfig.memoizer?.guard(inst);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n const _out = def.transform(payload.value, payload);\n if (ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n return payload;\n };\n});\nfunction handleOptionalResult(payload, result) {\n // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it.\n payload.value = result.issues.length ? undefined : result.value;\n return payload;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung.\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n inst._zod.optout = \"optional\";\n util.defineLazyInternal(inst, \"values\", (zod) => {\n const values = zod.def.innerType._zod.values;\n return values ? new Set([...values, undefined]) : undefined;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (payload.value === undefined) {\n // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means.\n if (def.innerType._zod.optin !== \"defaulted\")\n return payload;\n // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it.\n const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n if (result instanceof Promise)\n return result.then((result) => handleOptionalResult(payload, result));\n return handleOptionalResult(payload, result);\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n // Call parent init - inherits optin/optout = \"optional\"\n $ZodOptional.init(inst, def);\n // Override values/pattern to NOT add undefined\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n util.defineLazyInternal(inst, \"pattern\", (zod) => zod.def.innerType._zod.pattern);\n // Override parse to just delegate (no undefined handling)\n inst._zod.parse = (payload, ctx) => {\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazyInternal(inst, \"values\", (zod) => {\n return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n // Forward direction (decode): allow null to pass through\n if (payload.value === null)\n return payload;\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n // inst._zod.qin = \"true\";\n inst._zod.optin = \"defaulted\";\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply defaults for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n /**\n * $ZodDefault returns the default value immediately in forward direction.\n * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe. */\n return payload;\n }\n // Forward direction: continue with default handling\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleDefaultResult(result, def));\n }\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"defaulted\";\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply prefault for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => {\n const v = zod.def.innerType._zod.values;\n return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleNonOptionalResult(result, inst));\n }\n return handleNonOptionalResult(result, inst);\n };\n});\nfunction handleNonOptionalResult(payload, inst) {\n if (!payload.issues.length && payload.value === undefined) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: payload.value,\n inst,\n });\n }\n return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(\"ZodSuccess\");\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.issues.length === 0;\n return payload;\n });\n }\n payload.value = result.issues.length === 0;\n return payload;\n };\n});\nfunction handleCatchResult(payload, result, def, ctx) {\n if (!result.issues.length) {\n payload.value = result.value;\n // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property.\n if (result.memo)\n payload.memo = true;\n return payload;\n }\n // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call.\n payload.value = def.catchValue({\n ...result,\n value: payload.value,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n return payload;\n}\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply catch logic\n const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleCatchResult(payload, result, def, ctx));\n }\n return handleCatchResult(payload, result, def, ctx);\n };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"nan\",\n code: \"invalid_type\",\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handlePipeResult(right, def.in, ctx));\n }\n return handlePipeResult(right, def.in, ctx);\n }\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handlePipeResult(left, def.out, ctx));\n }\n return handlePipeResult(left, def.out, ctx);\n };\n});\nfunction handlePipeResult(left, next, ctx) {\n // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it.\n if (left.issues.some((iss) => iss.code !== \"unrecognized_keys\")) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handleCodecAResult(left, def, ctx));\n }\n return handleCodecAResult(left, def, ctx);\n }\n else {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handleCodecAResult(right, def, ctx));\n }\n return handleCodecAResult(right, def, ctx);\n }\n };\n});\nfunction handleCodecAResult(result, def, ctx) {\n if (result.issues.length) {\n // prevent further checks\n result.aborted = true;\n return result;\n }\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const transformed = def.transform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n }\n return handleCodecTxResult(result, transformed, def.out, ctx);\n }\n else {\n const transformed = def.reverseTransform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n }\n return handleCodecTxResult(result, transformed, def.in, ctx);\n }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n // Check if transform added any issues\n if (left.issues.length) {\n left.aborted = true;\n return left;\n }\n return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodPreprocess = /*@__PURE__*/ core.$constructor(\"$ZodPreprocess\", (inst, def) => {\n $ZodPipe.init(inst, def);\n});\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.innerType._zod.propValues);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType?._zod?.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType?._zod?.optout);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then(handleReadonlyResult);\n }\n return handleReadonlyResult(result);\n };\n});\nfunction handleReadonlyResult(payload) {\n // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign.\n if (!payload.memo)\n payload.value = Object.freeze(payload.value);\n return payload;\n}\n// a leaf's pattern source with its own checks folded in: the last pattern-carrying check wins, else length bounds narrow the catch-all, else an integer format narrows the number form. the fold lives here instead of on `_zod.pattern` so a bundle without template literals never pays for it\nfunction leafPattern(schema) {\n const def = schema._zod.def;\n let pattern = def.pattern;\n let isInt = !!def.format?.includes(\"int\");\n let minimum;\n let maximum;\n for (const ch of def.checks ?? []) {\n const d = ch._zod.def;\n if (d.pattern)\n pattern = d.pattern;\n isInt || (isInt = !!d.format?.includes(\"int\"));\n const lo = d.minimum ?? d.length;\n const hi = d.maximum ?? d.length;\n if (lo !== undefined && (minimum === undefined || lo > minimum))\n minimum = lo;\n if (hi !== undefined && (maximum === undefined || hi < maximum))\n maximum = hi;\n }\n if (pattern)\n return pattern.source;\n // an empty range matches nothing at runtime, and `{8,5}` is not a legal quantifier\n if (minimum !== undefined && maximum !== undefined && minimum > maximum)\n return \"(?!)\";\n if (minimum !== undefined || maximum !== undefined)\n return regexes.string({ minimum, maximum }).source;\n const own = schema._zod.pattern;\n return (isInt && own === regexes.number ? regexes.integer : own)?.source;\n}\n// a part's pattern source. a wrapper's pattern embeds its inner pattern's source verbatim, so the folded form is substituted in place without knowing the wrapper's own composition; a union's options are joined the way the union builds its own pattern\nfunction partPattern(schema) {\n const def = schema._zod.def;\n const own = schema._zod.pattern?.source;\n // lazy resolves its inner on the internals, not the def\n const inner = def.innerType ?? schema._zod.innerType;\n if (inner) {\n const before = inner._zod.pattern?.source;\n const after = partPattern(inner);\n if (own && before && after && after !== before) {\n return own.replace(util.cleanRegex(before), () => util.cleanRegex(after));\n }\n return own;\n }\n if (def.options) {\n const sources = def.options.map(partPattern);\n if (sources.every(Boolean))\n return `^(${sources.map((s) => util.cleanRegex(s)).join(\"|\")})$`;\n }\n return leafPattern(schema);\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const regexParts = [];\n for (const part of def.parts) {\n if (typeof part === \"object\" && part !== null) {\n // is Zod schema\n const source = partPattern(part);\n if (!source) {\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n regexParts.push(util.cleanRegex(source));\n }\n else if (part === null || util.primitiveTypes.has(typeof part)) {\n regexParts.push(util.escapeRegex(`${part}`));\n }\n else {\n throw new Error(`Invalid template literal part: ${part}`);\n }\n }\n inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"string\") {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"string\",\n code: \"invalid_type\",\n });\n return payload;\n }\n inst._zod.pattern.lastIndex = 0;\n if (!inst._zod.pattern.test(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n code: \"invalid_format\",\n format: def.format ?? \"template_literal\",\n pattern: inst._zod.pattern.source,\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n $ZodType.init(inst, def);\n // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter.\n Object.defineProperty(inst, \"_def\", { value: def });\n inst._zod.def = def;\n inst.implement = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implement() must be called with a function\");\n }\n // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function.\n return Object.defineProperty(function (...args) {\n const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n const result = Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return parse(inst._def.output, result);\n }\n return result;\n }, \"_zod\", { value: inst._zod, enumerable: false });\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return Object.defineProperty(async function (...args) {\n const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n const result = await Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return await parseAsync(inst._def.output, result);\n }\n return result;\n }, \"_zod\", { value: inst._zod, enumerable: false });\n };\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"function\") {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"function\",\n input: payload.value,\n inst,\n });\n return payload;\n }\n // Check if output is a promise type to determine if we should use async implementation\n const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n if (hasPromiseOutput) {\n payload.value = inst.implementAsync(payload.value);\n }\n else {\n payload.value = inst.implement(payload.value);\n }\n return payload;\n };\n inst.input = (...args) => {\n const F = inst.constructor;\n if (Array.isArray(args[0])) {\n return new F({\n type: \"function\",\n input: new $ZodTuple({\n type: \"tuple\",\n items: args[0],\n rest: args[1],\n }),\n output: inst._def.output,\n });\n }\n return new F({\n type: \"function\",\n input: args[0],\n output: inst._def.output,\n });\n };\n inst.output = (output) => {\n const F = inst.constructor;\n return new F({\n type: \"function\",\n input: inst._def.input,\n output,\n });\n };\n return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n $ZodType.init(inst, def);\n // Cache the resolved inner type on the shared `def` so all clones of this lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, preserving identity for cycle detection on recursive schemas.\n util.defineLazy(inst._zod, \"innerType\", () => {\n const d = def;\n if (!d._cachedInner)\n d._cachedInner = def.getter();\n return d._cachedInner;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => zod.innerType?._zod?.pattern);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.innerType?._zod?.propValues);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.innerType?._zod?.optin ?? undefined);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.innerType?._zod?.optout ?? undefined);\n inst._zod.parse = (payload, ctx) => {\n const inner = inst._zod.innerType;\n return inner._zod.run(payload, ctx);\n };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n checks.$ZodCheck.init(inst, def);\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _) => {\n return payload;\n };\n inst._zod.check = (payload) => {\n const input = payload.value;\n const r = def.fn(input);\n if (r instanceof Promise) {\n return r.then((r) => handleRefineResult(r, payload, input, inst));\n }\n handleRefineResult(r, payload, input, inst);\n return;\n };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n if (!result) {\n const _iss = {\n code: \"custom\",\n input,\n inst, // incorporates params.error into issue reporting\n path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n continue: !inst._zod.def.abort,\n // params: inst._zod.def.params,\n };\n if (inst._zod.def.params)\n _iss.params = inst._zod.def.params;\n payload.issues.push(util.issue(_iss));\n }\n}\n","import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\nfunction snapshotChecks(def) {\n if (def.checks)\n def.checks = [...def.checks];\n return def;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class(snapshotChecks({ type: \"string\", ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class(snapshotChecks({ type: \"string\", coerce: true, ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n return new Class({\n type: \"string\",\n format: \"email\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"guid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v4\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v6\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v7\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n return new Class({\n type: \"string\",\n format: \"emoji\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"nanoid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link _cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid2\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ulid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"xid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ksuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n return new Class({\n type: \"string\",\n format: \"mac\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n return new Class({\n type: \"string\",\n format: \"e164\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _creditCard(Class, params) {\n return new Class({\n type: \"string\",\n format: \"credit_card\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _iban(Class, params) {\n return new Class({\n type: \"string\",\n format: \"iban\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n return new Class({\n type: \"string\",\n format: \"jwt\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport const TimePrecision = {\n Any: null,\n Minute: -1,\n Second: 0,\n Millisecond: 3,\n Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"datetime\",\n check: \"string_format\",\n offset: false,\n local: false,\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n return new Class({\n type: \"string\",\n format: \"date\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"time\",\n check: \"string_format\",\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n return new Class({\n type: \"string\",\n format: \"duration\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n return new Class(snapshotChecks({ type: \"number\", checks: [], ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class(snapshotChecks({ type: \"number\", coerce: true, checks: [], ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"safeint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"int32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"uint32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n return new Class({\n type: \"boolean\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n return new Class({\n type: \"boolean\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n return new Class({\n type: \"bigint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n return new Class({\n type: \"bigint\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"int64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"uint64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n return new Class({\n type: \"symbol\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n return new Class({\n type: \"undefined\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n return new Class({\n type: \"null\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n return new Class({\n type: \"any\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n return new Class({\n type: \"unknown\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n return new Class({\n type: \"never\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n return new Class({\n type: \"void\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n return new Class({\n type: \"date\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n return new Class({\n type: \"date\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n return new Class({\n type: \"nan\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n return new checks.$ZodCheckMultipleOf({\n check: \"multiple_of\",\n ...util.normalizeParams(params),\n value,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n return new checks.$ZodCheckMaxSize({\n check: \"max_size\",\n ...util.normalizeParams(params),\n maximum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n return new checks.$ZodCheckMinSize({\n check: \"min_size\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n return new checks.$ZodCheckSizeEquals({\n check: \"size_equals\",\n ...util.normalizeParams(params),\n size,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n const ch = new checks.$ZodCheckMaxLength({\n check: \"max_length\",\n ...util.normalizeParams(params),\n maximum,\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n return new checks.$ZodCheckMinLength({\n check: \"min_length\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n return new checks.$ZodCheckLengthEquals({\n check: \"length_equals\",\n ...util.normalizeParams(params),\n length,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n return new checks.$ZodCheckRegex({\n check: \"string_format\",\n format: \"regex\",\n ...util.normalizeParams(params),\n pattern,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n return new checks.$ZodCheckLowerCase({\n check: \"string_format\",\n format: \"lowercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n return new checks.$ZodCheckUpperCase({\n check: \"string_format\",\n format: \"uppercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n return new checks.$ZodCheckIncludes({\n check: \"string_format\",\n format: \"includes\",\n ...util.normalizeParams(params),\n includes,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n return new checks.$ZodCheckStartsWith({\n check: \"string_format\",\n format: \"starts_with\",\n ...util.normalizeParams(params),\n prefix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n return new checks.$ZodCheckEndsWith({\n check: \"string_format\",\n format: \"ends_with\",\n ...util.normalizeParams(params),\n suffix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n return new checks.$ZodCheckProperty({\n check: \"property\",\n property,\n schema,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _properties(shape, params) {\n return new checks.$ZodCheckProperties({\n check: \"properties\",\n shape,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n return new checks.$ZodCheckMimeType({\n check: \"mime_type\",\n mime: types,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n return new checks.$ZodCheckOverwrite({\n check: \"overwrite\",\n tx,\n });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n return new Class({\n type: \"array\",\n element,\n // get element() {\n // return element;\n // },\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n ...util.normalizeParams(params),\n });\n}\nexport function _xor(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n return new Class({\n type: \"union\",\n options: options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n return new Class({\n type: \"intersection\",\n left,\n right,\n });\n}\n// export function _tuple(\n// Class: util.SchemaClass<schemas.$ZodTuple>,\n// items: [],\n// params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new Class({\n type: \"tuple\",\n items,\n rest,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n return new Class({\n type: \"record\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n return new Class({\n type: \"map\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n return new Class({\n type: \"set\",\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n // if (Array.isArray(values)) {\n // for (const value of values) {\n // entries[value] = value;\n // }\n // } else {\n // Object.assign(entries, values);\n // }\n // const entries: util.EnumLike = {};\n // for (const val of values) {\n // entries[val] = val;\n // }\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n return new Class({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n return new Class({\n type: \"file\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n return new Class({\n type: \"transform\",\n transform: fn,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n return new Class({\n type: \"optional\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n return new Class({\n type: \"nullable\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n return new Class({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n return new Class({\n type: \"nonoptional\",\n innerType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n return new Class({\n type: \"success\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n return new Class({\n type: \"catch\",\n innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : util.constantCatch(catchValue)),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n return new Class({\n type: \"pipe\",\n in: in_,\n out,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n return new Class({\n type: \"readonly\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n return new Class({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n return new Class({\n type: \"lazy\",\n getter,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n return new Class({\n type: \"promise\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n const norm = util.normalizeParams(_params);\n norm.abort ?? (norm.abort = true); // default to abort:false\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...norm,\n });\n return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...util.normalizeParams(_params),\n });\n return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn, params) {\n const ch = _check((payload) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n if (!(\"input\" in _issue))\n _issue.input = payload.value;\n _issue.inst ?? (_issue.inst = ch);\n _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n payload.issues.push(util.issue(_issue));\n }\n };\n return fn(payload.value, payload);\n }, params);\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n const ch = new checks.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n const ch = new checks.$ZodCheck({ check: \"describe\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, description });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n const ch = new checks.$ZodCheck({ check: \"meta\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, ...metadata });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n const params = util.normalizeParams(_params);\n let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n if (params.case !== \"sensitive\") {\n truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n }\n const truthySet = new Set(truthyArray);\n const falsySet = new Set(falsyArray);\n const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n const _String = Classes.String ?? schemas.$ZodString;\n const stringSchema = new _String({ type: \"string\", error: params.error });\n const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n const codec = new _Codec({\n type: \"pipe\",\n in: stringSchema,\n out: booleanSchema,\n transform: ((input, payload) => {\n let data = input;\n if (params.case !== \"sensitive\")\n data = data.toLowerCase();\n if (truthySet.has(data)) {\n return true;\n }\n else if (falsySet.has(data)) {\n return false;\n }\n else {\n payload.issues.push({\n code: \"invalid_value\",\n expected: \"stringbool\",\n values: [...truthySet, ...falsySet],\n input: payload.value,\n inst: codec,\n continue: false,\n });\n return {};\n }\n }),\n reverseTransform: ((input, _payload) => {\n if (input === true) {\n return truthyArray[0] || \"true\";\n }\n else {\n return falsyArray[0] || \"false\";\n }\n }),\n error: params.error,\n });\n codec._zod.bag.truthy = truthyArray;\n codec._zod.bag.falsy = falsyArray;\n codec._zod.bag.case = params.case ?? \"insensitive\";\n return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n check: \"string_format\",\n type: \"string\",\n format,\n fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n ...params,\n };\n if (fnOrRegex instanceof RegExp) {\n def.pattern = fnOrRegex;\n }\n const inst = new Class(def);\n return inst;\n}\n","import { globalRegistry } from \"./registries.js\";\nimport { assignProp } from \"./util.js\";\nfunction assignProps(target, ...sources) {\n for (const source of sources) {\n for (const key of Reflect.ownKeys(source)) {\n if (Object.prototype.propertyIsEnumerable.call(source, key)) {\n assignProp(target, key, source[key]);\n }\n }\n }\n return target;\n}\n// function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {\n// return {\n// processor: inputs.processor,\n// metadataRegistry: inputs.metadata ?? globalRegistry,\n// target: inputs.target ?? \"draft-2020-12\",\n// unrepresentable: inputs.unrepresentable ?? \"throw\",\n// };\n// }\nexport function initializeContext(params) {\n // Normalize target: convert old non-hyphenated versions to hyphenated versions\n let target = params?.target ?? \"draft-2020-12\";\n if (target === \"draft-4\")\n target = \"draft-04\";\n if (target === \"draft-7\")\n target = \"draft-07\";\n return {\n processors: params.processors ?? {},\n metadataRegistry: params?.metadata ?? globalRegistry,\n target,\n unrepresentable: params?.unrepresentable ?? \"throw\",\n override: params?.override ?? (() => { }),\n io: params?.io ?? \"output\",\n counter: 0,\n seen: new Map(),\n sharedDefsExtractedFor: undefined,\n sharedEmitDoneFor: undefined,\n cycles: params?.cycles ?? \"ref\",\n reused: params?.reused ?? \"inline\",\n intersections: [],\n deferred: [],\n external: params?.external ?? undefined,\n };\n}\n/**\n * Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws\n * `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a\n * custom JSON Schema was written into `json`, in which case the caller must not write its own.\n */\nexport function handleUnrepresentable(schema, ctx, json, params, message) {\n const result = typeof ctx.unrepresentable === \"function\"\n ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message })\n : ctx.unrepresentable;\n if (result === \"any\")\n return false;\n if (result === undefined || result === \"throw\")\n throw new Error(message);\n Object.assign(json, result);\n return true;\n}\n// never rename this back to `process`: bundler polyfills inject a top-level `const process` that a lexical declaration of the same name collides with (#6397)\nexport function processSchema(schema, ctx, _params = { path: [], schemaPath: [] }) {\n var _a;\n const def = schema._zod.def;\n // check for schema in seens\n const seen = ctx.seen.get(schema);\n if (seen) {\n seen.count++;\n // check if cycle\n const isCycle = _params.schemaPath.includes(schema);\n if (isCycle) {\n seen.cycle = _params.path;\n }\n return seen.schema;\n }\n // initialize\n const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };\n ctx.seen.set(schema, result);\n ctx.sharedDefsExtractedFor = undefined;\n ctx.sharedEmitDoneFor = undefined;\n // custom method overrides default behavior\n const overrideSchema = schema._zod.toJSONSchema?.();\n if (overrideSchema) {\n result.schema = overrideSchema;\n }\n else {\n const params = {\n ..._params,\n schemaPath: [..._params.schemaPath, schema],\n path: _params.path,\n };\n if (schema._zod.processJSONSchema) {\n schema._zod.processJSONSchema(ctx, result.schema, params);\n }\n else {\n const _json = result.schema;\n const processor = ctx.processors[def.type];\n if (!processor) {\n throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);\n }\n processor(schema, ctx, _json, params);\n }\n const parent = schema._zod.parent;\n if (parent) {\n // Also set ref if processor didn't (for inheritance)\n if (!result.ref)\n result.ref = parent;\n processSchema(parent, ctx, params);\n ctx.seen.get(parent).isParent = true;\n }\n }\n // metadata\n const meta = ctx.metadataRegistry.get(schema);\n if (meta)\n assignProps(result.schema, meta);\n if (ctx.io === \"input\" && isTransforming(schema)) {\n // examples/defaults only apply to output type of pipe\n delete result.schema.examples;\n delete result.schema.default;\n }\n // set prefault as default\n if (ctx.io === \"input\" && \"_prefault\" in result.schema)\n (_a = result.schema).default ?? (_a.default = result.schema._prefault);\n delete result.schema._prefault;\n // pulling fresh from ctx.seen in case it was overwritten\n const _result = ctx.seen.get(schema);\n return _result.schema;\n}\n/** @deprecated Renamed to `processSchema`. An export alias declares no binding, so it is safe to keep. */\nexport { processSchema as process };\n// Escape a reference token for use in a JSON Pointer fragment (RFC 6901): `~` becomes `~0` and `/` becomes `~1`. The `~` replacement must run first.\nfunction encodeJSONPointerSegment(segment) {\n return segment.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n}\nexport function extractDefs(ctx, schema\n// params: EmitParams\n) {\n // iterate over seen map;\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // With `external` set, every registered schema resolves through the external branch of `makeURI`, so the root branch below produces the same ref the external branch would — this pass is identical whichever schema it is called with, and only needs to run once.\n if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external)\n return;\n // Track ids to detect duplicates across different schemas\n const idToSchema = new Map();\n for (const entry of ctx.seen.entries()) {\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n const existing = idToSchema.get(id);\n if (existing && existing !== entry[0]) {\n throw new Error(`Duplicate schema id \"${id}\" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);\n }\n idToSchema.set(id, entry[0]);\n }\n }\n // returns a ref to the schema defId will be empty if the ref points to an external schema (or #)\n const makeURI = (entry) => {\n // comparing the seen objects because sometimes multiple schemas map to the same seen object. e.g. lazy\n // external is configured\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n if (ctx.external) {\n const externalId = ctx.external.registry.get(entry[0])?.id; // ?? \"__shared\";// `__schema${ctx.counter++}`;\n // check if schema is in the external registry\n const uriGenerator = ctx.external.uri ?? ((id) => id);\n if (externalId) {\n return { ref: uriGenerator(externalId) };\n }\n // otherwise, add to __shared\n const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;\n entry[1].defId = id; // set defId so it will be reused if needed\n return { defId: id, ref: `${uriGenerator(\"__shared\")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` };\n }\n const uriPrefix = `#`;\n const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n // an id-less root has nowhere to be extracted to, so it stays inline and self-references as `#`\n if (entry[1] === root && !entry[1].schema.id) {\n return { ref: uriPrefix };\n }\n // self-contained schema\n const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) };\n };\n // stored cached version in `def` property remove all properties, set $ref\n const extractToDef = (entry) => {\n // if the schema is already a reference, do not extract it\n if (entry[1].schema.$ref) {\n return;\n }\n const seen = entry[1];\n const { ref, defId } = makeURI(entry);\n seen.def = { ...seen.schema };\n // defId won't be set if the schema is a reference to an external schema or if the schema is the root schema\n if (defId)\n seen.defId = defId;\n // wipe away all properties except $ref\n const schema = seen.schema;\n for (const key in schema) {\n delete schema[key];\n }\n schema.$ref = ref;\n };\n // throw on cycles\n // break cycles\n if (ctx.cycles === \"throw\") {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.cycle) {\n throw new Error(\"Cycle detected: \" +\n `#/${seen.cycle?.join(\"/\")}/<root>` +\n '\\n\\nSet the `cycles` parameter to `\"ref\"` to resolve cyclical schemas with defs.');\n }\n }\n }\n // extract schemas into $defs\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n // convert root schema to # $ref\n if (schema === entry[0]) {\n extractToDef(entry); // this has special handling for the root schema\n continue;\n }\n // extract schemas that are in the external registry\n if (ctx.external) {\n const ext = ctx.external.registry.get(entry[0])?.id;\n if (schema !== entry[0] && ext) {\n extractToDef(entry);\n continue;\n }\n }\n // extract schemas with `id` meta\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n extractToDef(entry);\n continue;\n }\n // break cycles\n if (seen.cycle) {\n // any\n extractToDef(entry);\n continue;\n }\n // extract reused schemas\n if (seen.count > 1) {\n if (ctx.reused === \"ref\") {\n extractToDef(entry);\n }\n }\n }\n if (ctx.external)\n ctx.sharedDefsExtractedFor = ctx.external;\n}\n/** Rewrites `anyOf: [{type: \"a\"}, {type: \"b\"}]` to `type: [\"a\", \"b\"]`, which every JSON Schema draft treats as equivalent and most consumers render far better for the nullable case. Only branches that are a bare type assertion qualify — anything carrying a constraint, `$ref`, `const` or metadata is left alone. Runs after `flattenRef`, so a branch an override decorated or `$defs` extraction turned into a `$ref` is no longer bare and correctly stays in `anyOf`. `oneOf` is excluded: `integer` and `number` overlap, so \"exactly one\" and \"at least one\" are not the same there. OpenAPI 3.0 is excluded: its `type` must be a single string. */\nfunction compactTypeUnion(schema) {\n const options = schema.anyOf;\n if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined)\n return;\n const types = [];\n for (const option of options) {\n if (!option || typeof option !== \"object\")\n return;\n // A branch that is itself a compactible union folds into this one — nested `anyOf` and a flat `type` array say the same thing. Compacting it first also makes the result independent of the order this pass walks the seen map in.\n compactTypeUnion(option);\n const keys = Object.keys(option);\n if (keys.length !== 1 || keys[0] !== \"type\")\n return;\n const type = option.type;\n for (const member of Array.isArray(type) ? type : [type]) {\n if (typeof member !== \"string\")\n return;\n if (!types.includes(member))\n types.push(member);\n }\n }\n delete schema.anyOf;\n // A `type` array must be non-empty and unique (metaschema); a single member is spelled as a bare string.\n schema.type = types.length === 1 ? types[0] : types;\n}\n/** Keywords `foldIntersection` knows how to combine. Anything else — `$ref`, `patternProperties`,\n * an annotation like `description` — makes a member unfoldable, so a constraint this does not\n * understand leaves the `allOf` alone instead of being silently dropped or misattributed. */\nconst FOLDABLE_KEYS = new Set([\"type\", \"properties\", \"required\", \"additionalProperties\"]);\nconst UNION_KEYS = [\"oneOf\", \"anyOf\"];\n/** A member's constraint on a key it does not declare itself. A `catchall` states one; `false`, an absent `additionalProperties`, and the empty schema a loose object emits state nothing. */\nfunction undeclaredConstraint(member) {\n const extra = member.additionalProperties;\n if (extra === undefined || extra === false || typeof extra !== \"object\" || extra === null)\n return null;\n return Object.keys(extra).length ? extra : null;\n}\n/** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */\nfunction foldObjects(members) {\n const objects = [];\n for (const member of members) {\n // A boolean subschema is legal JSON Schema and carries no keywords to fold.\n if (typeof member !== \"object\" || member.type !== \"object\")\n return null;\n for (const key in member) {\n if (!FOLDABLE_KEYS.has(key))\n return null;\n }\n objects.push(member);\n }\n const properties = {};\n const required = new Set();\n for (const object of objects) {\n for (const key in object.properties) {\n // `in` would report a `__proto__` key as already present via the prototype chain and skip it.\n if (Object.prototype.hasOwnProperty.call(properties, key))\n continue;\n // Every member constrains this key: the ones that declare it say how, and a `catchall` member constrains it too even though it does not name it. The key has to satisfy all of them, which is the same intersection one level down.\n const parts = [];\n for (const other of objects) {\n const part = other.properties?.[key] ?? undeclaredConstraint(other);\n if (part === null || part === undefined)\n continue;\n if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part)))\n parts.push(part);\n }\n const merged = parts.length === 1\n ? parts[0]\n : (foldObjects(parts) ?? { allOf: parts });\n assignProp(properties, key, merged);\n }\n for (const key of object.required ?? [])\n required.add(key);\n }\n const folded = { type: \"object\", properties };\n if (required.size)\n folded.required = [...required];\n // A key no member declares is rejected only when every member rejects it, so the fold is closed only when every member is. Otherwise it carries whatever the `catchall` members demand of such a key.\n if (objects.every((object) => object.additionalProperties === false)) {\n folded.additionalProperties = false;\n }\n else {\n const constraints = [];\n for (const object of objects) {\n const constraint = undeclaredConstraint(object);\n if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint)))\n constraints.push(constraint);\n }\n if (constraints.length === 1)\n folded.additionalProperties = constraints[0];\n else if (constraints.length > 1)\n folded.additionalProperties = { allOf: constraints };\n }\n return folded;\n}\n/** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two\n * closed object members reject each other's keys and the schema validates nothing. Zod's parser\n * pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when\n * *every* side rejects it — so the emitted schema has to pool them too, and folding the members\n * into one object is the encoding that says so on every target.\n *\n * This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref`\n * machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it\n * keeps its reference and its own closedness rather than being inlined as a stale copy. */\nfunction foldIntersection(json) {\n const allOf = json.allOf;\n if (!Array.isArray(allOf) || allOf.length < 2)\n return;\n // An `override` runs before this pass and may have written object keywords onto the intersection itself. Those are deliberate, so decline rather than overwrite them.\n for (const key of FOLDABLE_KEYS)\n if (key in json)\n return;\n // An intersection distributes over a union: `A & (X | Y)` is `(A & X) | (A & Y)`. Only the first union is distributed over; a second one stays among the members every branch folds against, where it fails the object check and declines the whole intersection rather than multiplying out.\n const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k])));\n let folded = null;\n if (!unions.length) {\n folded = foldObjects(allOf);\n }\n else {\n const union = unions[0];\n const keyword = UNION_KEYS.find((k) => Array.isArray(union[k]));\n if (Object.keys(union).length !== 1)\n return;\n const rest = allOf.filter((m) => m !== union);\n const branches = union[keyword].map((branch) => foldObjects([...rest, branch]));\n if (branches.some((b) => !b))\n return;\n folded = { [keyword]: branches };\n }\n if (!folded)\n return;\n delete json.allOf;\n assignProps(json, folded);\n}\nexport function finalize(ctx, schema) {\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // flatten refs - inherit properties from parent schemas\n const flattenRef = (zodSchema) => {\n const seen = ctx.seen.get(zodSchema);\n // already processed\n if (seen.ref === null)\n return;\n const schema = seen.def ?? seen.schema;\n const _cached = { ...schema };\n const ref = seen.ref;\n seen.ref = null; // prevent infinite recursion\n if (ref) {\n flattenRef(ref);\n const refSeen = ctx.seen.get(ref);\n const refSchema = refSeen.schema;\n // merge referenced schema into current\n if (refSchema.$ref && (ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\")) {\n // older drafts can't combine $ref with other properties\n schema.allOf = schema.allOf ?? [];\n schema.allOf.push(refSchema);\n }\n else {\n assignProps(schema, refSchema);\n }\n // restore child's own properties (child wins)\n assignProps(schema, _cached);\n const isParentRef = zodSchema._zod.parent === ref;\n // For parent chain, child is a refinement - remove parent-only properties\n if (isParentRef) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (!(key in _cached)) {\n delete schema[key];\n }\n }\n }\n // When ref was extracted to $defs, remove properties that match the definition\n if (refSchema.$ref && refSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n // If parent was extracted (has $ref), propagate $ref to this schema. This handles cases like: readonly().meta({id}).describe() where processor sets ref to innerType but parent should be referenced\n const parent = zodSchema._zod.parent;\n if (parent && parent !== ref) {\n // Ensure parent is processed first so its def has inherited properties\n flattenRef(parent);\n const parentSeen = ctx.seen.get(parent);\n if (parentSeen?.schema.$ref) {\n schema.$ref = parentSeen.schema.$ref;\n // De-duplicate with parent's definition\n if (parentSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n }\n // execute overrides\n ctx.override({\n zodSchema: zodSchema,\n jsonSchema: schema,\n path: seen.path ?? [],\n });\n };\n // Flattening walks the whole map and clears each `ref` as it goes, so a second call over the same map is a no-op scan. Skip it outright once it has run for a registry conversion.\n if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {\n for (const entry of [...ctx.seen.entries()].reverse()) {\n flattenRef(entry[0]);\n }\n if (ctx.target !== \"openapi-3.0\") {\n for (const entry of ctx.seen.entries()) {\n compactTypeUnion(entry[1].def ?? entry[1].schema);\n }\n }\n for (const rewrite of ctx.deferred)\n rewrite();\n // After flattening, every member that was extracted is a `$ref`, so the fold sees the final shape. A schema that inherits an intersection — through `z.lazy`, or any `ref` chain — holds the same `allOf` array, so fold by array identity to catch every copy.\n if (ctx.intersections.length) {\n const carriers = new Map();\n for (const seen of ctx.seen.values()) {\n for (const json of [seen.schema, seen.def]) {\n const allOf = json?.allOf;\n if (!Array.isArray(allOf))\n continue;\n const existing = carriers.get(allOf);\n if (existing)\n existing.push(json);\n else\n carriers.set(allOf, [json]);\n }\n }\n for (const allOf of ctx.intersections) {\n for (const json of carriers.get(allOf) ?? [])\n foldIntersection(json);\n }\n }\n }\n const result = {};\n if (ctx.target === \"draft-2020-12\") {\n result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n }\n else if (ctx.target === \"draft-07\") {\n result.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n else if (ctx.target === \"draft-04\") {\n result.$schema = \"http://json-schema.org/draft-04/schema#\";\n }\n else if (ctx.target === \"openapi-3.0\") {\n // OpenAPI 3.0 schema objects should not include a $schema property\n }\n else {\n // Arbitrary string values are allowed but won't have a $schema property set\n }\n if (ctx.external?.uri) {\n const id = ctx.external.registry.get(schema)?.id;\n if (!id)\n throw new Error(\"Schema is missing an `id` property\");\n result.$id = ctx.external.uri(id);\n }\n // when the root was extracted into $defs, `root.schema` is the `$ref` wrapper and `root.def` is the body that now lives under $defs\n assignProps(result, root.defId ? root.schema : (root.def ?? root.schema));\n // The `id` in `.meta()` is a Zod-specific registration tag used to extract schemas into $defs — it is not user-facing JSON Schema metadata. Strip it from the output body where it would otherwise leak. The id is preserved implicitly via the $defs key (and via $ref paths).\n const rootMetaId = ctx.metadataRegistry.get(schema)?.id;\n if (rootMetaId !== undefined && result.id === rootMetaId)\n delete result.id;\n // build defs object. With `external`, `defs` is the shared object every schema writes into, so the same entries are reassigned on every call. Without it, `defs` is fresh per call and must be rebuilt.\n const defs = ctx.external?.defs ?? {};\n if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.def && seen.defId) {\n if (seen.def.id === seen.defId)\n delete seen.def.id;\n assignProp(defs, seen.defId, seen.def);\n }\n }\n }\n if (ctx.external)\n ctx.sharedEmitDoneFor = ctx.external;\n // set definitions in result\n if (ctx.external) {\n }\n else {\n if (Object.keys(defs).length > 0) {\n if (ctx.target === \"draft-2020-12\") {\n result.$defs = defs;\n }\n else {\n result.definitions = defs;\n }\n }\n }\n try {\n // this \"finalizes\" this schema and ensures all cycles are removed each call to finalize() is functionally independent though the seen map is shared\n const finalized = JSON.parse(JSON.stringify(result));\n Object.defineProperty(finalized, \"~standard\", {\n value: {\n ...schema[\"~standard\"],\n jsonSchema: {\n input: createStandardJSONSchemaMethod(schema, \"input\", ctx.processors),\n output: createStandardJSONSchemaMethod(schema, \"output\", ctx.processors),\n },\n },\n enumerable: false,\n writable: false,\n });\n return finalized;\n }\n catch (_err) {\n throw new Error(\"Error converting schema to JSON.\");\n }\n}\nfunction isTransforming(_schema, _ctx) {\n const ctx = _ctx ?? { seen: new Set() };\n if (ctx.seen.has(_schema))\n return false;\n ctx.seen.add(_schema);\n const def = _schema._zod.def;\n if (def.type === \"transform\")\n return true;\n if (def.type === \"array\")\n return isTransforming(def.element, ctx);\n if (def.type === \"set\")\n return isTransforming(def.valueType, ctx);\n if (def.type === \"lazy\")\n return isTransforming(def.getter(), ctx);\n if (def.type === \"promise\" ||\n def.type === \"optional\" ||\n def.type === \"nonoptional\" ||\n def.type === \"nullable\" ||\n def.type === \"readonly\" ||\n def.type === \"default\" ||\n def.type === \"prefault\" ||\n def.type === \"catch\") {\n return isTransforming(def.innerType, ctx);\n }\n if (def.type === \"intersection\") {\n return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);\n }\n if (def.type === \"record\" || def.type === \"map\") {\n return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);\n }\n if (def.type === \"pipe\") {\n if (_schema._zod.traits.has(\"$ZodCodec\"))\n return true;\n return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);\n }\n if (def.type === \"object\") {\n for (const key in def.shape) {\n if (isTransforming(def.shape[key], ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"union\") {\n for (const option of def.options) {\n if (isTransforming(option, ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"tuple\") {\n for (const item of def.items) {\n if (isTransforming(item, ctx))\n return true;\n }\n if (def.rest && isTransforming(def.rest, ctx))\n return true;\n return false;\n }\n return false;\n}\n/**\n * Creates a toJSONSchema method for a schema instance.\n * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.\n */\nexport const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {\n const ctx = initializeContext({ ...params, processors });\n processSchema(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\nexport const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {\n const { libraryOptions, target } = params ?? {};\n const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });\n processSchema(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\n","import * as regexes from \"./regexes.js\";\nimport { base64Charset, base64urlCharset } from \"./schemas.js\";\nimport { extractDefs, finalize, handleUnrepresentable, initializeContext, processSchema, } from \"./to-json-schema.js\";\nimport { BIGINT_FORMAT_RANGES, NUMBER_FORMAT_RANGES, assignProp, getEnumValues } from \"./util.js\";\nconst narrowMin = (agg, key, value) => {\n if (agg[key] === undefined || value > agg[key])\n agg[key] = value;\n};\nconst narrowMax = (agg, key, value) => {\n if (agg[key] === undefined || value < agg[key])\n agg[key] = value;\n};\nconst narrowBoth = (agg, value) => {\n narrowMin(agg, \"minimum\", value);\n narrowMax(agg, \"maximum\", value);\n};\nconst addDivisor = (agg, value) => {\n agg.multipleOf ?? (agg.multipleOf = []);\n if (!agg.multipleOf.includes(value))\n agg.multipleOf.push(value);\n};\nconst addPattern = (agg, pattern) => {\n agg.patterns ?? (agg.patterns = new Set());\n agg.patterns.add(pattern);\n};\nconst intersectMime = (agg, mime) => {\n agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime];\n};\n// last-wins, matching the bag's historical write order; the flag keeps an integer format from being lost to a later float one\nconst setFormat = (agg, format) => {\n agg.format = format;\n if (format.includes(\"int\"))\n agg.isInt = true;\n};\nconst minContributor = (agg, def) => narrowMin(agg, \"minimum\", def.minimum);\nconst maxContributor = (agg, def) => narrowMax(agg, \"maximum\", def.maximum);\nconst formatContributor = (ranges) => (agg, def) => {\n setFormat(agg, def.format);\n const [minimum, maximum] = ranges[def.format];\n narrowMin(agg, \"minimum\", minimum);\n narrowMax(agg, \"maximum\", maximum);\n};\nconst contributors = {\n greater_than: (agg, def) => narrowMin(agg, def.inclusive ? \"minimum\" : \"exclusiveMinimum\", def.value),\n less_than: (agg, def) => narrowMax(agg, def.inclusive ? \"maximum\" : \"exclusiveMaximum\", def.value),\n multiple_of: (agg, def) => addDivisor(agg, def.value),\n number_format: formatContributor(NUMBER_FORMAT_RANGES),\n bigint_format: formatContributor(BIGINT_FORMAT_RANGES),\n min_length: minContributor,\n max_length: maxContributor,\n length_equals: (agg, def) => narrowBoth(agg, def.length),\n min_size: minContributor,\n max_size: maxContributor,\n size_equals: (agg, def) => narrowBoth(agg, def.size),\n string_format: (agg, def) => {\n setFormat(agg, def.format);\n if (def.pattern)\n addPattern(agg, def.pattern);\n if (def.format === \"base64\" || def.format === \"base64url\")\n agg.contentEncoding = def.format;\n if (def.local || def.precision === -1)\n agg.laxFormat = true;\n },\n mime_type: (agg, def) => intersectMime(agg, def.mime),\n};\nexport function aggregateChecks(schema) {\n const agg = {};\n const def = schema._zod.def;\n // a format schema is its own first check, same rule as $ZodType init\n const list = schema._zod.traits.has(\"$ZodCheck\")\n ? [schema, ...(def.checks ?? [])]\n : (def.checks ?? []);\n for (const ch of list)\n contributors[ch._zod.def.check]?.(agg, ch._zod.def);\n // reconcile with the bag so third-party onattach contributions still land; first-party residue is never tighter than the fold, so merging it back is idempotent for one and additive for the other\n const bag = schema._zod.bag;\n if (bag.minimum !== undefined)\n narrowMin(agg, \"minimum\", bag.minimum);\n if (bag.exclusiveMinimum !== undefined)\n narrowMin(agg, \"exclusiveMinimum\", bag.exclusiveMinimum);\n if (bag.maximum !== undefined)\n narrowMax(agg, \"maximum\", bag.maximum);\n if (bag.exclusiveMaximum !== undefined)\n narrowMax(agg, \"exclusiveMaximum\", bag.exclusiveMaximum);\n if (bag.multipleOf !== undefined)\n addDivisor(agg, bag.multipleOf);\n if (bag.format !== undefined) {\n agg.format ?? (agg.format = bag.format);\n if (bag.format.includes(\"int\"))\n agg.isInt = true;\n }\n if (bag.mime)\n intersectMime(agg, bag.mime);\n for (const pattern of bag.patterns ?? [])\n addPattern(agg, pattern);\n return agg;\n}\nconst formatMap = {\n guid: \"uuid\",\n url: \"uri\",\n datetime: \"date-time\",\n json_string: \"json-string\",\n regex: \"\", // do not set\n};\n// ==================== SIMPLE TYPE PROCESSORS ====================\n// the runtime patterns are lax so parse paths never overflow the regex stack; the emitted schema swaps in the exact block forms, which zod itself never executes\nconst exactPatterns = new Map([\n [base64Charset, regexes.base64],\n [base64urlCharset, regexes.base64url],\n]);\nconst exactPattern = (p) => exactPatterns.get(p) ?? p;\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n json.type = \"string\";\n const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema);\n if (typeof minimum === \"number\")\n json.minLength = minimum;\n if (typeof maximum === \"number\")\n json.maxLength = maximum;\n // custom pattern overrides format\n if (format) {\n json.format = formatMap[format] ?? format;\n if (json.format === \"\")\n delete json.format; // empty format is not valid\n // `z.iso.time()` is never full-time, and `laxFormat` carries the datetime shapes that also accept what their keyword forbids\n if (format === \"time\" || laxFormat) {\n delete json.format;\n }\n }\n if (contentEncoding)\n json.contentEncoding = contentEncoding;\n if (patterns && patterns.size > 0) {\n const patternList = [...patterns].map(exactPattern);\n if (patternList.length === 1)\n json.pattern = patternList[0].source;\n else if (patternList.length > 1) {\n json.allOf = [\n ...patternList.map((regex) => ({\n ...(ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\"\n ? { type: \"string\" }\n : {}),\n pattern: regex.source,\n })),\n ];\n }\n }\n};\nexport const numberProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema);\n json.type = isInt ? \"integer\" : \"number\";\n // when both minimum and exclusiveMinimum exist, pick the more restrictive one\n const exMin = typeof exclusiveMinimum === \"number\" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);\n const exMax = typeof exclusiveMaximum === \"number\" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);\n const legacy = ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\";\n if (exMin) {\n if (legacy) {\n json.minimum = exclusiveMinimum;\n json.exclusiveMinimum = true;\n }\n else {\n json.exclusiveMinimum = exclusiveMinimum;\n }\n }\n else if (typeof minimum === \"number\") {\n json.minimum = minimum;\n }\n if (exMax) {\n if (legacy) {\n json.maximum = exclusiveMaximum;\n json.exclusiveMaximum = true;\n }\n else {\n json.exclusiveMaximum = exclusiveMaximum;\n }\n }\n else if (typeof maximum === \"number\") {\n json.maximum = maximum;\n }\n if (multipleOf) {\n // JSON Schema requires a divisor strictly greater than zero, and a non-finite one does not survive JSON at all. A negative divisor accepts exactly what its absolute value accepts, so it still maps; zero, NaN and Infinity have no keyword form.\n const divisors = new Set();\n for (const divisor of multipleOf) {\n if (Number.isFinite(divisor) && divisor !== 0)\n divisors.add(Math.abs(divisor));\n else\n handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);\n }\n // chained divisors are a conjunction the keyword cannot carry alone, so extras ride an allOf, same as stacked patterns\n const [first, ...rest] = divisors;\n if (first !== undefined)\n json.multipleOf = first;\n if (rest.length)\n json.allOf = [...(json.allOf ?? []), ...rest.map((m) => ({ multipleOf: m }))];\n }\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const bigintProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"BigInt cannot be represented in JSON Schema\");\n};\nexport const symbolProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Symbols cannot be represented in JSON Schema\");\n};\nexport const nullProcessor = (_schema, ctx, json, _params) => {\n if (ctx.target === \"openapi-3.0\") {\n json.type = \"string\";\n json.nullable = true;\n json.enum = [null];\n }\n else {\n json.type = \"null\";\n }\n};\nexport const undefinedProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Undefined cannot be represented in JSON Schema\");\n};\nexport const voidProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Void cannot be represented in JSON Schema\");\n};\nexport const neverProcessor = (_schema, _ctx, json, _params) => {\n json.not = {};\n};\nexport const anyProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const unknownProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const dateProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Date cannot be represented in JSON Schema\");\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n const def = schema._zod.def;\n const values = getEnumValues(def.entries);\n // an empty enum accepts nothing, same as z.never()\n if (values.length === 0) {\n json.not = {};\n return;\n }\n // Number enums can have both string and number values\n if (values.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (values.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n json.enum = values;\n};\nexport const literalProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // a literal with no values accepts nothing, same as z.never()\n if (def.values.length === 0) {\n json.not = {};\n return;\n }\n const vals = [];\n for (const val of def.values) {\n if (val === undefined) {\n // a custom schema replaces the whole literal, so there is nothing left to accumulate\n if (handleUnrepresentable(schema, ctx, json, params, \"Literal `undefined` cannot be represented in JSON Schema\"))\n return;\n // otherwise do not add to vals\n }\n else if (typeof val === \"bigint\") {\n if (handleUnrepresentable(schema, ctx, json, params, \"BigInt literals cannot be represented in JSON Schema\"))\n return;\n vals.push(Number(val));\n }\n else {\n vals.push(val);\n }\n }\n if (vals.length === 0) {\n // do nothing (an undefined literal was stripped)\n }\n else if (vals.length === 1) {\n const val = vals[0];\n json.type = val === null ? \"null\" : typeof val;\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.enum = [val];\n }\n else {\n json.const = val;\n }\n }\n else {\n if (vals.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (vals.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n if (vals.every((v) => typeof v === \"boolean\"))\n json.type = \"boolean\";\n if (vals.every((v) => v === null))\n json.type = \"null\";\n json.enum = vals;\n }\n};\nexport const nanProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"NaN cannot be represented in JSON Schema\");\n};\nexport const templateLiteralProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const pattern = schema._zod.pattern;\n if (!pattern)\n throw new Error(\"Pattern not found in template literal\");\n _json.type = \"string\";\n _json.pattern = pattern.source;\n};\nexport const fileProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n _json.type = \"string\";\n _json.format = \"binary\";\n _json.contentEncoding = \"binary\";\n const { minimum, maximum, mime } = aggregateChecks(schema);\n if (minimum !== undefined)\n _json.minLength = minimum;\n if (maximum !== undefined)\n _json.maxLength = maximum;\n if (!mime)\n return;\n // an empty intersection means the mime checks share no value, so nothing passes at runtime; `anyOf` must be non-empty, so the false schema is `not: {}`\n if (mime.length === 0)\n _json.not = {};\n else if (mime.length === 1)\n _json.contentMediaType = mime[0];\n // only contentMediaType differs, so the shared props stay at the root\n else\n _json.anyOf = mime.map((m) => ({ contentMediaType: m }));\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const customProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Custom types cannot be represented in JSON Schema\");\n};\nexport const functionProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Function types cannot be represented in JSON Schema\");\n};\nexport const transformProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Transforms cannot be represented in JSON Schema\");\n};\nexport const mapProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Map cannot be represented in JSON Schema\");\n};\nexport const setProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Set cannot be represented in JSON Schema\");\n};\n// ==================== COMPOSITE TYPE PROCESSORS ====================\nexport const arrayProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const { minimum, maximum } = aggregateChecks(schema);\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n json.type = \"array\";\n json.items = processSchema(def.element, ctx, {\n ...params,\n path: [...params.path, \"items\"],\n });\n};\n// Transform and catch set `optin = \"optional\"` at runtime so the parser lets them observe an\n// absent key, but their declared input type stays required. An input JSON Schema describes the\n// declared type, so resolve past them to the schema that actually carries the optionality.\n// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see\n// wiki/optionality.md, \"The JSON Schema emitter reads the *static* value\".\nfunction inputOptin(schema) {\n const def = schema._zod.def;\n if (def.type === \"pipe\" && def.in._zod.traits.has(\"$ZodTransform\")) {\n return inputOptin(def.out);\n }\n if (def.type === \"catch\") {\n return inputOptin(def.innerType);\n }\n return schema._zod.optin;\n}\nexport const objectProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const shape = def.shape;\n // dropping it while still emitting `additionalProperties: false` would emit a schema that rejects data this one requires\n const symbolKeys = Object.getOwnPropertySymbols(shape);\n if (symbolKeys.length &&\n handleUnrepresentable(schema, ctx, json, params, \"Symbol keys cannot be represented in JSON Schema\")) {\n return;\n }\n json.type = \"object\";\n json.properties = {};\n for (const key in shape) {\n // assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter on the plain {} we build into\n assignProp(json.properties, key, processSchema(shape[key], ctx, {\n ...params,\n path: [...params.path, \"properties\", key],\n }));\n }\n // required keys\n const requiredKeys = [];\n for (const key of Object.keys(shape)) {\n const field = def.shape[key];\n if (ctx.io === \"input\" ? inputOptin(field) === undefined : field._zod.optout === undefined) {\n requiredKeys.push(key);\n }\n }\n if (requiredKeys.length > 0) {\n json.required = requiredKeys;\n }\n // catchall\n if (def.catchall?._zod.def.type === \"never\") {\n // strict\n json.additionalProperties = false;\n }\n else if (!def.catchall) {\n // regular\n if (ctx.io === \"output\")\n json.additionalProperties = false;\n }\n else if (def.catchall) {\n json.additionalProperties = processSchema(def.catchall, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n};\nexport const unionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches). This includes both z.xor() and discriminated unions\n const isExclusive = def.inclusive === false;\n const options = def.options.map((x, i) => processSchema(x, ctx, {\n ...params,\n path: [...params.path, isExclusive ? \"oneOf\" : \"anyOf\", i],\n }));\n if (isExclusive) {\n json.oneOf = options;\n }\n else {\n json.anyOf = options;\n }\n};\nexport const intersectionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const a = processSchema(def.left, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 0],\n });\n const b = processSchema(def.right, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 1],\n });\n const isSimpleIntersection = (val) => \"allOf\" in val && Object.keys(val).length === 1;\n const allOf = [\n ...(isSimpleIntersection(a) ? a.allOf : [a]),\n ...(isSimpleIntersection(b) ? b.allOf : [b]),\n ];\n json.allOf = allOf;\n // Recorded innermost first, so a nested intersection has already folded by the time this one is considered. The array is the handle rather than the schema, because a wrapper that inherits this schema shares the same array; `finalize` folds every object holding it. See `foldIntersection`.\n ctx.intersections.push(allOf);\n};\nexport const tupleProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"array\";\n const prefixPath = ctx.target === \"draft-2020-12\" ? \"prefixItems\" : \"items\";\n const restPath = ctx.target === \"draft-2020-12\" ? \"items\" : ctx.target === \"openapi-3.0\" ? \"items\" : \"additionalItems\";\n const prefixItems = def.items.map((x, i) => processSchema(x, ctx, {\n ...params,\n path: [...params.path, prefixPath, i],\n }));\n const rest = def.rest\n ? processSchema(def.rest, ctx, {\n ...params,\n path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n })\n : null;\n let minItems = def.items.length;\n while (minItems > 0) {\n const item = def.items[minItems - 1];\n const optional = ctx.io === \"input\" ? inputOptin(item) !== undefined : item._zod.optout === \"optional\";\n if (!optional)\n break;\n minItems--;\n }\n const maxItems = def.items.length;\n const isClosed = !def.rest;\n if (ctx.target === \"draft-2020-12\") {\n json.prefixItems = prefixItems;\n if (isClosed) {\n json.items = false;\n }\n else if (rest) {\n json.items = rest;\n }\n if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\n }\n else if (ctx.target === \"openapi-3.0\") {\n json.items = {\n anyOf: prefixItems,\n };\n if (rest) {\n json.items.anyOf.push(rest);\n }\n if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\n }\n else {\n json.items = prefixItems;\n if (isClosed) {\n json.additionalItems = false;\n }\n else if (rest) {\n json.additionalItems = rest;\n }\n if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\n }\n // explicit user-defined length checks take precedence\n const { minimum, maximum } = aggregateChecks(schema);\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n};\n/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the\n * numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key\n * behind a wrapper only carries its own `type` before then, and a union key only has its branches.\n *\n * A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather\n * than carried over: keeping them beside `type: \"string\"` reproduces the match-nothing schema this\n * exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)`\n * accepts `\"3\"` — which is the deliberate trade, since throwing on it would reject an ordinary schema\n * outright. */\nfunction stringifyKeyNames(bySchema, json, visited) {\n // an extracted key that rewrites cannot go on sharing its definition — the string form a key position needs is not the number form every other reference wants — so it inlines. One that does not rewrite keeps the `$ref`.\n if (json.$ref) {\n // a recursive key holds its own reference inside its definition, so a node already on the path is left alone rather than resolved again\n if (visited.has(json))\n return json;\n visited.add(json);\n const def = bySchema.get(json)?.def;\n if (!def)\n return json;\n const inlined = stringifyKeyNames(bySchema, def, visited);\n return inlined === def ? json : inlined;\n }\n for (const keyword of [\"anyOf\", \"oneOf\"]) {\n const branches = json[keyword];\n if (!Array.isArray(branches))\n continue;\n const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited));\n // rebuilding regardless would detach a key that had nothing to re-express, dropping its `$ref` and leaking the internal `id`\n if (mapped.some((branch, i) => branch !== branches[i]))\n json = { ...json, [keyword]: mapped };\n }\n // a member that already admits a string leaves the key unconstrained, so the node's own type re-expresses only when every member is numeric\n const types = Array.isArray(json.type) ? json.type : [json.type];\n const numericType = !types.includes(\"string\") && types.some((t) => t === \"number\" || t === \"integer\");\n // a heterogeneous key carries no type at all, so its numeric members are caught here instead\n const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined);\n if (!numericType && !values?.some((v) => typeof v === \"number\"))\n return json;\n const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json;\n if (rest.enum)\n rest.enum = rest.enum.map((v) => (typeof v === \"number\" ? String(v) : v));\n else if (typeof rest.const === \"number\")\n rest.const = String(rest.const);\n // a heterogeneous key keeps its absent type: the stringified members already say what a key may be\n if (!numericType)\n return rest;\n rest.type = \"string\";\n if (!values)\n rest.pattern = (types.includes(\"number\") ? regexes.number : regexes.integer).source;\n return rest;\n}\n/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */\nconst pendingRecords = new WeakMap();\nfunction rewriteKeyNames(ctx) {\n // an extracted key is resolved by the object `extractToDef` left in its place, so the map is built once rather than searched per reference. `_zod.toJSONSchema` can hand the same object to two schemas, so the first entry carrying a body wins, as a search would have found it.\n const bySchema = new Map();\n for (const entry of ctx.seen.values()) {\n if (entry.def && !bySchema.has(entry.schema))\n bySchema.set(entry.schema, entry);\n }\n const rewrites = new Map();\n for (const record of pendingRecords.get(ctx) ?? []) {\n const seen = ctx.seen.get(record);\n const names = (seen?.def ?? seen?.schema)?.propertyNames;\n if (!names || names === true || rewrites.has(names))\n continue;\n const rewritten = stringifyKeyNames(bySchema, names, new Set());\n if (rewritten !== names)\n rewrites.set(names, rewritten);\n }\n if (!rewrites.size)\n return;\n // the flatten has already copied each record's own properties onto every wrapper by reference, and an extracted body is another such copy, so every carrier holding a rewritten key is updated together\n for (const entry of ctx.seen.values()) {\n for (const carrier of [entry.schema, entry.def]) {\n const rewritten = carrier && rewrites.get(carrier.propertyNames);\n if (rewritten)\n carrier.propertyNames = rewritten;\n }\n }\n}\nexport const recordProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n // For looseRecord with regex patterns, use patternProperties. This correctly represents \"only validate keys matching the pattern\" semantics and composes well with allOf (intersections)\n const keyType = def.keyType;\n const patterns = aggregateChecks(keyType).patterns;\n if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n // Use patternProperties for looseRecord with regex patterns\n const valueSchema = processSchema(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"patternProperties\", \"*\"],\n });\n json.patternProperties = {};\n for (const pattern of patterns) {\n assignProp(json.patternProperties, exactPattern(pattern).source, valueSchema);\n }\n }\n else {\n // Default behavior: use propertyNames + additionalProperties\n if (ctx.target === \"draft-07\" || ctx.target === \"draft-2020-12\") {\n json.propertyNames = processSchema(def.keyType, ctx, {\n ...params,\n path: [...params.path, \"propertyNames\"],\n });\n let pending = pendingRecords.get(ctx);\n if (!pending) {\n pending = [];\n pendingRecords.set(ctx, pending);\n ctx.deferred.push(() => rewriteKeyNames(ctx));\n }\n pending.push(schema);\n }\n json.additionalProperties = processSchema(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n // Add required for keys with discrete values (enum, literal, etc.)\n const keyValues = keyType._zod.values;\n // Every key shares one value schema, so an optional-in value makes the whole key set omittable on input. Output keeps them: the exhaustive branch assigns every key, even one whose value came back undefined.\n const omittableOnInput = ctx.io === \"input\" && inputOptin(def.valueType) !== undefined;\n if (keyValues && !def.partial && !omittableOnInput) {\n const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n if (validKeyValues.length > 0) {\n json.required = validKeyValues.map(String);\n }\n }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const inner = processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n if (ctx.target === \"openapi-3.0\") {\n seen.ref = def.innerType;\n json.nullable = true;\n }\n else {\n json.anyOf = [inner, { type: \"null\" }];\n }\n};\nexport const nonoptionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\n/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON.\n * A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other\n * unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */\nconst UNREPRESENTABLE_DEFAULT = Symbol();\nfunction serializeDefaultValue(value, schema, ctx, json, params) {\n let unrepresentable = false;\n const serialized = JSON.stringify(value, (_, val) => {\n if (typeof val !== \"bigint\")\n return val;\n unrepresentable = true;\n return null;\n });\n if (!unrepresentable)\n return JSON.parse(serialized);\n handleUnrepresentable(schema, ctx, json, params, \"BigInt defaults cannot be represented in JSON Schema\");\n return UNREPRESENTABLE_DEFAULT;\n}\nexport const defaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);\n if (value !== UNREPRESENTABLE_DEFAULT)\n json.default = value;\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n if (ctx.io !== \"input\")\n return;\n const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);\n if (value !== UNREPRESENTABLE_DEFAULT)\n json._prefault = value;\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n let catchValue;\n try {\n catchValue = def.catchValue(undefined);\n }\n catch {\n handleUnrepresentable(schema, ctx, json, params, \"Dynamic catch values are not supported in JSON Schema\");\n return;\n }\n json.default = catchValue;\n};\nexport const pipeProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n const inIsTransform = def.in._zod.traits.has(\"$ZodTransform\");\n const innerType = ctx.io === \"input\" ? (inIsTransform ? def.out : def.in) : def.out;\n processSchema(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\nexport const readonlyProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.readOnly = true;\n};\nexport const promiseProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const optionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const lazyProcessor = (schema, ctx, _json, params) => {\n const innerType = schema._zod.innerType;\n processSchema(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\n// ==================== ALL PROCESSORS ====================\nexport const allProcessors = {\n string: stringProcessor,\n number: numberProcessor,\n boolean: booleanProcessor,\n bigint: bigintProcessor,\n symbol: symbolProcessor,\n null: nullProcessor,\n undefined: undefinedProcessor,\n void: voidProcessor,\n never: neverProcessor,\n any: anyProcessor,\n unknown: unknownProcessor,\n date: dateProcessor,\n enum: enumProcessor,\n literal: literalProcessor,\n nan: nanProcessor,\n template_literal: templateLiteralProcessor,\n file: fileProcessor,\n success: successProcessor,\n custom: customProcessor,\n function: functionProcessor,\n transform: transformProcessor,\n map: mapProcessor,\n set: setProcessor,\n array: arrayProcessor,\n object: objectProcessor,\n union: unionProcessor,\n intersection: intersectionProcessor,\n tuple: tupleProcessor,\n record: recordProcessor,\n nullable: nullableProcessor,\n nonoptional: nonoptionalProcessor,\n default: defaultProcessor,\n prefault: prefaultProcessor,\n catch: catchProcessor,\n pipe: pipeProcessor,\n readonly: readonlyProcessor,\n promise: promiseProcessor,\n optional: optionalProcessor,\n lazy: lazyProcessor,\n};\nexport function toJSONSchema(input, params) {\n if (\"_idmap\" in input) {\n // Registry case\n const registry = input;\n const ctx = initializeContext({ ...params, processors: allProcessors });\n const defs = {};\n // First pass: process all schemas to build the seen map\n for (const entry of registry._idmap.entries()) {\n const [_, schema] = entry;\n processSchema(schema, ctx);\n }\n const schemas = {};\n const external = {\n registry,\n uri: params?.uri,\n defs,\n };\n // Update the context with external configuration\n ctx.external = external;\n // Second pass: emit each schema\n for (const entry of registry._idmap.entries()) {\n const [key, schema] = entry;\n extractDefs(ctx, schema);\n assignProp(schemas, key, finalize(ctx, schema));\n }\n if (Object.keys(defs).length > 0) {\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n schemas.__shared = {\n [defsSegment]: defs,\n };\n }\n return { schemas };\n }\n // Single schema case\n const ctx = initializeContext({ ...params, processors: allProcessors });\n processSchema(input, ctx);\n extractDefs(ctx, input);\n return finalize(ctx, input);\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"characters\", verb: \"to have\" },\n file: { unit: \"bytes\", verb: \"to have\" },\n array: { unit: \"items\", verb: \"to have\" },\n set: { unit: \"items\", verb: \"to have\" },\n map: { unit: \"entries\", verb: \"to have\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"input\",\n email: \"email address\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO datetime\",\n date: \"ISO date\",\n time: \"ISO time\",\n duration: \"ISO duration\",\n ipv4: \"IPv4 address\",\n ipv6: \"IPv6 address\",\n mac: \"MAC address\",\n cidrv4: \"IPv4 range\",\n cidrv6: \"IPv6 range\",\n base64: \"base64-encoded string\",\n base64url: \"base64url-encoded string\",\n json_string: \"JSON string\",\n e164: \"E.164 number\",\n currency_code: \"currency code\",\n credit_card: \"credit card number\",\n iban: \"IBAN\",\n jwt: \"JWT\",\n template_literal: \"input\",\n };\n // type names: missing keys = do not translate (use raw value via ?? fallback)\n const TypeDictionary = {\n // Compatibility: \"nan\" -> \"NaN\" for display\n nan: \"NaN\",\n // All other type names omitted - they fall back to raw values via ?? operator\n };\n function getTypeName(type, input) {\n if (type === \"number\" && typeof input === \"number\" && !Number.isFinite(input)) {\n return String(input);\n }\n return TypeDictionary[type] ?? type;\n }\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = getTypeName(issue.expected);\n const receivedType = util.parsedType(issue.input);\n const received = getTypeName(receivedType, issue.input);\n return `Invalid input: expected ${expected}, received ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Invalid input: expected ${util.stringifyPrimitive(issue.values[0])}`;\n return `Invalid option: expected one of ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.exact ? \"exactly \" : issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Too big: expected ${issue.origin ?? \"value\"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elements\"}`;\n return `Too big: expected ${issue.origin ?? \"value\"} to be ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.exact ? \"exactly \" : issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `Invalid string: must start with \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `Invalid string: must end with \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Invalid string: must include \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Invalid string: must match pattern ${_issue.pattern}`;\n return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Invalid number: must be a multiple of ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Unrecognized key${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Invalid key in ${issue.origin}`;\n case \"invalid_union\":\n if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) {\n const opts = issue.options.map((o) => `'${o}'`).join(\" | \");\n return `Invalid discriminator value. Expected ${opts}`;\n }\n if (issue.inclusive === false) {\n return \"Invalid input: more than one option matched\";\n }\n return \"Invalid input\";\n case \"invalid_element\":\n return `Invalid value in ${issue.origin}`;\n default:\n return `Invalid input`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\n/* Prototypes that already carry the lazy helper methods. Seeded with the\n * intrinsics so that `init` on a foreign object — it accepts any object —\n * can never install an accessor onto a prototype we do not own. */\nconst _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\n/* Helper methods live as non-enumerable lazy getters on the shared\n * prototype instead of own properties on every instance. On first\n * access the getter allocates the per-instance closure and caches it\n * as a non-enumerable own property, so detached usage still works and\n * the allocation only happens for methods actually touched. */\nfunction _lazyMethod(proto, key, make) {\n Object.defineProperty(proto, key, {\n configurable: true,\n enumerable: false,\n get() {\n const value = make(this);\n Object.defineProperty(this, key, { value, configurable: true, writable: true });\n return value;\n },\n set(value) {\n Object.defineProperty(this, key, { value, configurable: true, writable: true });\n },\n });\n}\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n const proto = Object.getPrototypeOf(inst);\n if (_installedErrorProtos.has(proto))\n return;\n _installedErrorProtos.add(proto);\n _lazyMethod(proto, \"format\", (self) => (mapper) => core.formatError(self, mapper));\n _lazyMethod(proto, \"flatten\", (self) => (mapper) => core.flattenError(self, mapper));\n _lazyMethod(proto, \"addIssue\", (self) => (issue) => {\n self.issues.push(issue);\n self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);\n });\n _lazyMethod(proto, \"addIssues\", (self) => (issues) => {\n self.issues.push(...issues);\n self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);\n });\n Object.defineProperty(proto, \"isEmpty\", {\n configurable: true,\n enumerable: false,\n get() {\n return this.issues.length === 0;\n },\n });\n};\nexport const ZodError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer, undefined, {\n Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n","import * as core from \"../core/index.js\";\nimport { ZodRealError } from \"./errors.js\";\nexport const parse = /* @__PURE__ */ core._parse(ZodRealError);\nexport const parseAsync = /* @__PURE__ */ core._parseAsync(ZodRealError);\nexport const safeParse = /* @__PURE__ */ core._safeParse(ZodRealError);\nexport const safeParseAsync = /* @__PURE__ */ core._safeParseAsync(ZodRealError);\nexport { validate, validateAsync } from \"../core/index.js\";\n// Codec functions\nexport const encode = /* @__PURE__ */ core._encode(ZodRealError);\nexport const decode = /* @__PURE__ */ core._decode(ZodRealError);\nexport const encodeAsync = /* @__PURE__ */ core._encodeAsync(ZodRealError);\nexport const decodeAsync = /* @__PURE__ */ core._decodeAsync(ZodRealError);\nexport const safeEncode = /* @__PURE__ */ core._safeEncode(ZodRealError);\nexport const safeDecode = /* @__PURE__ */ core._safeDecode(ZodRealError);\nexport const safeEncodeAsync = /* @__PURE__ */ core._safeEncodeAsync(ZodRealError);\nexport const safeDecodeAsync = /* @__PURE__ */ core._safeDecodeAsync(ZodRealError);\n","import * as core from \"../core/index.js\";\nimport { util } from \"../core/index.js\";\nimport * as processors from \"../core/json-schema-processors.js\";\nimport * as regexes from \"../core/regexes.js\";\nimport { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport en from \"../locales/en.js\";\nimport * as checks from \"./checks.js\";\nimport * as parse from \"./parse.js\";\n// Register English as the default locale on first ZodType construction. Hooked into the `ZodType` `$constructor` (rather than a top-level `config(en())` in `external.ts`) so bundlers honoring `sideEffects: false` can't tree-shake it out — see #5953, #5725. An explicit `z.config(z.locales.xx())` call wins regardless of order, since this only sets the default when none is present.\nfunction _ensureDefaultLocale() {\n if (!core.globalConfig.localeError)\n core.config(en());\n}\n// the default memoizer is read by the core container init, which runs before `ZodType.init`, so each container calls this first\nfunction _ensureDefaultMemoizer() {\n if (!core.globalConfig.memoizer)\n core.config({ memoizer: core.memoizer() });\n}\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n _ensureDefaultLocale();\n core.$ZodType.init(inst, def);\n inst.def = def;\n inst.type = def.type;\n return inst;\n}, {\n check(...chks) {\n const def = this.def;\n return this.clone(util.mergeDefs(def, {\n checks: [\n ...(def.checks ?? []),\n ...chks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }), { parent: true });\n },\n with(...chks) {\n return this.check(...chks);\n },\n clone(def, params) {\n return core.clone(this, def, params);\n },\n brand() {\n return this;\n },\n register(reg, meta) {\n reg.add(this, meta);\n return this;\n },\n refine(check, params) {\n return this.check(refine(check, params));\n },\n superRefine(refinement, params) {\n return this.check(superRefine(refinement, params));\n },\n overwrite(fn) {\n return this.check(checks.overwrite(fn));\n },\n optional() {\n return optional(this);\n },\n exactOptional() {\n return exactOptional(this);\n },\n nullable() {\n return nullable(this);\n },\n nullish() {\n return optional(nullable(this));\n },\n nonoptional(params) {\n return nonoptional(this, params);\n },\n array() {\n return array(this);\n },\n or(arg) {\n return union([this, arg]);\n },\n and(arg) {\n return intersection(this, arg);\n },\n transform(tx) {\n return pipe(this, transform(tx));\n },\n default(d) {\n return _default(this, d);\n },\n prefault(d) {\n return prefault(this, d);\n },\n catch(params) {\n return _catch(this, params);\n },\n pipe(target) {\n return pipe(this, target);\n },\n readonly() {\n return readonly(this);\n },\n describe(description) {\n const cl = this.clone();\n core.globalRegistry.add(cl, { description });\n return cl;\n },\n meta(...args) {\n // overloaded: meta() returns the registered metadata, meta(data) returns a clone with `data` registered. The mapped type picks up the second overload, so we accept variadic any-args and return `any` to satisfy both at runtime.\n if (args.length === 0)\n return core.globalRegistry.get(this);\n const cl = this.clone();\n core.globalRegistry.add(cl, args[0]);\n return cl;\n },\n isOptional() {\n return this.safeParse(undefined).success;\n },\n isNullable() {\n return this.safeParse(null).success;\n },\n apply(fn, ...args) {\n return args.length === 0 ? fn(this) : fn(this, ...args);\n },\n // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode.\n get \"~standard\"() {\n return util.hide(this, \"~standard\", {\n ...core.standardProps(this),\n jsonSchema: {\n input: createStandardJSONSchemaMethod(this, \"input\"),\n output: createStandardJSONSchemaMethod(this, \"output\"),\n },\n });\n },\n set \"~standard\"(value) {\n util.own(this, \"~standard\", value);\n },\n parse: function _parse(data, params) {\n return parse.parse(this, data, params, { callee: _parse });\n },\n parseAsync: async function _parseAsync(data, params) {\n return await parse.parseAsync(this, data, params, { callee: _parseAsync });\n },\n safeParse(data, params) {\n return parse.safeParse(this, data, params);\n },\n async safeParseAsync(data, params) {\n return parse.safeParseAsync(this, data, params);\n },\n // `spa` is an alias: same function object as `safeParseAsync`, as before.\n get spa() {\n return this?.safeParseAsync;\n },\n set spa(value) {\n util.own(this, \"spa\", value);\n },\n validate(data, params) {\n return parse.validate(this, data, params);\n },\n validateAsync(data, params) {\n return parse.validateAsync(this, data, params);\n },\n encode: function _encode(data, params) {\n return parse.encode(this, data, params, { callee: _encode });\n },\n decode: function _decode(data, params) {\n return parse.decode(this, data, params, { callee: _decode });\n },\n encodeAsync: async function _encodeAsync(data, params) {\n return await parse.encodeAsync(this, data, params, { callee: _encodeAsync });\n },\n decodeAsync: async function _decodeAsync(data, params) {\n return await parse.decodeAsync(this, data, params, { callee: _decodeAsync });\n },\n safeEncode(data, params) {\n return parse.safeEncode(this, data, params);\n },\n safeDecode(data, params) {\n return parse.safeDecode(this, data, params);\n },\n async safeEncodeAsync(data, params) {\n return parse.safeEncodeAsync(this, data, params);\n },\n async safeDecodeAsync(data, params) {\n return parse.safeDecodeAsync(this, data, params);\n },\n toJSONSchema(params) {\n return createToJSONSchemaMethod(this, {})(params);\n },\n // Reads through to the registry on every access, so it must not cache.\n get description() {\n return core.globalRegistry.get(this)?.description;\n },\n // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property.\n get _def() {\n return this._zod.def;\n },\n});\n/** @internal */\nexport const _ZodString = /*@__PURE__*/ core.$constructor(\"_ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.stringProcessor(inst, ctx, json, params);\n}, \n/*@__PURE__*/ util.derived({\n format: (inst) => processors.aggregateChecks(inst).format ?? null,\n minLength: (inst) => processors.aggregateChecks(inst).minimum ?? null,\n maxLength: (inst) => processors.aggregateChecks(inst).maximum ?? null,\n}, {\n regex(...args) {\n return this.check(checks.regex(...args));\n },\n includes(...args) {\n return this.check(checks.includes(...args));\n },\n startsWith(...args) {\n return this.check(checks.startsWith(...args));\n },\n endsWith(...args) {\n return this.check(checks.endsWith(...args));\n },\n min(...args) {\n return this.check(checks.minLength(...args));\n },\n max(...args) {\n return this.check(checks.maxLength(...args));\n },\n length(...args) {\n return this.check(checks.length(...args));\n },\n nonempty(...args) {\n return this.check(checks.minLength(1, ...args));\n },\n lowercase(params) {\n return this.check(checks.lowercase(params));\n },\n uppercase(params) {\n return this.check(checks.uppercase(params));\n },\n trim() {\n return this.check(checks.trim());\n },\n normalize(...args) {\n return this.check(checks.normalize(...args));\n },\n toLowerCase() {\n return this.check(checks.toLowerCase());\n },\n toUpperCase() {\n return this.check(checks.toUpperCase());\n },\n slugify() {\n return this.check(checks.slugify());\n },\n}));\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n _ZodString.init(inst, def);\n}, {\n email(params) {\n return this.check(core._email(ZodEmail, params));\n },\n url(params) {\n return this.check(core._url(ZodURL, params));\n },\n jwt(params) {\n return this.check(core._jwt(ZodJWT, params));\n },\n emoji(params) {\n return this.check(core._emoji(ZodEmoji, params));\n },\n guid(params) {\n return this.check(core._guid(ZodGUID, params));\n },\n uuid(params) {\n return this.check(core._uuid(ZodUUID, params));\n },\n uuidv4(params) {\n return this.check(core._uuidv4(ZodUUID, params));\n },\n uuidv6(params) {\n return this.check(core._uuidv6(ZodUUID, params));\n },\n uuidv7(params) {\n return this.check(core._uuidv7(ZodUUID, params));\n },\n nanoid(params) {\n return this.check(core._nanoid(ZodNanoID, params));\n },\n cuid(params) {\n return this.check(core._cuid(ZodCUID, params));\n },\n cuid2(params) {\n return this.check(core._cuid2(ZodCUID2, params));\n },\n ulid(params) {\n return this.check(core._ulid(ZodULID, params));\n },\n base64(params) {\n return this.check(core._base64(ZodBase64, params));\n },\n base64url(params) {\n return this.check(core._base64url(ZodBase64URL, params));\n },\n xid(params) {\n return this.check(core._xid(ZodXID, params));\n },\n ksuid(params) {\n return this.check(core._ksuid(ZodKSUID, params));\n },\n ipv4(params) {\n return this.check(core._ipv4(ZodIPv4, params));\n },\n ipv6(params) {\n return this.check(core._ipv6(ZodIPv6, params));\n },\n cidrv4(params) {\n return this.check(core._cidrv4(ZodCIDRv4, params));\n },\n cidrv6(params) {\n return this.check(core._cidrv6(ZodCIDRv6, params));\n },\n e164(params) {\n return this.check(core._e164(ZodE164, params));\n },\n datetime(params) {\n return this.check(core._isoDateTime(ZodISODateTime, params));\n },\n date(params) {\n return this.check(core._isoDate(ZodISODate, params));\n },\n time(params) {\n return this.check(core._isoTime(ZodISOTime, params));\n },\n duration(params) {\n return this.check(core._isoDuration(ZodISODuration, params));\n },\n});\nexport function string(params) {\n return core._string(ZodString, params);\n}\nexport const ZodStringFormat = /*@__PURE__*/ core.$constructor(\"ZodStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n _ZodString.init(inst, def);\n});\nexport const ZodISODateTime = /*@__PURE__*/ core.$constructor(\"ZodISODateTime\", (inst, def) => {\n core.$ZodISODateTime.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISODate = /*@__PURE__*/ core.$constructor(\"ZodISODate\", (inst, def) => {\n core.$ZodISODate.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISOTime = /*@__PURE__*/ core.$constructor(\"ZodISOTime\", (inst, def) => {\n core.$ZodISOTime.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISODuration = /*@__PURE__*/ core.$constructor(\"ZodISODuration\", (inst, def) => {\n core.$ZodISODuration.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodEmail = /*@__PURE__*/ core.$constructor(\"ZodEmail\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmail.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function email(params) {\n return core._email(ZodEmail, params);\n}\nexport const ZodGUID = /*@__PURE__*/ core.$constructor(\"ZodGUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodGUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function guid(params) {\n return core._guid(ZodGUID, params);\n}\nexport const ZodUUID = /*@__PURE__*/ core.$constructor(\"ZodUUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodUUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function uuid(params) {\n return core._uuid(ZodUUID, params);\n}\nexport function uuidv4(params) {\n return core._uuidv4(ZodUUID, params);\n}\n// ZodUUIDv6\nexport function uuidv6(params) {\n return core._uuidv6(ZodUUID, params);\n}\n// ZodUUIDv7\nexport function uuidv7(params) {\n return core._uuidv7(ZodUUID, params);\n}\nexport const ZodURL = /*@__PURE__*/ core.$constructor(\"ZodURL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodURL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function url(params) {\n return core._url(ZodURL, params);\n}\nexport function httpUrl(params) {\n return core._url(ZodURL, {\n protocol: regexes.httpProtocol,\n hostname: regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEmoji = /*@__PURE__*/ core.$constructor(\"ZodEmoji\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmoji.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function emoji(params) {\n return core._emoji(ZodEmoji, params);\n}\nexport const ZodNanoID = /*@__PURE__*/ core.$constructor(\"ZodNanoID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodNanoID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function nanoid(params) {\n return core._nanoid(ZodNanoID, params);\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const ZodCUID = /*@__PURE__*/ core.$constructor(\"ZodCUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\n/**\n * Validates a CUID v1 string.\n *\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport function cuid(params) {\n return core._cuid(ZodCUID, params);\n}\nexport const ZodCUID2 = /*@__PURE__*/ core.$constructor(\"ZodCUID2\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID2.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid2(params) {\n return core._cuid2(ZodCUID2, params);\n}\nexport const ZodULID = /*@__PURE__*/ core.$constructor(\"ZodULID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodULID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ulid(params) {\n return core._ulid(ZodULID, params);\n}\nexport const ZodXID = /*@__PURE__*/ core.$constructor(\"ZodXID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodXID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function xid(params) {\n return core._xid(ZodXID, params);\n}\nexport const ZodKSUID = /*@__PURE__*/ core.$constructor(\"ZodKSUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodKSUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ksuid(params) {\n return core._ksuid(ZodKSUID, params);\n}\nexport const ZodIPv4 = /*@__PURE__*/ core.$constructor(\"ZodIPv4\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv4(params) {\n return core._ipv4(ZodIPv4, params);\n}\nexport const ZodMAC = /*@__PURE__*/ core.$constructor(\"ZodMAC\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodMAC.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function mac(params) {\n return core._mac(ZodMAC, params);\n}\nexport const ZodIPv6 = /*@__PURE__*/ core.$constructor(\"ZodIPv6\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv6(params) {\n return core._ipv6(ZodIPv6, params);\n}\nexport const ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv4(params) {\n return core._cidrv4(ZodCIDRv4, params);\n}\nexport const ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv6(params) {\n return core._cidrv6(ZodCIDRv6, params);\n}\nexport const ZodBase64 = /*@__PURE__*/ core.$constructor(\"ZodBase64\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64(params) {\n return core._base64(ZodBase64, params);\n}\nexport const ZodBase64URL = /*@__PURE__*/ core.$constructor(\"ZodBase64URL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64URL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64url(params) {\n return core._base64url(ZodBase64URL, params);\n}\nexport const ZodE164 = /*@__PURE__*/ core.$constructor(\"ZodE164\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodE164.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function e164(params) {\n return core._e164(ZodE164, params);\n}\nexport const ZodCreditCard = /*@__PURE__*/ core.$constructor(\"ZodCreditCard\", (inst, def) => {\n core.$ZodCreditCard.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function creditCard(params) {\n return core._creditCard(ZodCreditCard, params);\n}\nexport const ZodIBAN = /*@__PURE__*/ core.$constructor(\"ZodIBAN\", (inst, def) => {\n core.$ZodIBAN.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function iban(params) {\n return core._iban(ZodIBAN, params);\n}\nexport const ZodJWT = /*@__PURE__*/ core.$constructor(\"ZodJWT\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodJWT.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function jwt(params) {\n return core._jwt(ZodJWT, params);\n}\nexport const ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodCustomStringFormat\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCustomStringFormat.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);\n}\nexport function hostname(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hostname\", regexes.hostname, _params);\n}\nexport function hex(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hex\", regexes.hex, _params);\n}\nexport function currencyCode(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"currency_code\", regexes.currencyCode, _params);\n}\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodCustomStringFormat, format, regex, params);\n}\nexport const ZodNumber = /*@__PURE__*/ core.$constructor(\"ZodNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.numberProcessor(inst, ctx, json, params);\n inst.isFinite = true;\n}, \n/*@__PURE__*/ util.derived({\n minValue: (inst) => {\n const { minimum, exclusiveMinimum } = processors.aggregateChecks(inst);\n return Math.max(minimum ?? Number.NEGATIVE_INFINITY, exclusiveMinimum ?? Number.NEGATIVE_INFINITY);\n },\n maxValue: (inst) => {\n const { maximum, exclusiveMaximum } = processors.aggregateChecks(inst);\n return Math.min(maximum ?? Number.POSITIVE_INFINITY, exclusiveMaximum ?? Number.POSITIVE_INFINITY);\n },\n isInt: (inst) => {\n const { isInt, multipleOf } = processors.aggregateChecks(inst);\n return !!isInt || !!multipleOf?.some(Number.isSafeInteger);\n },\n format: (inst) => processors.aggregateChecks(inst).format ?? null,\n}, {\n gt(value, params) {\n return this.check(checks.gt(value, params));\n },\n gte(value, params) {\n return this.check(checks.gte(value, params));\n },\n min(value, params) {\n return this.check(checks.gte(value, params));\n },\n lt(value, params) {\n return this.check(checks.lt(value, params));\n },\n lte(value, params) {\n return this.check(checks.lte(value, params));\n },\n max(value, params) {\n return this.check(checks.lte(value, params));\n },\n int(params) {\n return this.check(int(params));\n },\n safe(params) {\n return this.check(int(params));\n },\n positive(params) {\n return this.check(checks.gt(0, params));\n },\n nonnegative(params) {\n return this.check(checks.gte(0, params));\n },\n negative(params) {\n return this.check(checks.lt(0, params));\n },\n nonpositive(params) {\n return this.check(checks.lte(0, params));\n },\n multipleOf(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n step(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n finite() {\n return this;\n },\n}));\nexport function number(params) {\n return core._number(ZodNumber, params);\n}\nexport const ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodNumber.init(inst, def);\n});\nexport function int(params) {\n return core._int(ZodNumberFormat, params);\n}\nexport function float32(params) {\n return core._float32(ZodNumberFormat, params);\n}\nexport function float64(params) {\n return core._float64(ZodNumberFormat, params);\n}\nexport function int32(params) {\n return core._int32(ZodNumberFormat, params);\n}\nexport function uint32(params) {\n return core._uint32(ZodNumberFormat, params);\n}\nexport const ZodBoolean = /*@__PURE__*/ core.$constructor(\"ZodBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.booleanProcessor(inst, ctx, json, params);\n});\nexport function boolean(params) {\n return core._boolean(ZodBoolean, params);\n}\nexport const ZodBigInt = /*@__PURE__*/ core.$constructor(\"ZodBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params);\n}, \n/*@__PURE__*/ util.derived({\n minValue: (inst) => processors.aggregateChecks(inst).minimum ?? null,\n maxValue: (inst) => processors.aggregateChecks(inst).maximum ?? null,\n format: (inst) => processors.aggregateChecks(inst).format ?? null,\n}, {\n gte(value, params) {\n return this.check(checks.gte(value, params));\n },\n min(value, params) {\n return this.check(checks.gte(value, params));\n },\n gt(value, params) {\n return this.check(checks.gt(value, params));\n },\n lt(value, params) {\n return this.check(checks.lt(value, params));\n },\n lte(value, params) {\n return this.check(checks.lte(value, params));\n },\n max(value, params) {\n return this.check(checks.lte(value, params));\n },\n positive(params) {\n return this.check(checks.gt(BigInt(0), params));\n },\n negative(params) {\n return this.check(checks.lt(BigInt(0), params));\n },\n nonpositive(params) {\n return this.check(checks.lte(BigInt(0), params));\n },\n nonnegative(params) {\n return this.check(checks.gte(BigInt(0), params));\n },\n multipleOf(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n}));\nexport function bigint(params) {\n return core._bigint(ZodBigInt, params);\n}\nexport const ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodBigInt.init(inst, def);\n});\nexport function int64(params) {\n return core._int64(ZodBigIntFormat, params);\n}\nexport function uint64(params) {\n return core._uint64(ZodBigIntFormat, params);\n}\nexport const ZodSymbol = /*@__PURE__*/ core.$constructor(\"ZodSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params);\n});\nexport function symbol(params) {\n return core._symbol(ZodSymbol, params);\n}\nexport const ZodUndefined = /*@__PURE__*/ core.$constructor(\"ZodUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params);\n});\nfunction _undefined(params) {\n return core._undefined(ZodUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodNull = /*@__PURE__*/ core.$constructor(\"ZodNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullProcessor(inst, ctx, json, params);\n});\nfunction _null(params) {\n return core._null(ZodNull, params);\n}\nexport { _null as null };\nexport const ZodAny = /*@__PURE__*/ core.$constructor(\"ZodAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.anyProcessor(inst, ctx, json, params);\n});\nexport function any() {\n return core._any(ZodAny);\n}\nexport const ZodUnknown = /*@__PURE__*/ core.$constructor(\"ZodUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unknownProcessor(inst, ctx, json, params);\n});\nexport function unknown() {\n return core._unknown(ZodUnknown);\n}\nexport const ZodNever = /*@__PURE__*/ core.$constructor(\"ZodNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.neverProcessor(inst, ctx, json, params);\n});\nexport function never(params) {\n return core._never(ZodNever, params);\n}\nexport const ZodVoid = /*@__PURE__*/ core.$constructor(\"ZodVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params);\n});\nfunction _void(params) {\n return core._void(ZodVoid, params);\n}\nexport { _void as void };\nexport const ZodDate = /*@__PURE__*/ core.$constructor(\"ZodDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params);\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n}, \n/*@__PURE__*/ util.derived({\n minDate: (inst) => {\n const { minimum } = processors.aggregateChecks(inst);\n return minimum ? new Date(minimum) : null;\n },\n maxDate: (inst) => {\n const { maximum } = processors.aggregateChecks(inst);\n return maximum ? new Date(maximum) : null;\n },\n}, {}));\nexport function date(params) {\n return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodArray.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.arrayProcessor(inst, ctx, json, params);\n inst.element = def.element;\n}, {\n min(n, params) {\n return this.check(checks.minLength(n, params));\n },\n nonempty(params) {\n return this.check(checks.minLength(1, params));\n },\n max(n, params) {\n return this.check(checks.maxLength(n, params));\n },\n length(n, params) {\n return this.check(checks.length(n, params));\n },\n unwrap() {\n return this.element;\n },\n});\nexport function array(element, params) {\n return core._array(ZodArray, element, params);\n}\n// .keyof\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodObject = /*@__PURE__*/ core.$constructor(\"ZodObject\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodObjectJIT.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.objectProcessor(inst, ctx, json, params);\n util.installLazyProp(inst, \"shape\", (self) => self._zod.def.shape, false);\n}, {\n keyof() {\n return _enum(Object.keys(this._zod.def.shape));\n },\n catchall(catchall) {\n // `mergeDefs` rather than a spread: spreading reads `shape`, and resolving it can mint a whole fresh subtree\n return this.clone(util.mergeDefs(this._zod.def, { catchall: catchall }));\n },\n passthrough() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: unknown() }));\n },\n loose() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: unknown() }));\n },\n strict() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: never() }));\n },\n strip() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: undefined }));\n },\n extend(incoming) {\n return util.extend(this, incoming);\n },\n safeExtend(incoming) {\n return util.safeExtend(this, incoming);\n },\n merge(other) {\n return util.merge(this, other);\n },\n pick(mask) {\n return util.pick(this, mask);\n },\n omit(mask) {\n return util.omit(this, mask);\n },\n partial(...args) {\n return util.partial(ZodOptional, this, args[0]);\n },\n exactPartial(...args) {\n return util.partial(ZodExactOptional, this, args[0], \"exactPartial\");\n },\n required(...args) {\n return util.required(ZodNonOptional, this, args[0]);\n },\n});\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodObject(def);\n}\n// strictObject\nexport function strictObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\nexport function looseObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\nexport const ZodUnion = /*@__PURE__*/ core.$constructor(\"ZodUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\nexport function union(options, params) {\n return new ZodUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodXor = /*@__PURE__*/ core.$constructor(\"ZodXor\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\n/** Creates an exclusive union (XOR) where exactly one option must match.\n * Unlike regular unions that succeed when any option matches, xor fails if\n * zero or more than one option matches the input. */\nexport function xor(options, params) {\n return new ZodXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodDiscriminatedUnion\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodDiscriminatedUnion.init(inst, def);\n});\nexport function discriminatedUnion(discriminator, options, params) {\n // const [options, params] = args;\n return new ZodDiscriminatedUnion({\n type: \"union\",\n options: options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodIntersection = /*@__PURE__*/ core.$constructor(\"ZodIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.intersectionProcessor(inst, ctx, json, params);\n});\nexport function intersection(left, right) {\n return new ZodIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodTuple = /*@__PURE__*/ core.$constructor(\"ZodTuple\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodTuple.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params);\n}, {\n rest(rest) {\n return this.clone({\n ...this._zod.def,\n rest: rest,\n });\n },\n partial() {\n const def = this._zod.def;\n // a refinement was authored against the full arity; partialing would run it on a shorter array\n if (def.checks?.length)\n throw new Error(\".partial() cannot be used on tuple schemas containing refinements\");\n return this.clone({\n ...def,\n items: def.items.map((item) => new ZodOptional({ type: \"optional\", innerType: item })),\n });\n },\n});\nexport function tuple(items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof core.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new ZodTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodRecord = /*@__PURE__*/ core.$constructor(\"ZodRecord\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodRecord.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.recordProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n});\nexport function record(keyType, valueType, params) {\n // v3-compat: z.record(valueType, params?) — defaults keyType to z.string()\n if (!valueType || !valueType._zod) {\n return new ZodRecord({\n type: \"record\",\n keyType: string(),\n valueType: keyType,\n ...util.normalizeParams(valueType),\n });\n }\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// type alksjf = core.output<core.$ZodRecordKey>;\nexport function partialRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n partial: true,\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMap = /*@__PURE__*/ core.$constructor(\"ZodMap\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodMap.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function map(keyType, valueType, params) {\n return new ZodMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSet = /*@__PURE__*/ core.$constructor(\"ZodSet\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodSet.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params);\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function set(valueType, params) {\n return new ZodSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEnum = /*@__PURE__*/ core.$constructor(\"ZodEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.enumProcessor(inst, ctx, json, params);\n inst.enum = def.entries;\n // reuse the parsed value set so a numeric TS enum's reverse-mapping keys stay out\n inst.options = [...inst._zod.values];\n const keys = new Set(Object.keys(def.entries));\n inst.extract = (values, params) => {\n const newEntries = {};\n for (const value of values) {\n if (keys.has(value)) {\n newEntries[value] = def.entries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n inst.exclude = (values, params) => {\n const newEntries = { ...def.entries };\n for (const value of values) {\n if (keys.has(value)) {\n delete newEntries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n});\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLiteral = /*@__PURE__*/ core.$constructor(\"ZodLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.literalProcessor(inst, ctx, json, params);\n inst.values = new Set(def.values);\n Object.defineProperty(inst, \"value\", {\n get() {\n if (def.values.length > 1) {\n throw new Error(\"This schema contains multiple valid literal values. Use `.values` instead.\");\n }\n return def.values[0];\n },\n });\n});\nexport function literal(value, params) {\n return new ZodLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodFile = /*@__PURE__*/ core.$constructor(\"ZodFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params);\n inst.min = (size, params) => inst.check(core._minSize(size, params));\n inst.max = (size, params) => inst.check(core._maxSize(size, params));\n inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params));\n});\nexport function file(params) {\n return core._file(ZodFile, params);\n}\nexport const ZodTransform = /*@__PURE__*/ core.$constructor(\"ZodTransform\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodTransform.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.transformProcessor(inst, ctx, json, params);\n inst._zod.parse = (payload, _ctx) => {\n if (_ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n if (!(\"input\" in _issue))\n _issue.input = payload.value;\n _issue.inst ?? (_issue.inst = inst);\n // _issue.continue ??= true;\n payload.issues.push(util.issue(_issue));\n }\n };\n const output = def.transform(payload.value, payload);\n if (output instanceof Promise) {\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n payload.value = output;\n return payload;\n };\n});\nexport function transform(fn) {\n return new ZodTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodOptional = /*@__PURE__*/ core.$constructor(\"ZodOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function optional(innerType) {\n return new ZodOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodExactOptional = /*@__PURE__*/ core.$constructor(\"ZodExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function exactOptional(innerType) {\n return new ZodExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodNullable = /*@__PURE__*/ core.$constructor(\"ZodNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullableProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nullable(innerType) {\n return new ZodNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodDefault = /*@__PURE__*/ core.$constructor(\"ZodDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.defaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeDefault = inst.unwrap;\n});\nexport function _default(innerType, defaultValue) {\n return new ZodDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodPrefault = /*@__PURE__*/ core.$constructor(\"ZodPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.prefaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function prefault(innerType, defaultValue) {\n return new ZodPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodNonOptional = /*@__PURE__*/ core.$constructor(\"ZodNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nonoptionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nonoptional(innerType, params) {\n return new ZodNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSuccess = /*@__PURE__*/ core.$constructor(\"ZodSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function success(innerType) {\n return new ZodSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodCatch = /*@__PURE__*/ core.$constructor(\"ZodCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.catchProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeCatch = inst.unwrap;\n});\nfunction _catch(innerType, catchValue) {\n return new ZodCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : core.util.constantCatch(catchValue)),\n });\n}\nexport { _catch as catch };\nexport const ZodNaN = /*@__PURE__*/ core.$constructor(\"ZodNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params);\n});\nexport function nan(params) {\n return core._nan(ZodNaN, params);\n}\nexport const ZodPipe = /*@__PURE__*/ core.$constructor(\"ZodPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.pipeProcessor(inst, ctx, json, params);\n inst.in = def.in;\n inst.out = def.out;\n});\nexport function pipe(in_, out) {\n return new ZodPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n // ...util.normalizeParams(params),\n });\n}\nexport const ZodCodec = /*@__PURE__*/ core.$constructor(\"ZodCodec\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\nexport function codec(in_, out, params) {\n return new ZodCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\nexport function invertCodec(codec) {\n const def = codec._zod.def;\n return new ZodCodec({\n type: \"pipe\",\n in: def.out,\n out: def.in,\n transform: def.reverseTransform,\n reverseTransform: def.transform,\n });\n}\nexport const ZodPreprocess = /*@__PURE__*/ core.$constructor(\"ZodPreprocess\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodPreprocess.init(inst, def);\n});\nexport const ZodReadonly = /*@__PURE__*/ core.$constructor(\"ZodReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.readonlyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function readonly(innerType) {\n return new ZodReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params);\n});\nexport function templateLiteral(parts, params) {\n return new ZodTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLazy = /*@__PURE__*/ core.$constructor(\"ZodLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.lazyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.getter();\n});\nexport function lazy(getter) {\n return new ZodLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport const ZodPromise = /*@__PURE__*/ core.$constructor(\"ZodPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function promise(innerType) {\n return new ZodPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodFunction = /*@__PURE__*/ core.$constructor(\"ZodFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params);\n});\nexport function _function(params) {\n return new ZodFunction({\n type: \"function\",\n input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n output: params?.output ?? unknown(),\n });\n}\nexport { _function as function };\nexport const ZodCustom = /*@__PURE__*/ core.$constructor(\"ZodCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.customProcessor(inst, ctx, json, params);\n});\n// custom checks\nexport function check(fn) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n // ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\nexport function custom(fn, _params) {\n return core._custom(ZodCustom, fn ?? (() => true), _params);\n}\nexport function refine(fn, _params = {}) {\n return core._refine(ZodCustom, fn, _params);\n}\n// superRefine\nexport function superRefine(fn, params) {\n return core._superRefine(fn, params);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\nexport const ZodInstanceOf = /*@__PURE__*/ core.$constructor(\"ZodInstanceOf\", (inst, def) => {\n ZodCustom.init(inst, def);\n}, {\n properties(shape, params) {\n // asserts in place, so the narrowed output type is truthful without a wrapper\n return this.check(core._properties(shape, params));\n },\n});\nfunction _instanceof(cls, params = {}) {\n const inst = new ZodInstanceOf({\n type: \"custom\",\n check: \"custom\",\n fn: (data) => data instanceof cls,\n abort: true,\n ...util.normalizeParams(params),\n });\n inst._zod.bag.Class = cls;\n // Override check to emit invalid_type instead of custom\n inst._zod.check = (payload) => {\n if (!(payload.value instanceof cls)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: cls.name,\n input: payload.value,\n inst,\n path: [...(inst._zod.def.path ?? [])],\n });\n }\n };\n return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n Codec: ZodCodec,\n Boolean: ZodBoolean,\n String: ZodString,\n}, ...args);\nexport function json(params) {\n const jsonSchema = lazy(() => {\n return union([string(params), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\n// preprocess\nexport function preprocess(fn, schema) {\n return new ZodPreprocess({\n type: \"pipe\",\n in: transform(fn),\n out: schema,\n });\n}\n","import * as core from \"../core/index.js\";\nimport { ZodISODate, ZodISODateTime, ZodISODuration, ZodISOTime } from \"./schemas.js\";\nexport { ZodISODate, ZodISODateTime, ZodISODuration, ZodISOTime } from \"./schemas.js\";\nexport function datetime(params) {\n return core._isoDateTime(ZodISODateTime, params);\n}\nexport function date(params) {\n return core._isoDate(ZodISODate, params);\n}\nexport function time(params) {\n return core._isoTime(ZodISOTime, params);\n}\nexport function duration(params) {\n return core._isoDuration(ZodISODuration, params);\n}\n","unable to read source [project]/node_modules/@aeolus-fleet/common/src/fleet/index.ts","/**\n * The web app's server calling the gateway's API (header design part 5,\n * decision 0033): one tRPC client per page request, as the browser that\n * asked, by its shared sign-in forwarded, in the fleet its page names. Server\n * only: a browser never calls the API from a page.\n */\nimport { FLEET_HEADER } from '@aeolus-fleet/common';\nimport { createTRPCClient, httpLink, type TRPCClient } from '@trpc/client';\n\nimport type { GatewayRouter } from '../../../src/adapters/trpc/router.js';\n\n/** The gateway's API, as the web app's server calls it. */\nexport type GatewayApi = TRPCClient<GatewayRouter>;\n\n/** The shared account sign-in's cookie (header design H5): src/core/account-sign-in/ports.ts names the same. */\nconst SHARED_SIGN_IN_COOKIE = 'aeolus_account_session';\n\n/**\n * The browser's cookies the API is sent: the shared sign-in alone. The API\n * would take the gateway's old page session or argo's console session first,\n * as another account or fleet than the page shows.\n */\nexport function forwardedCookieOf(header: string | undefined): string | undefined {\n const prefix = `${SHARED_SIGN_IN_COOKIE}=`;\n const signIn = header\n ?.split(';')\n .map((part) => part.trim())\n .find((part) => part.startsWith(prefix) && part.length > prefix.length);\n return signIn;\n}\n\n/** The header the waiting page sends its browser's secret in, so it never travels in an address (src/adapters/trpc/router.ts names the same). */\nconst WAITING_SECRET_HEADER = 'aeolus-waiting-secret';\n\n/** What a call of the API is sent besides its input: the shared sign-in, the fleet the page names, and the waiting page's browser secret. */\nexport interface ApiSent {\n cookie: string | undefined;\n fleetId: string | undefined;\n waitingSecret?: string;\n}\n\nexport function apiHeadersOf(sent: ApiSent): Record<string, string> {\n const cookie = forwardedCookieOf(sent.cookie);\n return {\n ...(cookie === undefined ? {} : { cookie }),\n ...(sent.fleetId === undefined ? {} : { [FLEET_HEADER]: sent.fleetId }),\n ...(sent.waitingSecret === undefined ? {} : { [WAITING_SECRET_HEADER]: sent.waitingSecret }),\n };\n}\n\nexport function gatewayApi(sent: ApiSent & { url: string }): GatewayApi {\n return createTRPCClient<GatewayRouter>({ links: [httpLink({ url: `${sent.url}/trpc`, headers: apiHeadersOf(sent) })] });\n}\n","/**\n * What a page of the web app does with the API's account.inView (header\n * design H5, H9): show its fleet as the account signed in, or send the\n * browser where it may go: the same page in the fleet the account may open,\n * the app it may open there, or sign-in and back to the page.\n */\n\n/** The API's answer to account.inView. */\nexport type InView =\n | { kind: 'signedIn'; fleetId: string; accountId: string; scopes: string[] }\n | { kind: 'goTo'; fleetId: string }\n | { kind: 'elsewhere'; url: string };\n\n/** The API's refusals of account.inView a page answers: signed in to no account, and no shared sign-in at this gateway. */\nexport type InViewRefusal = 'UNAUTHORIZED' | 'NOT_FOUND';\n\nexport type PageAccount = { kind: 'signedIn'; fleetId: string; scopes: readonly string[] } | { kind: 'goTo'; location: string } | { kind: 'noSignIn' };\n\nconst SIGN_IN_START = '/sign-in/start';\n\n/** The parameter a page names its fleet by. */\nexport const FLEET_PARAMETER = 'fleet';\n\n/** A page of the web app in a fleet: every link keeps the fleet in its address. */\nexport function inFleet(page: string, fleetId: string): string {\n const [path = '', query = ''] = page.split('?');\n const parameters = new URLSearchParams(query);\n parameters.set(FLEET_PARAMETER, fleetId);\n return `${path}?${parameters.toString()}`;\n}\n\n/** Reads the answer for the page asked for, its path and query as the browser sent them. */\nexport function pageAccountOf(read: { inView: InView } | { refusal: InViewRefusal }, page: string): PageAccount {\n if ('refusal' in read) {\n return read.refusal === 'UNAUTHORIZED' ? { kind: 'goTo', location: `${SIGN_IN_START}?${new URLSearchParams({ return_to: page }).toString()}` } : { kind: 'noSignIn' };\n }\n const { inView } = read;\n switch (inView.kind) {\n case 'signedIn':\n return { kind: 'signedIn', fleetId: inView.fleetId, scopes: inView.scopes };\n case 'goTo':\n return { kind: 'goTo', location: inFleet(page, inView.fleetId) };\n case 'elsewhere':\n return { kind: 'goTo', location: inView.url };\n }\n}\n","/**\n * The gateway's API for a page of the web app and for its forms (server\n * actions): as the browser that asked, by its cookies, at the address the\n * gateway's server gave the web app, never one a request names.\n */\nimport { TRPCClientError } from '@trpc/client';\nimport { headers } from 'next/headers';\nimport { redirect } from 'next/navigation';\n\nimport type { GatewayRouter } from '../../../src/adapters/trpc/router.js';\nimport { gatewayApi, type GatewayApi } from './gateway-api';\nimport { FLEET_PARAMETER, pageAccountOf, type InView, type InViewRefusal } from './page-account';\n\n/** Set by the gateway's server as it starts the web app (src/adapters/web/next-web-app.ts). */\nconst API_URL_VARIABLE = 'AEOLUS_GATEWAY_API_URL';\n\n/** A page's search parameters, as Next.js hands them over. */\nexport type SearchParams = Record<string, string | string[] | undefined>;\n\n/** A page shown as the account signed in: the API as it, its fleet and its scopes there. */\nexport interface SignedInPage {\n kind: 'signedIn';\n api: GatewayApi;\n fleetId: string;\n scopes: readonly string[];\n}\n\n/** The gateway's own address, where the API answers. */\nexport function apiUrl(): string {\n const url = process.env[API_URL_VARIABLE];\n if (url === undefined) {\n throw new Error(`${API_URL_VARIABLE} is not set: the gateway's server starts the web app`);\n }\n return url;\n}\n\n/** The API as the browser that asked, in the fleet named. */\nexport async function requestApi(fleetId: string | undefined): Promise<GatewayApi> {\n return gatewayApi({ url: apiUrl(), cookie: (await headers()).get('cookie') ?? undefined, fleetId });\n}\n\nfunction isApiRefusal(error: unknown): error is TRPCClientError<GatewayRouter> {\n return error instanceof TRPCClientError;\n}\n\n/** The code the API refused a call with, if it refused it. */\nexport function refusalCodeOf(error: unknown): string | undefined {\n return isApiRefusal(error) ? error.data?.code : undefined;\n}\n\n/** Why the API refused a call, as it says it; anything else is no refusal and is thrown on. */\nexport function refusalMessageOf(error: unknown): string {\n if (!isApiRefusal(error)) {\n throw error;\n }\n return error.message;\n}\n\nfunction isInViewRefusal(code: string | undefined): code is InViewRefusal {\n return code === 'UNAUTHORIZED' || code === 'NOT_FOUND';\n}\n\n/**\n * The page as the account signed in, in the fleet its address names; or\n * the browser is sent where it may go. A gateway that signs no one in to\n * its pages answers noSignIn.\n */\nexport async function signedInPage(page: { path: string; searchParams: SearchParams }): Promise<SignedInPage | { kind: 'noSignIn' }> {\n const query = new URLSearchParams();\n for (const [name, value] of Object.entries(page.searchParams)) {\n if (typeof value === 'string') {\n query.set(name, value);\n }\n }\n const fleet = query.get(FLEET_PARAMETER) ?? undefined;\n const asked = query.size === 0 ? page.path : `${page.path}?${query.toString()}`;\n const api = await requestApi(fleet);\n let read: { inView: InView } | { refusal: InViewRefusal };\n try {\n read = { inView: await api.account.inView.query() };\n } catch (error) {\n const code = refusalCodeOf(error);\n if (!isInViewRefusal(code)) {\n throw error;\n }\n read = { refusal: code };\n }\n const account = pageAccountOf(read, asked);\n switch (account.kind) {\n case 'goTo':\n return redirect(account.location);\n case 'noSignIn':\n return account;\n case 'signedIn':\n return { kind: 'signedIn', api, fleetId: account.fleetId, scopes: account.scopes };\n }\n}\n\n/** What a page reads from the API, or why the API refused it, for the page to say in its place. */\nexport type Read<T> = { isOk: true; value: T } | { isOk: false; refusal: string };\n\nexport async function readOf<T>(call: Promise<T>): Promise<Read<T>> {\n try {\n return { isOk: true, value: await call };\n } catch (error) {\n return { isOk: false, refusal: refusalMessageOf(error) };\n }\n}\n"],"names":["isObservable","x","teardownRef","subscribe","isDone","_observer$complete","teardownImmediately","unsubscribe","observable","AbortController","onDone","ac","signal","addEventListener","data","complete","isObject","msg","forbidden","DIGEST","HTTP_ERROR_FALLBACK_ERROR_CODE","process","env","__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS","Error","error","digest","HTTPAccessErrorStatus","getAccessFallbackErrorTypeByStatus","getAccessFallbackHTTPStatus","isHTTPAccessFallbackError","NOT_FOUND","FORBIDDEN","UNAUTHORIZED","ALLOWED_CODES","Set","Object","values","prefix","httpStatus","split","has","Number","status","isNextRouterError","isRedirectError","ReadonlyURLSearchParams","RedirectType","notFound","permanentRedirect","redirect","unauthorized","unstable_isUnrecognizedActionError","unstable_rethrow","push","replace","ReadonlyURLSearchParamsError","constructor","URLSearchParams","append","delete","set","sort","REDIRECT_ERROR_CODE","errorCode","type","destination","slice","join","at","statusCode","isNaN","RedirectStatusCode","getRedirectError","getRedirectStatusCodeFromError","getRedirectTypeFromError","getURLFromRedirectError","url","TemporaryRedirect","actionAsyncStorage","getStore","isAction","PermanentRedirect","workAsyncStorage","workUnitAsyncStorage","isBailoutToCSRError","isDynamicServerError","isHangingPromiseRejectionError","isPrerenderInterruptedError","cause","BailoutToCSRError","BAILOUT_TO_CSR","reason","err","assertEqual","val","assertNotEqual","toZod","schema","assertIs","_arg","assertNever","_x","assert","_","getEnumValues","entries","numericValues","filter","v","k","indexOf","map","joinValues","array","separator","stringifyPrimitive","jsonStringifyReplacer","value","toString","Cached","getter","_getter","_value","undefined","cached","nullish","input","cleanRegex","source","start","startsWith","end","endsWith","length","floatSafeRemainder","step","ratio","roundedRatio","Math","round","tolerance","EPSILON","max","abs","EVALUATING","Symbol","defineLazy","object","key","defineProperty","get","configurable","objectClone","obj","create","getPrototypeOf","getOwnPropertyDescriptors","assignProp","target","prop","writable","enumerable","rawShape","def","desc","getOwnPropertyDescriptor","raw","sourceShape","_zod","shape","deferProp","putProp","mirrorShape","keys","wrap","mirrorProps","Reflect","ownKeys","mergeDefs","defs","mergedDescriptors","descriptors","assign","defineProperties","cloneDef","getElementAtPath","path","reduce","acc","promiseAllObject","promisesObj","promises","Promise","all","then","results","resolvedObj","i","randomString","chars","str","floor","random","esc","JSON","stringify","slugify","toLowerCase","trim","captureStackTrace","_args","Array","isArray","allowsEval","globalConfig","jitless","navigator","userAgent","includes","F","Function","isPlainObject","o","ctor","prot","prototype","hasOwnProperty","call","shallowClone","Map","numKeys","keyCount","getParsedType","t","catch","Date","File","propertyKeyTypes","primitiveTypes","escapeRegex","clone","inst","params","cl","constr","parent","normalizeParams","_params","message","createTransparentProxy","Proxy","receiver","deleteProperty","descriptor","optionalKeys","optin","optout","NUMBER_FORMAT_RANGES","safeint","MIN_SAFE_INTEGER","MAX_SAFE_INTEGER","int32","uint32","float32","float64","MAX_VALUE","BIGINT_FORMAT_RANGES","int64","BigInt","uint64","pick","mask","currDef","checks","hasChecks","newShape","maskedKeys","String","omit","omitted","extend","existingShape","extended","safeExtend","merge","a","b","catchall","partial","Class","name","selected","innerType","required","aborted","startIndex","issues","continue","explicitlyAborted","prefixIssues","iss","_a","unshift","unwrapMessage","sizeCaps","defChecks","caps","ch","d","test","check","maximum","size","attachSchema","finalizeIssue","ctx","config","traits","schemaError","customError","localeError","full","reportInput","getSizableOrigin","highSurrogate","codePointLength","units","count","charCodeAt","getLengthableOrigin","parsedType","issue","args","code","cleanEnum","parseInt","el","base64ToUint8Array","base64","binaryString","atob","bytes","Uint8Array","uint8ArrayToBase64","fromCharCode","btoa","base64urlToUint8Array","base64url","padding","repeat","uint8ArrayToBase64url","hexToUint8Array","hex","cleanHex","uint8ArrayToHex","from","padStart","members","proto","table","defineBound","own","hide","derived","computes","compute","fn","bind","claim","sentinel","installing","broke","breaker","defineLazyInternal","outer","installLazyProp","make","CONSTANT_CATCH","constantCatch","SIGN_IN_START","FLEET_PARAMETER","inFleet","page","fleetId","query","parameters","pageAccountOf","read","refusal","kind","location","return_to","inView","scopes","API_URL_VARIABLE","apiUrl","requestApi","cookie","isApiRefusal","refusalCodeOf","refusalMessageOf","isInViewRefusal","signedInPage","searchParams","fleet","asked","api","account","readOf","isOk"],"mappings":"6CASG,IAAA,EAAA,EAAA,CAAA,CAAA,OACH,EAAwB,CAAjB,CAAiB,CAAA,AAAf,CAAe,AAAd,EAAE,KAEL,CAFW,GAEL,EAFU,AAEI,CAFH,AAGtB,KAAK,CAAE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AAO,CACd,MAAO,CAAEiY,MAAM,EAAOrB,QAASY,EAAiBxX,EAAO,CACzD,CACF","ignoreList":[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93]}
1
+ {"version":3,"sources":["../../../../../node_modules/%40aeolus-fleet/common/src/ids/index.ts","../../../../../node_modules/%40aeolus-fleet/common/src/schemas/account-token.ts","../../../../../node_modules/%40trpc/client/dist/objectSpread2-weooBxVk.mjs","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/createProxy.ts","../../../../../node_modules/%40trpc/server/src/observable/observable.ts","../../../../../node_modules/%40trpc/server/src/observable/operators.ts","../../../../../node_modules/%40trpc/client/src/getFetch.ts","../../../../../node_modules/%40trpc/client/src/links/internals/createChain.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/error/formatter.ts","../../../../../node_modules/%40trpc/client/src/links/loggerLink.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/http/parseConnectionParams.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/utils.ts","../../../../../node_modules/%40trpc/client/src/links/wsLink/wsClient/encoder.ts","../../../../../node_modules/%40trpc/client/src/TRPCClientError.ts","../../../../../node_modules/%40trpc/client/src/links/internals/contentTypes.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/error/TRPCError.ts","../../../../../node_modules/%40trpc/client/src/internals/dataLoader.ts","../../../../../node_modules/%40trpc/client/src/internals/transformer.ts","../../../../../node_modules/%40trpc/client/src/internals/TRPCUntypedClient.ts","../../../../../node_modules/%40trpc/client/src/links/wsLink/wsClient/options.ts","../../../../../node_modules/%40trpc/client/src/links/httpLink.ts","../../../../../node_modules/%40trpc/client/src/internals/signals.ts","../../../../../node_modules/%40trpc/client/src/links/splitLink.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/http/contentType.ts","../../../../../node_modules/%40trpc/client/src/links/internals/urlWithConnectionParams.ts","../../../../../node_modules/%40trpc/client/src/links/wsLink/wsClient/utils.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/transformer.ts","../../../../../node_modules/%40trpc/client/src/links/internals/httpUtils.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/http/getHTTPStatusCode.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/rpc/codes.ts","../../../../../node_modules/%40trpc/client/src/createTRPCUntypedClient.ts","../../../../../node_modules/%40trpc/client/src/createTRPCClient.ts","../../../../../node_modules/%40trpc/client/src/links/wsLink/wsClient/requestManager.ts","../../../../../node_modules/%40trpc/client/src/links/httpBatchLink.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/router.ts","../../../../../node_modules/%40trpc/server/src/observable/behaviorSubject.ts","../../../../../node_modules/%40trpc/client/src/links/httpBatchStreamLink.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/error/getErrorShape.ts","../../../../../node_modules/%40trpc/client/src/links/wsLink/wsClient/wsConnection.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/http/abortError.ts","../../../../../node_modules/%40trpc/server/src/vendor/is-plain-object.ts","../../../../../node_modules/%40trpc/client/src/internals/inputWithTrackedEventId.ts","../../../../../node_modules/%40trpc/server/src/vendor/unpromise/unpromise.ts","../../../../../node_modules/%40trpc/client/src/links/httpSubscriptionLink.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/stream/tracked.ts","../../../../../node_modules/%40trpc/client/src/links/wsLink/wsClient/wsClient.ts","../../../../../node_modules/%40trpc/client/src/links/retryLink.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/stream/utils/disposable.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/stream/utils/timerResource.ts","../../../../../node_modules/%40trpc/client/src/links/wsLink/createWsClient.ts","../../../../../node_modules/%40trpc/client/src/links/wsLink/wsLink.ts","../../../../../node_modules/%40trpc/client/src/links/localLink.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/stream/utils/asyncIterable.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/stream/utils/createDeferred.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/stream/utils/mergeAsyncIterables.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/stream/utils/readableStreamFrom.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/stream/utils/withPing.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/stream/jsonl.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/stream/sse.ts","../../../../../node_modules/%40trpc/server/src/unstable-core-do-not-import/http/resolveResponse.ts","../../../../../node_modules/src/api/navigation.react-server.ts","../../../../../node_modules/next/src/client/components/forbidden.ts","../../../../../node_modules/next/src/client/components/http-access-fallback/http-access-fallback.ts","../../../../../node_modules/next/src/client/components/is-next-router-error.ts","../../../../../node_modules/next/src/client/components/navigation.react-server.ts","../../../../../node_modules/next/src/client/components/not-found.ts","../../../../../node_modules/next/src/client/components/readonly-url-search-params.ts","../../../../../node_modules/next/src/client/components/redirect-error.ts","../../../../../node_modules/next/src/client/components/redirect-status-code.ts","../../../../../node_modules/next/src/client/components/redirect.ts","../../../../../node_modules/next/src/client/components/server-async-storage.ts","../../../../../node_modules/next/src/client/components/unauthorized.ts","../../../../../node_modules/next/src/client/components/unstable-rethrow.ts","../../../../../node_modules/next/src/shared/lib/lazy-dynamic/bailout-to-csr.ts","../../../../../node_modules/zod/v4/core/util.js","../../../../../node_modules/zod/v4/core/core.js","../../../../../node_modules/zod/v4/core/memoizer.js","../../../../../node_modules/zod/v4/core/registries.js","../../../../../node_modules/zod/v4/core/regexes.js","../../../../../node_modules/zod/v4/core/checks.js","../../../../../node_modules/zod/v4/core/doc.js","../../../../../node_modules/zod/v4/core/errors.js","../../../../../node_modules/zod/v4/core/parse.js","../../../../../node_modules/zod/v4/core/versions.js","../../../../../node_modules/zod/v4/core/schemas.js","../../../../../node_modules/zod/v4/core/api.js","../../../../../node_modules/zod/v4/core/to-json-schema.js","../../../../../node_modules/zod/v4/core/json-schema-processors.js","../../../../../node_modules/zod/v4/locales/en.js","../../../../../node_modules/zod/v4/classic/errors.js","../../../../../node_modules/zod/v4/classic/parse.js","../../../../../node_modules/zod/v4/classic/schemas.js","../../../../../node_modules/zod/v4/classic/iso.js","../../../../../node_modules/%40aeolus-fleet/common/src/fleet/index.ts","../../../../../web/lib/gateway-api/gateway-api.ts","../../../../../web/lib/gateway-api/page-account.ts","../../../../../web/lib/gateway-api/page-api.ts"],"sourcesContent":["unable to read source [project]/node_modules/@aeolus-fleet/common/src/ids/index.ts","unable to read source [project]/node_modules/@aeolus-fleet/common/src/schemas/account-token.ts","//#region \\0@oxc-project+runtime@0.149.0/helpers/esm/typeof.js\nfunction _typeof(o) {\n\t\"@babel/helpers - typeof\";\n\treturn _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function(o) {\n\t\treturn typeof o;\n\t} : function(o) {\n\t\treturn o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n\t}, _typeof(o);\n}\n//#endregion\n//#region \\0@oxc-project+runtime@0.149.0/helpers/esm/toPrimitive.js\nfunction toPrimitive(t, r) {\n\tif (\"object\" != _typeof(t) || !t) return t;\n\tvar e = t[Symbol.toPrimitive];\n\tif (void 0 !== e) {\n\t\tvar i = e.call(t, r || \"default\");\n\t\tif (\"object\" != _typeof(i)) return i;\n\t\tthrow new TypeError(\"@@toPrimitive must return a primitive value.\");\n\t}\n\treturn (\"string\" === r ? String : Number)(t);\n}\n//#endregion\n//#region \\0@oxc-project+runtime@0.149.0/helpers/esm/toPropertyKey.js\nfunction toPropertyKey(t) {\n\tvar i = toPrimitive(t, \"string\");\n\treturn \"symbol\" == _typeof(i) ? i : i + \"\";\n}\n//#endregion\n//#region \\0@oxc-project+runtime@0.149.0/helpers/esm/defineProperty.js\nfunction _defineProperty(e, r, t) {\n\treturn (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n\t\tvalue: t,\n\t\tenumerable: !0,\n\t\tconfigurable: !0,\n\t\twritable: !0\n\t}) : e[r] = t, e;\n}\n//#endregion\n//#region \\0@oxc-project+runtime@0.149.0/helpers/esm/objectSpread2.js\nfunction ownKeys(e, r) {\n\tvar t = Object.keys(e);\n\tif (Object.getOwnPropertySymbols) {\n\t\tvar o = Object.getOwnPropertySymbols(e);\n\t\tr && (o = o.filter(function(r) {\n\t\t\treturn Object.getOwnPropertyDescriptor(e, r).enumerable;\n\t\t})), t.push.apply(t, o);\n\t}\n\treturn t;\n}\nfunction _objectSpread2(e) {\n\tfor (var r = 1; r < arguments.length; r++) {\n\t\tvar t = null != arguments[r] ? arguments[r] : {};\n\t\tr % 2 ? ownKeys(Object(t), !0).forEach(function(r) {\n\t\t\t_defineProperty(e, r, t[r]);\n\t\t}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r) {\n\t\t\tObject.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));\n\t\t});\n\t}\n\treturn e;\n}\n//#endregion\nexport { _defineProperty as n, _objectSpread2 as t };\n","import { emptyObject } from './utils';\n\ninterface ProxyCallbackOptions {\n path: readonly string[];\n args: readonly unknown[];\n}\ntype ProxyCallback = (opts: ProxyCallbackOptions) => unknown;\n\nconst noop = () => {\n // noop\n};\n\nconst freezeIfAvailable = (obj: object) => {\n if (Object.freeze) {\n Object.freeze(obj);\n }\n};\n\nfunction createInnerProxy(\n callback: ProxyCallback,\n path: readonly string[],\n memo: Record<string, unknown>,\n) {\n const cacheKey = path.join('.');\n\n memo[cacheKey] ??= new Proxy(noop, {\n get(_obj, key) {\n if (typeof key !== 'string' || key === 'then') {\n // special case for if the proxy is accidentally treated\n // like a PromiseLike (like in `Promise.resolve(proxy)`)\n return undefined;\n }\n return createInnerProxy(callback, [...path, key], memo);\n },\n apply(_1, _2, args) {\n const lastOfPath = path[path.length - 1];\n\n // React 19 may call valueOf / toString / toJSON when coercing a proxy\n // to a primitive (e.g. during rendering or logging). Return a debug\n // string so the coercion does not recurse into the proxy. This only\n // triggers for direct calls (proxy.toString()), not for chained access\n // (proxy.toString.query()), preserving route naming freedom.\n if (\n lastOfPath === 'valueOf' ||\n lastOfPath === 'toString' ||\n lastOfPath === 'toJSON'\n ) {\n const debugPath = path.slice(0, -1).join('.');\n return `tRPC.proxy(${debugPath})`;\n }\n\n let opts = { args, path };\n // special handling for e.g. `trpc.hello.call(this, 'there')` and `trpc.hello.apply(this, ['there'])\n if (lastOfPath === 'call') {\n opts = {\n args: args.length >= 2 ? [args[1]] : [],\n path: path.slice(0, -1),\n };\n } else if (lastOfPath === 'apply') {\n opts = {\n args: args.length >= 2 ? args[1] : [],\n path: path.slice(0, -1),\n };\n }\n freezeIfAvailable(opts.args);\n freezeIfAvailable(opts.path);\n return callback(opts);\n },\n });\n\n return memo[cacheKey];\n}\n\n/**\n * Creates a proxy that calls the callback with the path and arguments\n *\n * @internal\n */\nexport const createRecursiveProxy = <TFaux = unknown>(\n callback: ProxyCallback,\n): TFaux => createInnerProxy(callback, [], emptyObject()) as TFaux;\n\n/**\n * Used in place of `new Proxy` where each handler will map 1 level deep to another value.\n *\n * @internal\n */\nexport const createFlatProxy = <TFaux>(\n callback: (path: keyof TFaux) => any,\n): TFaux => {\n return new Proxy(noop, {\n get(_obj, name) {\n if (name === 'then') {\n // special case for if the proxy is accidentally treated\n // like a PromiseLike (like in `Promise.resolve(proxy)`)\n return undefined;\n }\n return callback(name as any);\n },\n }) as TFaux;\n};\n","import type { Result } from '../unstable-core-do-not-import';\nimport type {\n Observable,\n Observer,\n OperatorFunction,\n TeardownLogic,\n UnaryFunction,\n Unsubscribable,\n} from './types';\n\n/** @public */\nexport type inferObservableValue<TObservable> =\n TObservable extends Observable<infer TValue, unknown> ? TValue : never;\n\n/** @public */\nexport function isObservable(x: unknown): x is Observable<unknown, unknown> {\n return typeof x === 'object' && x !== null && 'subscribe' in x;\n}\n\n/** @public */\nexport function observable<TValue, TError = unknown>(\n subscribe: (observer: Observer<TValue, TError>) => TeardownLogic,\n): Observable<TValue, TError> {\n const self: Observable<TValue, TError> = {\n subscribe(observer) {\n let teardownRef: TeardownLogic | null = null;\n let isDone = false;\n let unsubscribed = false;\n let teardownImmediately = false;\n function unsubscribe() {\n if (teardownRef === null) {\n teardownImmediately = true;\n return;\n }\n if (unsubscribed) {\n return;\n }\n unsubscribed = true;\n\n if (typeof teardownRef === 'function') {\n teardownRef();\n } else if (teardownRef) {\n teardownRef.unsubscribe();\n }\n }\n teardownRef = subscribe({\n next(value) {\n if (isDone) {\n return;\n }\n observer.next?.(value);\n },\n error(err) {\n if (isDone) {\n return;\n }\n isDone = true;\n observer.error?.(err);\n unsubscribe();\n },\n complete() {\n if (isDone) {\n return;\n }\n isDone = true;\n observer.complete?.();\n unsubscribe();\n },\n });\n if (teardownImmediately) {\n unsubscribe();\n }\n return {\n unsubscribe,\n };\n },\n pipe(\n ...operations: OperatorFunction<any, any, any, any>[]\n ): Observable<any, any> {\n return operations.reduce(pipeReducer, self);\n },\n };\n return self;\n}\n\nfunction pipeReducer(prev: any, fn: UnaryFunction<any, any>) {\n return fn(prev);\n}\n\n/** @internal */\nexport function observableToPromise<TValue>(\n observable: Observable<TValue, unknown>,\n) {\n const ac = new AbortController();\n const promise = new Promise<TValue>((resolve, reject) => {\n let isDone = false;\n function onDone() {\n if (isDone) {\n return;\n }\n isDone = true;\n obs$.unsubscribe();\n }\n ac.signal.addEventListener('abort', () => {\n reject(ac.signal.reason);\n });\n const obs$ = observable.subscribe({\n next(data) {\n isDone = true;\n resolve(data);\n onDone();\n },\n error(data) {\n reject(data);\n },\n complete() {\n ac.abort();\n onDone();\n },\n });\n });\n return promise;\n}\n\n/**\n * @internal\n */\nfunction observableToReadableStream<TValue>(\n observable: Observable<TValue, unknown>,\n signal: AbortSignal,\n): ReadableStream<Result<TValue>> {\n let unsub: Unsubscribable | null = null;\n\n const onAbort = () => {\n unsub?.unsubscribe();\n unsub = null;\n signal.removeEventListener('abort', onAbort);\n };\n\n return new ReadableStream<Result<TValue>>({\n start(controller) {\n unsub = observable.subscribe({\n next(data) {\n controller.enqueue({ ok: true, value: data });\n },\n error(error) {\n controller.enqueue({ ok: false, error });\n controller.close();\n },\n complete() {\n controller.close();\n },\n });\n\n if (signal.aborted) {\n onAbort();\n } else {\n signal.addEventListener('abort', onAbort, { once: true });\n }\n },\n cancel() {\n onAbort();\n },\n });\n}\n\n/** @internal */\nexport function observableToAsyncIterable<TValue>(\n observable: Observable<TValue, unknown>,\n signal: AbortSignal,\n): AsyncIterable<TValue> {\n const stream = observableToReadableStream(observable, signal);\n\n const reader = stream.getReader();\n const iterator: AsyncIterator<TValue> = {\n async next() {\n const value = await reader.read();\n if (value.done) {\n return {\n value: undefined,\n done: true,\n };\n }\n const { value: result } = value;\n if (!result.ok) {\n throw result.error;\n }\n return {\n value: result.value,\n done: false,\n };\n },\n async return() {\n await reader.cancel();\n return {\n value: undefined,\n done: true,\n };\n },\n };\n return {\n [Symbol.asyncIterator]() {\n return iterator;\n },\n };\n}\n","import { observable } from './observable';\nimport type {\n MonoTypeOperatorFunction,\n Observer,\n OperatorFunction,\n Unsubscribable,\n} from './types';\n\nexport function map<TValueBefore, TError, TValueAfter>(\n project: (value: TValueBefore, index: number) => TValueAfter,\n): OperatorFunction<TValueBefore, TError, TValueAfter, TError> {\n return (source) => {\n return observable((destination) => {\n let index = 0;\n const subscription = source.subscribe({\n next(value) {\n destination.next(project(value, index++));\n },\n error(error) {\n destination.error(error);\n },\n complete() {\n destination.complete();\n },\n });\n return subscription;\n });\n };\n}\n\ninterface ShareConfig {}\nexport function share<TValue, TError>(\n _opts?: ShareConfig,\n): MonoTypeOperatorFunction<TValue, TError> {\n return (source) => {\n let refCount = 0;\n\n let subscription: Unsubscribable | null = null;\n const observers: Partial<Observer<TValue, TError>>[] = [];\n\n function startIfNeeded() {\n if (subscription) {\n return;\n }\n subscription = source.subscribe({\n next(value) {\n for (const observer of observers) {\n observer.next?.(value);\n }\n },\n error(error) {\n for (const observer of observers) {\n observer.error?.(error);\n }\n },\n complete() {\n for (const observer of observers) {\n observer.complete?.();\n }\n },\n });\n }\n function resetIfNeeded() {\n // \"resetOnRefCountZero\"\n if (refCount === 0 && subscription) {\n const _sub = subscription;\n subscription = null;\n _sub.unsubscribe();\n }\n }\n\n return observable((subscriber) => {\n refCount++;\n\n observers.push(subscriber);\n startIfNeeded();\n return {\n unsubscribe() {\n refCount--;\n resetIfNeeded();\n\n const index = observers.findIndex((v) => v === subscriber);\n\n if (index > -1) {\n observers.splice(index, 1);\n }\n },\n };\n });\n };\n}\n\nexport function tap<TValue, TError>(\n observer: Partial<Observer<TValue, TError>>,\n): MonoTypeOperatorFunction<TValue, TError> {\n return (source) => {\n return observable((destination) => {\n return source.subscribe({\n next(value) {\n observer.next?.(value);\n destination.next(value);\n },\n error(error) {\n observer.error?.(error);\n destination.error(error);\n },\n complete() {\n observer.complete?.();\n destination.complete();\n },\n });\n });\n };\n}\n\nconst distinctUnsetMarker = Symbol();\nexport function distinctUntilChanged<TValue, TError>(\n compare: (a: TValue, b: TValue) => boolean = (a, b) => a === b,\n): MonoTypeOperatorFunction<TValue, TError> {\n return (source) => {\n return observable((destination) => {\n let lastValue: TValue | typeof distinctUnsetMarker = distinctUnsetMarker;\n\n return source.subscribe({\n next(value) {\n if (lastValue !== distinctUnsetMarker && compare(lastValue, value)) {\n return;\n }\n lastValue = value;\n destination.next(value);\n },\n error(error) {\n destination.error(error);\n },\n complete() {\n destination.complete();\n },\n });\n });\n };\n}\n\nconst isDeepEqual = <T>(a: T, b: T): boolean => {\n if (a === b) {\n return true;\n }\n const bothAreObjects =\n a && b && typeof a === 'object' && typeof b === 'object';\n\n return (\n !!bothAreObjects &&\n Object.keys(a).length === Object.keys(b).length &&\n Object.entries(a).every(([k, v]) => isDeepEqual(v, b[k as keyof T]))\n );\n};\nexport function distinctUntilDeepChanged<\n TValue,\n TError,\n>(): MonoTypeOperatorFunction<TValue, TError> {\n return distinctUntilChanged(isDeepEqual);\n}\n","import type { FetchEsque, NativeFetchEsque } from './internals/types';\n\ntype AnyFn = (...args: any[]) => unknown;\n\nconst isFunction = (fn: unknown): fn is AnyFn => typeof fn === 'function';\n\nexport function getFetch(\n customFetchImpl?: FetchEsque | NativeFetchEsque,\n): FetchEsque {\n if (customFetchImpl) {\n return customFetchImpl as FetchEsque;\n }\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (typeof window !== 'undefined' && isFunction(window.fetch)) {\n return window.fetch.bind(window);\n }\n\n if (typeof globalThis !== 'undefined' && isFunction(globalThis.fetch)) {\n return globalThis.fetch;\n }\n\n throw new Error('No fetch implementation found');\n}\n","import { observable } from '@trpc/server/observable';\nimport type { AnyRouter } from '@trpc/server/unstable-core-do-not-import';\nimport type {\n Operation,\n OperationLink,\n OperationResultObservable,\n} from '../types';\n\n/** @internal */\nexport function createChain<\n TRouter extends AnyRouter,\n TInput = unknown,\n TOutput = unknown,\n>(opts: {\n links: OperationLink<TRouter, TInput, TOutput>[];\n op: Operation<TInput>;\n}): OperationResultObservable<TRouter, TOutput> {\n return observable((observer) => {\n function execute(index = 0, op = opts.op) {\n const next = opts.links[index];\n if (!next) {\n throw new Error(\n 'No more links to execute - did you forget to add an ending link?',\n );\n }\n const subscription = next({\n op,\n next(nextOp) {\n const nextObserver = execute(index + 1, nextOp);\n\n return nextObserver;\n },\n });\n return subscription;\n }\n\n const obs$ = execute();\n return obs$.subscribe(observer);\n });\n}\n","import type { ProcedureType } from '../procedure';\nimport type {\n TRPC_ERROR_CODE_KEY,\n TRPC_ERROR_CODE_NUMBER,\n TRPCErrorShape,\n} from '../rpc';\nimport type { TRPCError } from './TRPCError';\n\n/**\n * @internal\n */\nexport type ErrorFormatter<TContext, TShape extends TRPCErrorShape> = (opts: {\n error: TRPCError;\n type: ProcedureType | 'unknown';\n path: string | undefined;\n input: unknown;\n ctx: TContext | undefined;\n shape: DefaultErrorShape;\n}) => TShape;\n\n/**\n * @internal\n */\nexport type DefaultErrorData = {\n code: TRPC_ERROR_CODE_KEY;\n httpStatus: number;\n /**\n * Path to the procedure that threw the error\n */\n path?: string;\n /**\n * Stack trace of the error (only in development)\n */\n stack?: string;\n};\n\n/**\n * @internal\n */\nexport interface DefaultErrorShape extends TRPCErrorShape<DefaultErrorData> {\n message: string;\n code: TRPC_ERROR_CODE_NUMBER;\n}\n\nexport const defaultFormatter: ErrorFormatter<any, any> = ({ shape }) => {\n return shape;\n};\n","/// <reference lib=\"dom.iterable\" />\n\n// `dom.iterable` types are explicitly required for extracting `FormData` values,\n// as all implementations of `Symbol.iterable` are separated from the main `dom` types.\n// Using triple-slash directive makes sure that it will be available,\n// even if end-user `tsconfig.json` omits it in the `lib` array.\n\nimport { observable, tap } from '@trpc/server/observable';\nimport type {\n AnyRouter,\n InferrableClientTypes,\n} from '@trpc/server/unstable-core-do-not-import';\nimport type { TRPCClientError } from '../TRPCClientError';\nimport type { Operation, OperationResultEnvelope, TRPCLink } from './types';\n\ntype ConsoleEsque = {\n log: (...args: any[]) => void;\n error: (...args: any[]) => void;\n};\n\ntype EnableFnOptions<TRouter extends InferrableClientTypes> =\n | {\n direction: 'down';\n result:\n | OperationResultEnvelope<unknown, TRPCClientError<TRouter>>\n | TRPCClientError<TRouter>;\n }\n | (Operation & {\n direction: 'up';\n });\ntype EnabledFn<TRouter extends AnyRouter> = (\n opts: EnableFnOptions<TRouter>,\n) => boolean;\n\ntype LoggerLinkFnOptions<TRouter extends AnyRouter> = Operation &\n (\n | {\n /**\n * Request result\n */\n direction: 'down';\n result:\n | OperationResultEnvelope<unknown, TRPCClientError<TRouter>>\n | TRPCClientError<TRouter>;\n elapsedMs: number;\n }\n | {\n /**\n * Request was just initialized\n */\n direction: 'up';\n }\n );\n\ntype LoggerLinkFn<TRouter extends AnyRouter> = (\n opts: LoggerLinkFnOptions<TRouter>,\n) => void;\n\ntype ColorMode = 'ansi' | 'css' | 'none';\n\nexport interface LoggerLinkOptions<TRouter extends AnyRouter> {\n logger?: LoggerLinkFn<TRouter>;\n enabled?: EnabledFn<TRouter>;\n /**\n * Used in the built-in defaultLogger\n */\n console?: ConsoleEsque;\n /**\n * Color mode\n * @default typeof window === 'undefined' ? 'ansi' : 'css'\n */\n colorMode?: ColorMode;\n\n /**\n * Include context in the log - defaults to false unless `colorMode` is 'css'\n */\n withContext?: boolean;\n}\n\nfunction isFormData(value: unknown): value is FormData {\n if (typeof FormData === 'undefined') {\n // FormData is not supported\n return false;\n }\n return value instanceof FormData;\n}\n\nconst palettes = {\n css: {\n query: ['72e3ff', '3fb0d8'],\n mutation: ['c5a3fc', '904dfc'],\n subscription: ['ff49e1', 'd83fbe'],\n },\n ansi: {\n regular: {\n // Cyan background, black and white text respectively\n query: ['\\x1b[30;46m', '\\x1b[97;46m'],\n // Magenta background, black and white text respectively\n mutation: ['\\x1b[30;45m', '\\x1b[97;45m'],\n // Green background, black and white text respectively\n subscription: ['\\x1b[30;42m', '\\x1b[97;42m'],\n },\n bold: {\n query: ['\\x1b[1;30;46m', '\\x1b[1;97;46m'],\n mutation: ['\\x1b[1;30;45m', '\\x1b[1;97;45m'],\n subscription: ['\\x1b[1;30;42m', '\\x1b[1;97;42m'],\n },\n },\n} as const;\n\nfunction constructPartsAndArgs(\n opts: LoggerLinkFnOptions<any> & {\n colorMode: ColorMode;\n withContext?: boolean;\n },\n) {\n const { direction, type, withContext, path, id, input } = opts;\n\n const parts: string[] = [];\n const args: any[] = [];\n\n if (opts.colorMode === 'none') {\n parts.push(direction === 'up' ? '>>' : '<<', type, `#${id}`, path);\n } else if (opts.colorMode === 'ansi') {\n const [lightRegular, darkRegular] = palettes.ansi.regular[type];\n const [lightBold, darkBold] = palettes.ansi.bold[type];\n const reset = '\\x1b[0m';\n\n parts.push(\n direction === 'up' ? lightRegular : darkRegular,\n direction === 'up' ? '>>' : '<<',\n type,\n direction === 'up' ? lightBold : darkBold,\n `#${id}`,\n path,\n reset,\n );\n } else {\n // css color mode\n const [light, dark] = palettes.css[type];\n const css = `\n background-color: #${direction === 'up' ? light : dark};\n color: ${direction === 'up' ? 'black' : 'white'};\n padding: 2px;\n `;\n\n parts.push(\n '%c',\n direction === 'up' ? '>>' : '<<',\n type,\n `#${id}`,\n `%c${path}%c`,\n '%O',\n );\n args.push(\n css,\n `${css}; font-weight: bold;`,\n `${css}; font-weight: normal;`,\n );\n }\n\n if (direction === 'up') {\n args.push(withContext ? { input, context: opts.context } : { input });\n } else {\n args.push({\n input,\n result: opts.result,\n elapsedMs: opts.elapsedMs,\n ...(withContext && { context: opts.context }),\n });\n }\n\n return { parts, args };\n}\n\n// maybe this should be moved to it's own package\nconst defaultLogger =\n <TRouter extends AnyRouter>({\n c = console,\n colorMode = 'css',\n withContext,\n }: {\n c?: ConsoleEsque;\n colorMode?: ColorMode;\n withContext?: boolean;\n }): LoggerLinkFn<TRouter> =>\n (props) => {\n const rawInput = props.input;\n const input = isFormData(rawInput)\n ? Object.fromEntries(rawInput)\n : rawInput;\n\n const { parts, args } = constructPartsAndArgs({\n ...props,\n colorMode,\n input,\n withContext,\n });\n\n const fn: 'error' | 'log' =\n props.direction === 'down' &&\n props.result &&\n (props.result instanceof Error ||\n ('error' in props.result.result && props.result.result.error))\n ? 'error'\n : 'log';\n\n c[fn].apply(null, [parts.join(' ')].concat(args));\n };\n\n/**\n * @see https://trpc.io/docs/v11/client/links/loggerLink\n */\nexport function loggerLink<TRouter extends AnyRouter = AnyRouter>(\n opts: LoggerLinkOptions<TRouter> = {},\n): TRPCLink<TRouter> {\n const { enabled = () => true } = opts;\n\n const colorMode =\n opts.colorMode ?? (typeof window === 'undefined' ? 'ansi' : 'css');\n const withContext = opts.withContext ?? colorMode === 'css';\n const {\n logger = defaultLogger({ c: opts.console, colorMode, withContext }),\n } = opts;\n\n return () => {\n return ({ op, next }) => {\n return observable((observer) => {\n // ->\n if (enabled({ ...op, direction: 'up' })) {\n logger({\n ...op,\n direction: 'up',\n });\n }\n const requestStartTime = Date.now();\n function logResult(\n result:\n | OperationResultEnvelope<unknown, TRPCClientError<TRouter>>\n | TRPCClientError<TRouter>,\n ) {\n const elapsedMs = Date.now() - requestStartTime;\n\n if (enabled({ ...op, direction: 'down', result })) {\n logger({\n ...op,\n direction: 'down',\n elapsedMs,\n result,\n });\n }\n }\n return next(op)\n .pipe(\n tap({\n next(result) {\n logResult(result);\n },\n error(result) {\n logResult(result);\n },\n }),\n )\n .subscribe(observer);\n });\n };\n };\n}\n","import { TRPCError } from '../error/TRPCError';\nimport { isObject } from '../utils';\nimport type { TRPCRequestInfo } from './types';\n\nexport function parseConnectionParamsFromUnknown(\n parsed: unknown,\n): TRPCRequestInfo['connectionParams'] {\n try {\n if (parsed === null) {\n return null;\n }\n if (!isObject(parsed)) {\n throw new Error('Expected object');\n }\n const nonStringValues = Object.entries(parsed).filter(\n ([_key, value]) => typeof value !== 'string',\n );\n\n if (nonStringValues.length > 0) {\n throw new Error(\n `Expected connectionParams to be string values. Got ${nonStringValues\n .map(([key, value]) => `${key}: ${typeof value}`)\n .join(', ')}`,\n );\n }\n return parsed as Record<string, string>;\n } catch (cause) {\n throw new TRPCError({\n code: 'PARSE_ERROR',\n message: 'Invalid connection params shape',\n cause,\n });\n }\n}\nexport function parseConnectionParamsFromString(\n str: string,\n): TRPCRequestInfo['connectionParams'] {\n let parsed: unknown;\n try {\n parsed = JSON.parse(str);\n } catch (cause) {\n throw new TRPCError({\n code: 'PARSE_ERROR',\n message: 'Not JSON-parsable query params',\n cause,\n });\n }\n return parseConnectionParamsFromUnknown(parsed);\n}\n","/** @internal */\nexport type UnsetMarker = 'unsetMarker' & {\n __brand: 'unsetMarker';\n};\n\n/**\n * Ensures there are no duplicate keys when building a procedure.\n * @internal\n */\nexport function mergeWithoutOverrides<TType extends Record<string, unknown>>(\n obj1: TType,\n ...objs: Partial<TType>[]\n): TType {\n const newObj: TType = Object.assign(emptyObject(), obj1);\n\n for (const overrides of objs) {\n for (const key in overrides) {\n if (key in newObj && newObj[key] !== overrides[key]) {\n throw new Error(`Duplicate key ${key}`);\n }\n newObj[key as keyof TType] = overrides[key] as TType[keyof TType];\n }\n }\n return newObj;\n}\n\n/**\n * Check that value is object\n * @internal\n */\nexport function isObject(value: unknown): value is Record<string, unknown> {\n return !!value && !Array.isArray(value) && typeof value === 'object';\n}\n\ntype AnyFn = ((...args: any[]) => unknown) & Record<keyof any, unknown>;\nexport function isFunction(fn: unknown): fn is AnyFn {\n return typeof fn === 'function';\n}\n\n/**\n * Create an object without inheriting anything from `Object.prototype`\n * @internal\n */\nexport function emptyObject<TObj extends Record<string, unknown>>(): TObj {\n return Object.create(null);\n}\n\nconst asyncIteratorsSupported =\n typeof Symbol === 'function' && !!Symbol.asyncIterator;\n\nexport function isAsyncIterable<TValue>(\n value: unknown,\n): value is AsyncIterable<TValue> {\n return (\n asyncIteratorsSupported && isObject(value) && Symbol.asyncIterator in value\n );\n}\n\n/**\n * Run an IIFE\n */\nexport const run = <TValue>(fn: () => TValue): TValue => fn();\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nexport function noop(): void {}\n\nexport function identity<T>(it: T): T {\n return it;\n}\n\n/**\n * Generic runtime assertion function. Throws, if the condition is not `true`.\n *\n * Can be used as a slightly less dangerous variant of type assertions. Code\n * mistakes would be revealed at runtime then (hopefully during testing).\n */\nexport function assert(\n condition: boolean,\n msg = 'no additional info',\n): asserts condition {\n if (!condition) {\n throw new Error(`AssertionError: ${msg}`);\n }\n}\n\nexport function sleep(ms = 0): Promise<void> {\n return new Promise<void>((res) => setTimeout(res, ms));\n}\n\n/**\n * Ponyfill for\n * [`AbortSignal.any`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/any_static).\n */\nexport function abortSignalsAnyPonyfill(signals: AbortSignal[]): AbortSignal {\n if (typeof AbortSignal.any === 'function') {\n return AbortSignal.any(signals);\n }\n\n const ac = new AbortController();\n\n for (const signal of signals) {\n if (signal.aborted) {\n trigger();\n break;\n }\n signal.addEventListener('abort', trigger, { once: true });\n }\n\n return ac.signal;\n\n function trigger() {\n ac.abort();\n for (const signal of signals) {\n signal.removeEventListener('abort', trigger);\n }\n }\n}\n","import type { Encoder } from '@trpc/server/adapters/ws';\n\nexport type { Encoder };\n\nexport const jsonEncoder: Encoder = {\n encode: (data) => JSON.stringify(data),\n decode: (data) => {\n if (typeof data !== 'string') {\n throw new Error(\n 'jsonEncoder received binary data. JSON uses text frames. ' +\n 'Use a binary encoder for binary data.',\n );\n }\n return JSON.parse(data);\n },\n};\n","import type {\n inferClientTypes,\n InferrableClientTypes,\n Maybe,\n TRPCErrorResponse,\n} from '@trpc/server/unstable-core-do-not-import';\nimport {\n isObject,\n type DefaultErrorShape,\n} from '@trpc/server/unstable-core-do-not-import';\n\ntype inferErrorShape<TInferrable extends InferrableClientTypes> =\n inferClientTypes<TInferrable>['errorShape'];\nexport interface TRPCClientErrorBase<TShape extends DefaultErrorShape> {\n readonly message: string;\n readonly shape: Maybe<TShape>;\n readonly data: Maybe<TShape['data']>;\n}\nexport type TRPCClientErrorLike<TInferrable extends InferrableClientTypes> =\n TRPCClientErrorBase<inferErrorShape<TInferrable>>;\n\nexport function isTRPCClientError<TInferrable extends InferrableClientTypes>(\n cause: unknown,\n): cause is TRPCClientError<TInferrable> {\n return cause instanceof TRPCClientError;\n}\n\nfunction isTRPCErrorResponse(obj: unknown): obj is TRPCErrorResponse<any> {\n return (\n isObject(obj) &&\n isObject(obj['error']) &&\n typeof obj['error']['code'] === 'number' &&\n typeof obj['error']['message'] === 'string'\n );\n}\n\nfunction getMessageFromUnknownError(err: unknown, fallback: string): string {\n if (typeof err === 'string') {\n return err;\n }\n if (isObject(err) && typeof err['message'] === 'string') {\n return err['message'];\n }\n return fallback;\n}\n\nexport class TRPCClientError<TRouterOrProcedure extends InferrableClientTypes>\n extends Error\n implements TRPCClientErrorBase<inferErrorShape<TRouterOrProcedure>>\n{\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore override doesn't work in all environments due to \"This member cannot have an 'override' modifier because it is not declared in the base class 'Error'\"\n public override readonly cause;\n public readonly shape: Maybe<inferErrorShape<TRouterOrProcedure>>;\n public readonly data: Maybe<inferErrorShape<TRouterOrProcedure>['data']>;\n\n /**\n * Additional meta data about the error\n * In the case of HTTP-errors, we'll have `response` and potentially `responseJSON` here\n */\n public meta;\n\n constructor(\n message: string,\n opts?: {\n result?: Maybe<TRPCErrorResponse<inferErrorShape<TRouterOrProcedure>>>;\n cause?: Error;\n meta?: Record<string, unknown>;\n },\n ) {\n const cause = opts?.cause;\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore https://github.com/tc39/proposal-error-cause\n super(message, { cause });\n\n this.meta = opts?.meta;\n\n this.cause = cause;\n this.shape = opts?.result?.error;\n this.data = opts?.result?.error.data;\n this.name = 'TRPCClientError';\n\n Object.setPrototypeOf(this, TRPCClientError.prototype);\n }\n\n public static from<TRouterOrProcedure extends InferrableClientTypes>(\n _cause: Error | TRPCErrorResponse<any> | object,\n opts: { meta?: Record<string, unknown>; cause?: Error } = {},\n ): TRPCClientError<TRouterOrProcedure> {\n const cause = _cause as unknown;\n\n if (isTRPCClientError(cause)) {\n if (opts.meta) {\n // Decorate with meta error data\n cause.meta = {\n ...cause.meta,\n ...opts.meta,\n };\n }\n return cause;\n }\n if (isTRPCErrorResponse(cause)) {\n return new TRPCClientError(cause.error.message, {\n ...opts,\n result: cause,\n cause: opts.cause,\n });\n }\n return new TRPCClientError(\n getMessageFromUnknownError(cause, 'Unknown error'),\n {\n ...opts,\n cause: cause as any,\n },\n );\n }\n}\n","export function isOctetType(\n input: unknown,\n): input is Uint8Array<ArrayBuffer> | Blob {\n return (\n input instanceof Uint8Array ||\n // File extends from Blob but is only available in nodejs from v20\n input instanceof Blob\n );\n}\n\nexport function isFormData(input: unknown) {\n return input instanceof FormData;\n}\n\nexport function isNonJsonSerializable(input: unknown) {\n return isOctetType(input) || isFormData(input);\n}\n","import type { TRPC_ERROR_CODE_KEY } from '../rpc/codes';\nimport { isObject } from '../utils';\n\nclass UnknownCauseError extends Error {\n [key: string]: unknown;\n\n constructor(cause: object) {\n super(getMessage(cause));\n Object.assign(this, cause);\n }\n}\n\nfunction getMessage(cause: object) {\n if ('message' in cause) return String(cause.message);\n\n return undefined;\n}\n\nexport function getCauseFromUnknown(cause: unknown): Error | undefined {\n if (cause instanceof Error) {\n return cause;\n }\n\n const type = typeof cause;\n if (type === 'undefined' || type === 'function' || cause === null) {\n return undefined;\n }\n\n // Primitive types just get wrapped in an error\n if (type !== 'object') {\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n return new Error(String(cause));\n }\n\n // If it's an object, we'll create a synthetic error\n if (isObject(cause)) {\n return new UnknownCauseError(cause);\n }\n\n return undefined;\n}\n\nexport function getTRPCErrorFromUnknown(cause: unknown): TRPCError {\n if (cause instanceof TRPCError) {\n return cause;\n }\n if (cause instanceof Error && cause.name === 'TRPCError') {\n // https://github.com/trpc/trpc/pull/4848\n return cause as TRPCError;\n }\n\n const trpcError = new TRPCError({\n code: 'INTERNAL_SERVER_ERROR',\n cause,\n });\n\n // Inherit stack from error\n if (cause instanceof Error && cause.stack) {\n trpcError.stack = cause.stack;\n }\n\n return trpcError;\n}\n\nexport class TRPCError extends Error {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore override doesn't work in all environments due to \"This member cannot have an 'override' modifier because it is not declared in the base class 'Error'\"\n public override readonly cause?: Error;\n public readonly code;\n\n constructor(opts: {\n message?: string;\n code: TRPC_ERROR_CODE_KEY;\n cause?: unknown;\n }) {\n const cause = getCauseFromUnknown(opts.cause);\n const message = opts.message ?? cause?.message ?? opts.code;\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore https://github.com/tc39/proposal-error-cause\n super(message, { cause });\n\n this.code = opts.code;\n this.name = 'TRPCError';\n this.cause ??= cause;\n }\n}\n","/* eslint-disable @typescript-eslint/no-non-null-assertion */\n\ntype BatchItem<TKey, TValue> = {\n aborted: boolean;\n key: TKey;\n resolve: ((value: TValue) => void) | null;\n reject: ((error: Error) => void) | null;\n batch: Batch<TKey, TValue> | null;\n};\ntype Batch<TKey, TValue> = {\n items: BatchItem<TKey, TValue>[];\n};\nexport type BatchLoader<TKey, TValue> = {\n validate: (keys: TKey[]) => boolean;\n fetch: (keys: TKey[]) => Promise<TValue[] | Promise<TValue>[]>;\n};\n\n/**\n * A function that should never be called unless we messed something up.\n */\nconst throwFatalError = () => {\n throw new Error(\n 'Something went wrong. Please submit an issue at https://github.com/trpc/trpc/issues/new',\n );\n};\n\n/**\n * Dataloader that's very inspired by https://github.com/graphql/dataloader\n * Less configuration, no caching, and allows you to cancel requests\n * When cancelling a single fetch the whole batch will be cancelled only when _all_ items are cancelled\n */\nexport function dataLoader<TKey, TValue>(\n batchLoader: BatchLoader<TKey, TValue>,\n) {\n let pendingItems: BatchItem<TKey, TValue>[] | null = null;\n let dispatchTimer: ReturnType<typeof setTimeout> | null = null;\n\n const destroyTimerAndPendingItems = () => {\n clearTimeout(dispatchTimer as any);\n dispatchTimer = null;\n pendingItems = null;\n };\n\n /**\n * Iterate through the items and split them into groups based on the `batchLoader`'s validate function\n */\n function groupItems(items: BatchItem<TKey, TValue>[]) {\n const groupedItems: BatchItem<TKey, TValue>[][] = [[]];\n let index = 0;\n while (true) {\n const item = items[index];\n if (!item) {\n // we're done\n break;\n }\n const lastGroup = groupedItems[groupedItems.length - 1]!;\n\n if (item.aborted) {\n // Item was aborted before it was dispatched\n item.reject?.(new Error('Aborted'));\n index++;\n continue;\n }\n\n const isValid = batchLoader.validate(\n lastGroup.concat(item).map((it) => it.key),\n );\n\n if (isValid) {\n lastGroup.push(item);\n index++;\n continue;\n }\n\n if (lastGroup.length === 0) {\n item.reject?.(new Error('Input is too big for a single dispatch'));\n index++;\n continue;\n }\n // Create new group, next iteration will try to add the item to that\n groupedItems.push([]);\n }\n return groupedItems;\n }\n\n function dispatch() {\n const groupedItems = groupItems(pendingItems!);\n destroyTimerAndPendingItems();\n\n // Create batches for each group of items\n for (const items of groupedItems) {\n if (!items.length) {\n continue;\n }\n const batch: Batch<TKey, TValue> = {\n items,\n };\n for (const item of items) {\n item.batch = batch;\n }\n const promise = batchLoader.fetch(batch.items.map((_item) => _item.key));\n\n promise\n .then(async (result) => {\n await Promise.all(\n result.map(async (valueOrPromise, index) => {\n const item = batch.items[index]!;\n try {\n const value = await Promise.resolve(valueOrPromise);\n\n item.resolve?.(value);\n } catch (cause) {\n item.reject?.(cause as Error);\n }\n\n item.batch = null;\n item.reject = null;\n item.resolve = null;\n }),\n );\n\n for (const item of batch.items) {\n item.reject?.(new Error('Missing result'));\n item.batch = null;\n }\n })\n .catch((cause) => {\n for (const item of batch.items) {\n item.reject?.(cause);\n item.batch = null;\n }\n });\n }\n }\n function load(key: TKey): Promise<TValue> {\n const item: BatchItem<TKey, TValue> = {\n aborted: false,\n key,\n batch: null,\n resolve: throwFatalError,\n reject: throwFatalError,\n };\n\n const promise = new Promise<TValue>((resolve, reject) => {\n item.reject = reject;\n item.resolve = resolve;\n\n pendingItems ??= [];\n pendingItems.push(item);\n });\n\n dispatchTimer ??= setTimeout(dispatch);\n\n return promise;\n }\n\n return {\n load,\n };\n}\n","import type {\n AnyClientTypes,\n CombinedDataTransformer,\n DataTransformerOptions,\n TypeError,\n} from '@trpc/server/unstable-core-do-not-import';\n\n/**\n * @internal\n */\nexport type CoercedTransformerParameters = {\n transformer?: DataTransformerOptions;\n};\n\ntype TransformerOptionYes = {\n /**\n * Data transformer\n *\n * You must use the same transformer on the backend and frontend\n * @see https://trpc.io/docs/v11/data-transformers\n **/\n transformer: DataTransformerOptions;\n};\ntype TransformerOptionNo = {\n /**\n * Data transformer\n *\n * You must use the same transformer on the backend and frontend\n * @see https://trpc.io/docs/v11/data-transformers\n **/\n transformer?: TypeError<'You must define a transformer on your your `initTRPC`-object first'>;\n};\n\n/**\n * @internal\n */\nexport type TransformerOptions<\n TRoot extends Pick<AnyClientTypes, 'transformer'>,\n> = TRoot['transformer'] extends true\n ? TransformerOptionYes\n : TransformerOptionNo;\n/**\n * @internal\n */\n\n/**\n * @internal\n */\nexport function getTransformer(\n transformer:\n | TransformerOptions<{ transformer: false }>['transformer']\n | TransformerOptions<{ transformer: true }>['transformer']\n | undefined,\n): CombinedDataTransformer {\n const _transformer =\n transformer as CoercedTransformerParameters['transformer'];\n if (!_transformer) {\n return {\n input: {\n serialize: (data) => data,\n deserialize: (data) => data,\n },\n output: {\n serialize: (data) => data,\n deserialize: (data) => data,\n },\n };\n }\n if ('input' in _transformer) {\n return _transformer;\n }\n return {\n input: _transformer,\n output: _transformer,\n };\n}\n","import type {\n inferObservableValue,\n Unsubscribable,\n} from '@trpc/server/observable';\nimport { observableToPromise, share } from '@trpc/server/observable';\nimport type {\n AnyRouter,\n inferAsyncIterableYield,\n InferrableClientTypes,\n Maybe,\n TypeError,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { createChain } from '../links/internals/createChain';\nimport type { TRPCConnectionState } from '../links/internals/subscriptions';\nimport type {\n OperationContext,\n OperationLink,\n TRPCClientRuntime,\n TRPCLink,\n} from '../links/types';\nimport { TRPCClientError } from '../TRPCClientError';\n\ntype TRPCType = 'mutation' | 'query' | 'subscription';\nexport interface TRPCRequestOptions {\n /**\n * Pass additional context to links\n */\n context?: OperationContext;\n signal?: AbortSignal;\n}\n\nexport interface TRPCSubscriptionObserver<TValue, TError> {\n onStarted: (opts: { context: OperationContext | undefined }) => void;\n onData: (value: inferAsyncIterableYield<TValue>) => void;\n onError: (err: TError) => void;\n onStopped: () => void;\n onComplete: () => void;\n onConnectionStateChange: (state: TRPCConnectionState<TError>) => void;\n}\n\n/** @internal */\nexport type CreateTRPCClientOptions<TRouter extends InferrableClientTypes> = {\n links: TRPCLink<TRouter>[];\n transformer?: TypeError<'The transformer property has moved to httpLink/httpBatchLink/wsLink'>;\n};\n\nexport class TRPCUntypedClient<TInferrable extends InferrableClientTypes> {\n private readonly links: OperationLink<TInferrable>[];\n public readonly runtime: TRPCClientRuntime;\n private requestId: number;\n\n constructor(opts: CreateTRPCClientOptions<TInferrable>) {\n this.requestId = 0;\n\n this.runtime = {};\n\n // Initialize the links\n this.links = opts.links.map((link) => link(this.runtime));\n }\n\n private $request<TInput = unknown, TOutput = unknown>(opts: {\n type: TRPCType;\n input: TInput;\n path: string;\n context?: OperationContext;\n signal: Maybe<AbortSignal>;\n }) {\n const chain$ = createChain<AnyRouter, TInput, TOutput>({\n links: this.links as OperationLink<any, any, any>[],\n op: {\n ...opts,\n context: opts.context ?? {},\n id: ++this.requestId,\n },\n });\n return chain$.pipe(share());\n }\n\n private async requestAsPromise<TInput = unknown, TOutput = unknown>(opts: {\n type: TRPCType;\n input: TInput;\n path: string;\n context?: OperationContext;\n signal: Maybe<AbortSignal>;\n }): Promise<TOutput> {\n try {\n const req$ = this.$request<TInput, TOutput>(opts);\n type TValue = inferObservableValue<typeof req$>;\n\n const envelope = await observableToPromise<TValue>(req$);\n const data = (envelope.result as any).data;\n return data;\n } catch (err) {\n throw TRPCClientError.from(err as Error);\n }\n }\n public query(path: string, input?: unknown, opts?: TRPCRequestOptions) {\n return this.requestAsPromise<unknown, unknown>({\n type: 'query',\n path,\n input,\n context: opts?.context,\n signal: opts?.signal,\n });\n }\n public mutation(path: string, input?: unknown, opts?: TRPCRequestOptions) {\n return this.requestAsPromise<unknown, unknown>({\n type: 'mutation',\n path,\n input,\n context: opts?.context,\n signal: opts?.signal,\n });\n }\n public subscription(\n path: string,\n input: unknown,\n opts: Partial<\n TRPCSubscriptionObserver<unknown, TRPCClientError<AnyRouter>>\n > &\n TRPCRequestOptions,\n ): Unsubscribable {\n const observable$ = this.$request({\n type: 'subscription',\n path,\n input,\n context: opts.context,\n signal: opts.signal,\n });\n return observable$.subscribe({\n next(envelope) {\n switch (envelope.result.type) {\n case 'state': {\n opts.onConnectionStateChange?.(envelope.result);\n break;\n }\n case 'started': {\n opts.onStarted?.({\n context: envelope.context,\n });\n break;\n }\n case 'stopped': {\n opts.onStopped?.();\n break;\n }\n case 'data':\n case undefined: {\n opts.onData?.(envelope.result.data);\n break;\n }\n }\n },\n error(err) {\n opts.onError?.(err);\n },\n complete() {\n opts.onComplete?.();\n },\n });\n }\n}\n","import type { UrlOptionsWithConnectionParams } from '../../internals/urlWithConnectionParams';\nimport type { Encoder } from './encoder';\n\nexport interface WebSocketClientOptions extends UrlOptionsWithConnectionParams {\n /**\n * Ponyfill which WebSocket implementation to use\n */\n WebSocket?: typeof WebSocket;\n /**\n * The number of milliseconds before a reconnect is attempted.\n * @default {@link exponentialBackoff}\n */\n retryDelayMs?: (attemptIndex: number) => number;\n /**\n * Triggered when a WebSocket connection is established\n */\n onOpen?: () => void;\n /**\n * Triggered when a WebSocket connection encounters an error\n */\n onError?: (evt?: Event) => void;\n /**\n * Triggered when a WebSocket connection is closed\n */\n onClose?: (cause?: { code?: number }) => void;\n /**\n * Lazy mode will close the WebSocket automatically after a period of inactivity (no messages sent or received and no pending requests)\n */\n lazy?: {\n /**\n * Enable lazy mode\n * @default false\n */\n enabled: boolean;\n /**\n * Close the WebSocket after this many milliseconds\n * @default 0\n */\n closeMs: number;\n };\n /**\n * Send ping messages to the server and kill the connection if no pong message is returned\n */\n keepAlive?: {\n /**\n * @default false\n */\n enabled: boolean;\n /**\n * Send a ping message every this many milliseconds\n * @default 5_000\n */\n intervalMs?: number;\n /**\n * Close the WebSocket after this many milliseconds if the server does not respond\n * @default 1_000\n */\n pongTimeoutMs?: number;\n };\n /**\n * Custom encoder for wire encoding (e.g. custom binary formats)\n * @default jsonEncoder\n */\n experimental_encoder?: Encoder;\n}\n\n/**\n * Default options for lazy WebSocket connections.\n * Determines whether the connection should be established lazily and defines the delay before closure.\n */\nexport type LazyOptions = Required<NonNullable<WebSocketClientOptions['lazy']>>;\nexport const lazyDefaults: LazyOptions = {\n enabled: false,\n closeMs: 0,\n};\n\n/**\n * Default options for the WebSocket keep-alive mechanism.\n * Configures whether keep-alive is enabled and specifies the timeout and interval for ping-pong messages.\n */\nexport type KeepAliveOptions = Required<\n NonNullable<WebSocketClientOptions['keepAlive']>\n>;\nexport const keepAliveDefaults: KeepAliveOptions = {\n enabled: false,\n pongTimeoutMs: 1_000,\n intervalMs: 5_000,\n};\n\n/**\n * Calculates a delay for exponential backoff based on the retry attempt index.\n * The delay starts at 0 for the first attempt and doubles for each subsequent attempt,\n * capped at 30 seconds.\n */\nexport const exponentialBackoff = (attemptIndex: number) => {\n return attemptIndex === 0 ? 0 : Math.min(1000 * 2 ** attemptIndex, 30000);\n};\n","import { observable } from '@trpc/server/observable';\nimport type {\n AnyClientTypes,\n AnyRouter,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { transformResult } from '@trpc/server/unstable-core-do-not-import';\nimport { raceAbortSignals } from '../internals/signals';\nimport { TRPCClientError } from '../TRPCClientError';\nimport type {\n HTTPLinkBaseOptions,\n HTTPResult,\n Requester,\n} from './internals/httpUtils';\nimport {\n getUrl,\n httpRequest,\n jsonHttpRequester,\n resolveHTTPLinkOptions,\n} from './internals/httpUtils';\nimport {\n isFormData,\n isOctetType,\n type HTTPHeaders,\n type Operation,\n type TRPCLink,\n} from './types';\n\nexport type HTTPLinkOptions<TRoot extends AnyClientTypes> =\n HTTPLinkBaseOptions<TRoot> & {\n /**\n * Headers to be set on outgoing requests or a callback that of said headers\n * @see http://trpc.io/docs/client/headers\n */\n headers?:\n | HTTPHeaders\n | ((opts: { op: Operation }) => HTTPHeaders | Promise<HTTPHeaders>);\n };\n\nconst universalRequester: Requester = (opts) => {\n if ('input' in opts) {\n const { input } = opts;\n if (isFormData(input)) {\n if (opts.type !== 'mutation' && opts.methodOverride !== 'POST') {\n throw new Error('FormData is only supported for mutations');\n }\n\n return httpRequest({\n ...opts,\n // The browser will set this automatically and include the boundary= in it\n contentTypeHeader: undefined,\n getUrl,\n getBody: () => input,\n });\n }\n\n if (isOctetType(input)) {\n if (opts.type !== 'mutation' && opts.methodOverride !== 'POST') {\n throw new Error('Octet type input is only supported for mutations');\n }\n\n return httpRequest({\n ...opts,\n contentTypeHeader: 'application/octet-stream',\n getUrl,\n getBody: () => input,\n });\n }\n }\n\n return jsonHttpRequester(opts);\n};\n\n/**\n * @see https://trpc.io/docs/client/links/httpLink\n */\nexport function httpLink<TRouter extends AnyRouter = AnyRouter>(\n opts: HTTPLinkOptions<TRouter['_def']['_config']['$types']>,\n): TRPCLink<TRouter> {\n const resolvedOpts = resolveHTTPLinkOptions(opts);\n return () => {\n return (operationOpts) => {\n const { op } = operationOpts;\n return observable((observer) => {\n const { path, input, type } = op;\n /* istanbul ignore if -- @preserve */\n if (type === 'subscription') {\n throw new Error(\n 'Subscriptions are unsupported by `httpLink` - use `httpSubscriptionLink` or `wsLink`',\n );\n }\n\n const ac = new AbortController();\n const request = universalRequester({\n ...resolvedOpts,\n type,\n path,\n input,\n signal: raceAbortSignals(op.signal, ac.signal),\n headers() {\n if (!opts.headers) {\n return {};\n }\n if (typeof opts.headers === 'function') {\n return opts.headers({\n op,\n });\n }\n return opts.headers;\n },\n });\n let isDone = false;\n let meta: HTTPResult['meta'] | undefined = undefined;\n request\n .then((res) => {\n isDone = true;\n meta = res.meta;\n const transformed = transformResult(\n res.json,\n resolvedOpts.transformer.output,\n );\n\n if (!transformed.ok) {\n observer.error(\n TRPCClientError.from(transformed.error, {\n meta,\n }),\n );\n return;\n }\n observer.next({\n context: res.meta,\n result: transformed.result,\n });\n observer.complete();\n })\n .catch((cause) => {\n isDone = true;\n observer.error(TRPCClientError.from(cause, { meta }));\n });\n\n return () => {\n if (!isDone) {\n ac.abort();\n }\n };\n });\n };\n };\n}\n","import type { Maybe } from '@trpc/server/unstable-core-do-not-import';\n\n/**\n * Like `Promise.all()` but for abort signals\n * - When all signals have been aborted, the merged signal will be aborted\n * - If one signal is `null`, no signal will be aborted\n */\nexport function allAbortSignals(...signals: Maybe<AbortSignal>[]): AbortSignal {\n const ac = new AbortController();\n\n const count = signals.length;\n\n let abortedCount = 0;\n\n const onAbort = () => {\n if (++abortedCount === count) {\n ac.abort();\n }\n };\n\n for (const signal of signals) {\n if (signal?.aborted) {\n onAbort();\n } else {\n signal?.addEventListener('abort', onAbort, {\n once: true,\n });\n }\n }\n\n return ac.signal;\n}\n\n/**\n * Like `Promise.race` but for abort signals\n *\n * Basically, a ponyfill for\n * [`AbortSignal.any`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/any_static).\n */\nexport function raceAbortSignals(\n ...signals: Maybe<AbortSignal>[]\n): AbortSignal {\n const ac = new AbortController();\n\n for (const signal of signals) {\n if (signal?.aborted) {\n ac.abort();\n } else {\n signal?.addEventListener('abort', () => ac.abort(), { once: true });\n }\n }\n\n return ac.signal;\n}\n\nexport function abortSignalToPromise(signal: AbortSignal): Promise<never> {\n return new Promise((_, reject) => {\n if (signal.aborted) {\n reject(signal.reason);\n return;\n }\n signal.addEventListener(\n 'abort',\n () => {\n reject(signal.reason);\n },\n { once: true },\n );\n });\n}\n","import { observable } from '@trpc/server/observable';\nimport type { AnyRouter } from '@trpc/server/unstable-core-do-not-import';\nimport { createChain } from './internals/createChain';\nimport type { Operation, TRPCLink } from './types';\n\nfunction asArray<TType>(value: TType | TType[]) {\n return Array.isArray(value) ? value : [value];\n}\nexport function splitLink<TRouter extends AnyRouter = AnyRouter>(opts: {\n condition: (op: Operation) => boolean;\n /**\n * The link to execute next if the test function returns `true`.\n */\n true: TRPCLink<TRouter> | TRPCLink<TRouter>[];\n /**\n * The link to execute next if the test function returns `false`.\n */\n false: TRPCLink<TRouter> | TRPCLink<TRouter>[];\n}): TRPCLink<TRouter> {\n return (runtime) => {\n const yes = asArray(opts.true).map((link) => link(runtime));\n const no = asArray(opts.false).map((link) => link(runtime));\n return (props) => {\n return observable((observer) => {\n const links = opts.condition(props.op) ? yes : no;\n return createChain({ op: props.op, links }).subscribe(observer);\n });\n };\n };\n}\n","import { TRPCError } from '../error/TRPCError';\nimport type { ProcedureType } from '../procedure';\nimport { getProcedureAtPath, type AnyRouter } from '../router';\nimport { emptyObject, isObject } from '../utils';\nimport { parseConnectionParamsFromString } from './parseConnectionParams';\nimport type { TRPCAcceptHeader, TRPCRequestInfo } from './types';\n\nexport function getAcceptHeader(headers: Headers): TRPCAcceptHeader | null {\n return (\n (headers.get('trpc-accept') as TRPCAcceptHeader | null) ??\n (headers\n .get('accept')\n ?.split(',')\n .some((t) => t.trim() === 'application/jsonl')\n ? 'application/jsonl'\n : null)\n );\n}\n\ntype GetRequestInfoOptions = {\n path: string;\n req: Request;\n url: URL | null;\n searchParams: URLSearchParams;\n headers: Headers;\n router: AnyRouter;\n maxBatchSize?: number;\n};\n\ntype ContentTypeHandler = {\n isMatch: (opts: Request) => boolean;\n parse: (opts: GetRequestInfoOptions) => Promise<TRPCRequestInfo>;\n};\n\n/**\n * Memoize a function that takes no arguments\n * @internal\n */\nfunction memo<TReturn>(fn: () => Promise<TReturn>) {\n let promise: Promise<TReturn> | null = null;\n const sym = Symbol.for('@trpc/server/http/memo');\n let value: TReturn | typeof sym = sym;\n return {\n /**\n * Lazily read the value\n */\n read: async (): Promise<TReturn> => {\n if (value !== sym) {\n return value;\n }\n\n // dedupes promises and catches errors\n promise ??= fn().catch((cause) => {\n if (cause instanceof TRPCError) {\n throw cause;\n }\n throw new TRPCError({\n code: 'BAD_REQUEST',\n message: cause instanceof Error ? cause.message : 'Invalid input',\n cause,\n });\n });\n\n value = await promise;\n promise = null;\n\n return value;\n },\n /**\n * Get an already stored result\n */\n result: (): TReturn | undefined => {\n return value !== sym ? value : undefined;\n },\n };\n}\n\nconst jsonContentTypeHandler: ContentTypeHandler = {\n isMatch(req) {\n return !!req.headers.get('content-type')?.startsWith('application/json');\n },\n async parse(opts) {\n const { req } = opts;\n const isBatchCall = opts.searchParams.get('batch') === '1';\n const maxBatchSize = opts.maxBatchSize;\n\n const paths = isBatchCall ? opts.path.split(',') : [opts.path];\n if (\n isBatchCall &&\n typeof maxBatchSize === 'number' &&\n paths.length > maxBatchSize\n ) {\n throw new TRPCError({\n code: 'BAD_REQUEST',\n message: `Batch call exceeds maximum size`,\n });\n }\n\n type InputRecord = Record<number, unknown>;\n const getInputs = memo(async (): Promise<InputRecord> => {\n let inputs: unknown = undefined;\n if (req.method === 'GET') {\n const queryInput = opts.searchParams.get('input');\n if (queryInput) {\n inputs = JSON.parse(queryInput);\n }\n } else {\n inputs = await req.json();\n }\n if (inputs === undefined) {\n return emptyObject();\n }\n\n if (!isBatchCall) {\n const result: InputRecord = emptyObject();\n result[0] =\n opts.router._def._config.transformer.input.deserialize(inputs);\n return result;\n }\n\n if (!isObject(inputs)) {\n throw new TRPCError({\n code: 'BAD_REQUEST',\n message: '\"input\" needs to be an object when doing a batch call',\n });\n }\n const acc: InputRecord = emptyObject();\n for (const index of paths.keys()) {\n const input = inputs[index];\n if (input !== undefined) {\n acc[index] =\n opts.router._def._config.transformer.input.deserialize(input);\n }\n }\n\n return acc;\n });\n\n const calls = await Promise.all(\n paths.map(\n async (path, index): Promise<TRPCRequestInfo['calls'][number]> => {\n const procedure = await getProcedureAtPath(opts.router, path);\n return {\n batchIndex: index,\n path,\n procedure,\n getRawInput: async () => {\n const inputs = await getInputs.read();\n let input = inputs[index];\n\n if (procedure?._def.type === 'subscription') {\n const lastEventId =\n opts.headers.get('last-event-id') ??\n opts.searchParams.get('lastEventId') ??\n opts.searchParams.get('Last-Event-Id');\n\n if (lastEventId) {\n if (isObject(input)) {\n input = {\n ...input,\n lastEventId: lastEventId,\n };\n } else {\n input ??= {\n lastEventId: lastEventId,\n };\n }\n }\n }\n return input;\n },\n result: () => {\n return getInputs.result()?.[index];\n },\n };\n },\n ),\n );\n\n const types = new Set(\n calls.map((call) => call.procedure?._def.type).filter(Boolean),\n );\n\n /* istanbul ignore if -- @preserve */\n if (types.size > 1) {\n throw new TRPCError({\n code: 'BAD_REQUEST',\n message: `Cannot mix procedure types in call: ${Array.from(types).join(\n ', ',\n )}`,\n });\n }\n const type: ProcedureType | 'unknown' =\n types.values().next().value ?? 'unknown';\n\n const connectionParamsStr = opts.searchParams.get('connectionParams');\n\n const info: TRPCRequestInfo = {\n isBatchCall,\n accept: getAcceptHeader(req.headers),\n calls,\n type,\n connectionParams:\n connectionParamsStr === null\n ? null\n : parseConnectionParamsFromString(connectionParamsStr),\n signal: req.signal,\n url: opts.url,\n };\n return info;\n },\n};\n\nconst formDataContentTypeHandler: ContentTypeHandler = {\n isMatch(req) {\n return !!req.headers.get('content-type')?.startsWith('multipart/form-data');\n },\n async parse(opts) {\n const { req } = opts;\n if (req.method !== 'POST') {\n throw new TRPCError({\n code: 'METHOD_NOT_SUPPORTED',\n message:\n 'Only POST requests are supported for multipart/form-data requests',\n });\n }\n const getInputs = memo(async () => {\n const fd = await req.formData();\n return fd;\n });\n const procedure = await getProcedureAtPath(opts.router, opts.path);\n return {\n accept: null,\n calls: [\n {\n batchIndex: 0,\n path: opts.path,\n getRawInput: getInputs.read,\n result: getInputs.result,\n procedure,\n },\n ],\n isBatchCall: false,\n type: 'mutation',\n connectionParams: null,\n signal: req.signal,\n url: opts.url,\n };\n },\n};\n\nconst octetStreamContentTypeHandler: ContentTypeHandler = {\n isMatch(req) {\n return !!req.headers\n .get('content-type')\n ?.startsWith('application/octet-stream');\n },\n async parse(opts) {\n const { req } = opts;\n if (req.method !== 'POST') {\n throw new TRPCError({\n code: 'METHOD_NOT_SUPPORTED',\n message:\n 'Only POST requests are supported for application/octet-stream requests',\n });\n }\n const getInputs = memo(async () => {\n return req.body;\n });\n return {\n calls: [\n {\n batchIndex: 0,\n path: opts.path,\n getRawInput: getInputs.read,\n result: getInputs.result,\n procedure: await getProcedureAtPath(opts.router, opts.path),\n },\n ],\n isBatchCall: false,\n accept: null,\n type: 'mutation',\n connectionParams: null,\n signal: req.signal,\n url: opts.url,\n };\n },\n};\n\nconst handlers = [\n jsonContentTypeHandler,\n formDataContentTypeHandler,\n octetStreamContentTypeHandler,\n];\n\nfunction getContentTypeHandler(req: Request): ContentTypeHandler {\n const handler = handlers.find((handler) => handler.isMatch(req));\n if (handler) {\n return handler;\n }\n\n if (!handler && req.method === 'GET') {\n // fallback to JSON for get requests so GET-requests can be opened in browser easily\n return jsonContentTypeHandler;\n }\n\n throw new TRPCError({\n code: 'UNSUPPORTED_MEDIA_TYPE',\n message: req.headers.has('content-type')\n ? `Unsupported content-type \"${req.headers.get('content-type')}`\n : 'Missing content-type header',\n });\n}\n\nexport async function getRequestInfo(\n opts: GetRequestInfoOptions,\n): Promise<TRPCRequestInfo> {\n const handler = getContentTypeHandler(opts.req);\n return await handler.parse(opts);\n}\n","import { type TRPCRequestInfo } from '@trpc/server/http';\n\n/**\n * Get the result of a value or function that returns a value\n * It also optionally accepts typesafe arguments for the function\n */\nexport const resultOf = <T, TArgs extends any[]>(\n value: T | ((...args: TArgs) => T),\n ...args: TArgs\n): T => {\n return typeof value === 'function'\n ? (value as (...args: TArgs) => T)(...args)\n : value;\n};\n\n/**\n * A value that can be wrapped in callback\n */\nexport type CallbackOrValue<T> = T | (() => T | Promise<T>);\n\nexport interface UrlOptionsWithConnectionParams {\n /**\n * The URL to connect to (can be a function that returns a URL)\n */\n url: CallbackOrValue<string>;\n\n /**\n * Connection params that are available in `createContext()`\n * - For `wsLink`/`wsClient`, these are sent as the first message\n * - For `httpSubscriptionLink`, these are serialized as part of the URL under the `connectionParams` query\n */\n connectionParams?: CallbackOrValue<TRPCRequestInfo['connectionParams']>;\n}\n","import type {\n TRPCConnectionParamsMessage,\n TRPCRequestInfo,\n} from '@trpc/server/unstable-core-do-not-import';\nimport type {\n CallbackOrValue,\n UrlOptionsWithConnectionParams,\n} from '../../internals/urlWithConnectionParams';\nimport { resultOf } from '../../internals/urlWithConnectionParams';\nimport type { Encoder } from './encoder';\n\nexport class TRPCWebSocketClosedError extends Error {\n constructor(opts: { message: string; cause?: unknown }) {\n super(opts.message, {\n cause: opts.cause,\n });\n this.name = 'TRPCWebSocketClosedError';\n Object.setPrototypeOf(this, TRPCWebSocketClosedError.prototype);\n }\n}\n\n/**\n * Utility class for managing a timeout that can be started, stopped, and reset.\n * Useful for scenarios where the timeout duration is reset dynamically based on events.\n */\nexport class ResettableTimeout {\n private timeout: ReturnType<typeof setTimeout> | undefined;\n\n constructor(\n private readonly onTimeout: () => void,\n private readonly timeoutMs: number,\n ) {}\n\n /**\n * Resets the current timeout, restarting it with the same duration.\n * Does nothing if no timeout is active.\n */\n public reset() {\n if (!this.timeout) return;\n\n clearTimeout(this.timeout);\n this.timeout = setTimeout(this.onTimeout, this.timeoutMs);\n }\n\n public start() {\n clearTimeout(this.timeout);\n this.timeout = setTimeout(this.onTimeout, this.timeoutMs);\n }\n\n public stop() {\n clearTimeout(this.timeout);\n this.timeout = undefined;\n }\n}\n\n// Ponyfill for Promise.withResolvers https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers\nexport function withResolvers<T>() {\n let resolve: (value: T | PromiseLike<T>) => void;\n let reject: (reason?: any) => void;\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return { promise, resolve: resolve!, reject: reject! };\n}\n\n/**\n * Resolves a WebSocket URL and optionally appends connection parameters.\n *\n * If connectionParams are provided, appends 'connectionParams=1' query parameter.\n */\nexport async function prepareUrl(urlOptions: UrlOptionsWithConnectionParams) {\n const url = await resultOf(urlOptions.url);\n\n if (!urlOptions.connectionParams) return url;\n\n // append `?connectionParams=1` when connection params are used\n const prefix = url.includes('?') ? '&' : '?';\n const connectionParams = `${prefix}connectionParams=1`;\n\n return url + connectionParams;\n}\n\nexport async function buildConnectionMessage(\n connectionParams: CallbackOrValue<TRPCRequestInfo['connectionParams']>,\n encoder: Encoder,\n) {\n const message: TRPCConnectionParamsMessage = {\n method: 'connectionParams',\n data: await resultOf(connectionParams),\n };\n\n return encoder.encode(message);\n}\n","import type { AnyRootTypes, RootConfig } from './rootConfig';\nimport type { AnyRouter, inferRouterError } from './router';\nimport type {\n TRPCResponse,\n TRPCResponseMessage,\n TRPCResultMessage,\n} from './rpc';\nimport { isObject } from './utils';\n\n/**\n * @public\n */\nexport interface DataTransformer {\n serialize(object: any): any;\n deserialize(object: any): any;\n}\n\ninterface InputDataTransformer extends DataTransformer {\n /**\n * This function runs **on the client** before sending the data to the server.\n */\n serialize(object: any): any;\n /**\n * This function runs **on the server** to transform the data before it is passed to the resolver\n */\n deserialize(object: any): any;\n}\n\ninterface OutputDataTransformer extends DataTransformer {\n /**\n * This function runs **on the server** before sending the data to the client.\n */\n serialize(object: any): any;\n /**\n * This function runs **only on the client** to transform the data sent from the server.\n */\n deserialize(object: any): any;\n}\n\n/**\n * @public\n */\nexport interface CombinedDataTransformer {\n /**\n * Specify how the data sent from the client to the server should be transformed.\n */\n input: InputDataTransformer;\n /**\n * Specify how the data sent from the server to the client should be transformed.\n */\n output: OutputDataTransformer;\n}\n\n/**\n * @public\n */\nexport type CombinedDataTransformerClient = {\n input: Pick<CombinedDataTransformer['input'], 'serialize'>;\n output: Pick<CombinedDataTransformer['output'], 'deserialize'>;\n};\n\n/**\n * @public\n */\nexport type DataTransformerOptions = CombinedDataTransformer | DataTransformer;\n\n/**\n * @internal\n */\nexport function getDataTransformer(\n transformer: DataTransformerOptions,\n): CombinedDataTransformer {\n if ('input' in transformer) {\n return transformer;\n }\n return { input: transformer, output: transformer };\n}\n\n/**\n * @internal\n */\nexport const defaultTransformer: CombinedDataTransformer = {\n input: { serialize: (obj) => obj, deserialize: (obj) => obj },\n output: { serialize: (obj) => obj, deserialize: (obj) => obj },\n};\n\nfunction transformTRPCResponseItem<\n TResponseItem extends TRPCResponse | TRPCResponseMessage,\n>(config: RootConfig<AnyRootTypes>, item: TResponseItem): TResponseItem {\n if ('error' in item) {\n return {\n ...item,\n error: config.transformer.output.serialize(item.error),\n };\n }\n\n if ('data' in item.result) {\n return {\n ...item,\n result: {\n ...item.result,\n data: config.transformer.output.serialize(item.result.data),\n },\n };\n }\n\n return item;\n}\n\n/**\n * Takes a unserialized `TRPCResponse` and serializes it with the router's transformers\n **/\nexport function transformTRPCResponse<\n TResponse extends\n TRPCResponse | TRPCResponse[] | TRPCResponseMessage | TRPCResponseMessage[],\n>(config: RootConfig<AnyRootTypes>, itemOrItems: TResponse) {\n return Array.isArray(itemOrItems)\n ? itemOrItems.map((item) => transformTRPCResponseItem(config, item))\n : transformTRPCResponseItem(config, itemOrItems);\n}\n\n// FIXME:\n// - the generics here are probably unnecessary\n// - the RPC-spec could probably be simplified to combine HTTP + WS\n/** @internal */\nfunction transformResultInner<TRouter extends AnyRouter, TOutput>(\n response:\n | TRPCResponse<TOutput, inferRouterError<TRouter>>\n | TRPCResponseMessage<TOutput, inferRouterError<TRouter>>,\n transformer: DataTransformer,\n) {\n if ('error' in response) {\n const error = transformer.deserialize(\n response.error,\n ) as inferRouterError<TRouter>;\n return {\n ok: false,\n error: {\n ...response,\n error,\n },\n } as const;\n }\n\n const result = {\n ...response.result,\n ...((!response.result.type || response.result.type === 'data') && {\n type: 'data',\n data: transformer.deserialize(response.result.data),\n }),\n } as TRPCResultMessage<TOutput>['result'];\n return { ok: true, result } as const;\n}\n\nclass TransformResultError extends Error {\n constructor() {\n super('Unable to transform response from server');\n }\n}\n\n/**\n * Transforms and validates that the result is a valid TRPCResponse\n * @internal\n */\nexport function transformResult<TRouter extends AnyRouter, TOutput>(\n response:\n | TRPCResponse<TOutput, inferRouterError<TRouter>>\n | TRPCResponseMessage<TOutput, inferRouterError<TRouter>>,\n transformer: DataTransformer,\n): ReturnType<typeof transformResultInner> {\n let result: ReturnType<typeof transformResultInner>;\n try {\n // Use the data transformers on the JSON-response\n result = transformResultInner(response, transformer);\n } catch {\n throw new TransformResultError();\n }\n\n // check that output of the transformers is a valid TRPCResponse\n if (\n !result.ok &&\n (!isObject(result.error.error) ||\n typeof result.error.error['code'] !== 'number')\n ) {\n throw new TransformResultError();\n }\n if (result.ok && !isObject(result.result)) {\n throw new TransformResultError();\n }\n return result;\n}\n","import type {\n AnyClientTypes,\n CombinedDataTransformer,\n Maybe,\n ProcedureType,\n TRPCAcceptHeader,\n TRPCResponse,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { getFetch } from '../../getFetch';\nimport type {\n FetchEsque,\n RequestInitEsque,\n ResponseEsque,\n} from '../../internals/types';\nimport type { TransformerOptions } from '../../unstable-internals';\nimport { getTransformer } from '../../unstable-internals';\nimport type { HTTPHeaders } from '../types';\n\n/**\n * @internal\n */\nexport type HTTPLinkBaseOptions<\n TRoot extends Pick<AnyClientTypes, 'transformer'>,\n> = {\n url: string | URL;\n /**\n * Add ponyfill for fetch\n */\n fetch?: FetchEsque;\n /**\n * Send all requests `as POST`s requests regardless of the procedure type\n * The HTTP handler must separately allow overriding the method. See:\n * @see https://trpc.io/docs/rpc\n */\n methodOverride?: 'POST';\n} & TransformerOptions<TRoot>;\n\nexport interface ResolvedHTTPLinkOptions {\n url: string;\n fetch?: FetchEsque;\n transformer: CombinedDataTransformer;\n methodOverride?: 'POST';\n}\n\nexport function resolveHTTPLinkOptions(\n opts: HTTPLinkBaseOptions<AnyClientTypes>,\n): ResolvedHTTPLinkOptions {\n return {\n url: opts.url.toString(),\n fetch: opts.fetch,\n transformer: getTransformer(opts.transformer),\n methodOverride: opts.methodOverride,\n };\n}\n\n// https://github.com/trpc/trpc/pull/669\nfunction arrayToDict(array: unknown[]) {\n const dict: Record<number, unknown> = {};\n for (let index = 0; index < array.length; index++) {\n const element = array[index];\n dict[index] = element;\n }\n return dict;\n}\n\nconst METHOD = {\n query: 'GET',\n mutation: 'POST',\n subscription: 'PATCH',\n} as const;\n\nexport interface HTTPResult {\n json: TRPCResponse;\n meta: {\n response: ResponseEsque;\n responseJSON?: unknown;\n };\n}\n\ntype GetInputOptions = {\n transformer: CombinedDataTransformer;\n} & ({ input: unknown } | { inputs: unknown[] });\n\nexport function getInput(opts: GetInputOptions) {\n return 'input' in opts\n ? opts.transformer.input.serialize(opts.input)\n : arrayToDict(\n opts.inputs.map((_input) => opts.transformer.input.serialize(_input)),\n );\n}\n\nexport type HTTPBaseRequestOptions = GetInputOptions &\n ResolvedHTTPLinkOptions & {\n type: ProcedureType;\n path: string;\n signal: Maybe<AbortSignal>;\n };\n\ntype GetUrl = (opts: HTTPBaseRequestOptions) => string;\ntype GetBody = (opts: HTTPBaseRequestOptions) => RequestInitEsque['body'];\n\nexport type ContentOptions = {\n trpcAcceptHeader?: TRPCAcceptHeader;\n trpcAcceptHeaderKey?: 'trpc-accept' | 'accept';\n contentTypeHeader?: string;\n getUrl: GetUrl;\n getBody: GetBody;\n};\n\nexport const getUrl: GetUrl = (opts) => {\n const parts = opts.url.split('?') as [string, string?];\n const base = parts[0].replace(/\\/$/, ''); // Remove any trailing slashes\n\n let url = base + '/' + opts.path;\n const queryParts: string[] = [];\n\n if (parts[1]) {\n queryParts.push(parts[1]);\n }\n if ('inputs' in opts) {\n queryParts.push('batch=1');\n }\n if (opts.type === 'query' || opts.type === 'subscription') {\n const input = getInput(opts);\n if (input !== undefined && opts.methodOverride !== 'POST') {\n queryParts.push(`input=${encodeURIComponent(JSON.stringify(input))}`);\n }\n }\n if (queryParts.length) {\n url += '?' + queryParts.join('&');\n }\n return url;\n};\n\nexport const getBody: GetBody = (opts) => {\n if (opts.type === 'query' && opts.methodOverride !== 'POST') {\n return undefined;\n }\n const input = getInput(opts);\n return input !== undefined ? JSON.stringify(input) : undefined;\n};\n\nexport type Requester = (\n opts: HTTPBaseRequestOptions & {\n headers: () => HTTPHeaders | Promise<HTTPHeaders>;\n },\n) => Promise<HTTPResult>;\n\nexport const jsonHttpRequester: Requester = (opts) => {\n return httpRequest({\n ...opts,\n contentTypeHeader: 'application/json',\n getUrl,\n getBody,\n });\n};\n\n/**\n * Polyfill for DOMException with AbortError name\n */\nclass AbortError extends Error {\n constructor() {\n const name = 'AbortError';\n super(name);\n this.name = name;\n this.message = name;\n }\n}\n\nexport type HTTPRequestOptions = ContentOptions &\n HTTPBaseRequestOptions & {\n headers: () => HTTPHeaders | Promise<HTTPHeaders>;\n };\n\n/**\n * Polyfill for `signal.throwIfAborted()`\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/throwIfAborted\n */\nconst throwIfAborted = (signal: Maybe<AbortSignal>) => {\n if (!signal?.aborted) {\n return;\n }\n // If available, use the native implementation\n signal.throwIfAborted?.();\n\n // If we have `DOMException`, use it\n if (typeof DOMException !== 'undefined') {\n throw new DOMException('AbortError', 'AbortError');\n }\n\n // Otherwise, use our own implementation\n throw new AbortError();\n};\n\nexport async function fetchHTTPResponse(opts: HTTPRequestOptions) {\n throwIfAborted(opts.signal);\n\n const url = opts.getUrl(opts);\n const body = opts.getBody(opts);\n const method = opts.methodOverride ?? METHOD[opts.type];\n const resolvedHeaders = await (async () => {\n const heads = await opts.headers();\n if (Symbol.iterator in heads) {\n return Object.fromEntries(heads);\n }\n return heads;\n })();\n const headers = {\n ...(opts.contentTypeHeader && method !== 'GET'\n ? { 'content-type': opts.contentTypeHeader }\n : {}),\n ...(opts.trpcAcceptHeader\n ? { [opts.trpcAcceptHeaderKey ?? 'trpc-accept']: opts.trpcAcceptHeader }\n : undefined),\n ...resolvedHeaders,\n };\n\n return getFetch(opts.fetch)(url, {\n method,\n signal: opts.signal,\n body,\n headers,\n });\n}\n\nexport async function httpRequest(\n opts: HTTPRequestOptions,\n): Promise<HTTPResult> {\n const meta = {} as HTTPResult['meta'];\n\n const res = await fetchHTTPResponse(opts);\n meta.response = res;\n\n const json = await res.json();\n\n meta.responseJSON = json;\n\n return {\n json: json as TRPCResponse,\n meta,\n };\n}\n","import type { TRPCError } from '../error/TRPCError';\nimport type { TRPC_ERROR_CODES_BY_KEY, TRPCResponse } from '../rpc';\nimport { TRPC_ERROR_CODES_BY_NUMBER } from '../rpc';\nimport type { InvertKeyValue, ValueOf } from '../types';\nimport { isObject } from '../utils';\n\nexport const JSONRPC2_TO_HTTP_CODE: Record<\n keyof typeof TRPC_ERROR_CODES_BY_KEY,\n number\n> = {\n PARSE_ERROR: 400,\n BAD_REQUEST: 400,\n UNAUTHORIZED: 401,\n PAYMENT_REQUIRED: 402,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n METHOD_NOT_SUPPORTED: 405,\n TIMEOUT: 408,\n CONFLICT: 409,\n PRECONDITION_FAILED: 412,\n PAYLOAD_TOO_LARGE: 413,\n UNSUPPORTED_MEDIA_TYPE: 415,\n UNPROCESSABLE_CONTENT: 422,\n PRECONDITION_REQUIRED: 428,\n TOO_MANY_REQUESTS: 429,\n CLIENT_CLOSED_REQUEST: 499,\n INTERNAL_SERVER_ERROR: 500,\n NOT_IMPLEMENTED: 501,\n BAD_GATEWAY: 502,\n SERVICE_UNAVAILABLE: 503,\n GATEWAY_TIMEOUT: 504,\n};\n\nexport const HTTP_CODE_TO_JSONRPC2: InvertKeyValue<\n typeof JSONRPC2_TO_HTTP_CODE\n> = {\n 400: 'BAD_REQUEST',\n 401: 'UNAUTHORIZED',\n 402: 'PAYMENT_REQUIRED',\n 403: 'FORBIDDEN',\n 404: 'NOT_FOUND',\n 405: 'METHOD_NOT_SUPPORTED',\n 408: 'TIMEOUT',\n 409: 'CONFLICT',\n 412: 'PRECONDITION_FAILED',\n 413: 'PAYLOAD_TOO_LARGE',\n 415: 'UNSUPPORTED_MEDIA_TYPE',\n 422: 'UNPROCESSABLE_CONTENT',\n 428: 'PRECONDITION_REQUIRED',\n 429: 'TOO_MANY_REQUESTS',\n 499: 'CLIENT_CLOSED_REQUEST',\n 500: 'INTERNAL_SERVER_ERROR',\n 501: 'NOT_IMPLEMENTED',\n 502: 'BAD_GATEWAY',\n 503: 'SERVICE_UNAVAILABLE',\n 504: 'GATEWAY_TIMEOUT',\n} as const;\n\nexport function getStatusCodeFromKey(\n code: keyof typeof TRPC_ERROR_CODES_BY_KEY,\n) {\n return JSONRPC2_TO_HTTP_CODE[code] ?? 500;\n}\n\nexport function getStatusKeyFromCode(\n code: keyof typeof HTTP_CODE_TO_JSONRPC2,\n): ValueOf<typeof HTTP_CODE_TO_JSONRPC2> {\n return HTTP_CODE_TO_JSONRPC2[code] ?? 'INTERNAL_SERVER_ERROR';\n}\n\nexport function getHTTPStatusCode(json: TRPCResponse | TRPCResponse[]) {\n const arr = Array.isArray(json) ? json : [json];\n const httpStatuses = new Set<number>(\n arr.map((res) => {\n if ('error' in res && isObject(res.error.data)) {\n if (typeof res.error.data?.['httpStatus'] === 'number') {\n return res.error.data['httpStatus'];\n }\n const code = TRPC_ERROR_CODES_BY_NUMBER[res.error.code];\n return getStatusCodeFromKey(code);\n }\n return 200;\n }),\n );\n\n if (httpStatuses.size !== 1) {\n return 207;\n }\n\n const httpStatus = httpStatuses.values().next().value;\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return httpStatus!;\n}\n\nexport function getHTTPStatusCodeFromError(error: TRPCError) {\n return getStatusCodeFromKey(error.code);\n}\n","import type { InvertKeyValue, ValueOf } from '../types';\n\n// reference: https://www.jsonrpc.org/specification\n\n/**\n * JSON-RPC 2.0 Error codes\n *\n * `-32000` to `-32099` are reserved for implementation-defined server-errors.\n * For tRPC we're copying the last digits of HTTP 4XX errors.\n */\nexport const TRPC_ERROR_CODES_BY_KEY = {\n /**\n * Invalid JSON was received by the server.\n * An error occurred on the server while parsing the JSON text.\n */\n PARSE_ERROR: -32700,\n /**\n * The JSON sent is not a valid Request object.\n */\n BAD_REQUEST: -32600, // 400\n\n // Internal JSON-RPC error\n INTERNAL_SERVER_ERROR: -32603, // 500\n NOT_IMPLEMENTED: -32603, // 501\n BAD_GATEWAY: -32603, // 502\n SERVICE_UNAVAILABLE: -32603, // 503\n GATEWAY_TIMEOUT: -32603, // 504\n\n // Implementation specific errors\n UNAUTHORIZED: -32001, // 401\n PAYMENT_REQUIRED: -32002, // 402\n FORBIDDEN: -32003, // 403\n NOT_FOUND: -32004, // 404\n METHOD_NOT_SUPPORTED: -32005, // 405\n TIMEOUT: -32008, // 408\n CONFLICT: -32009, // 409\n PRECONDITION_FAILED: -32012, // 412\n PAYLOAD_TOO_LARGE: -32013, // 413\n UNSUPPORTED_MEDIA_TYPE: -32015, // 415\n UNPROCESSABLE_CONTENT: -32022, // 422\n PRECONDITION_REQUIRED: -32028, // 428\n TOO_MANY_REQUESTS: -32029, // 429\n CLIENT_CLOSED_REQUEST: -32099, // 499\n} as const;\n\n// pure\nexport const TRPC_ERROR_CODES_BY_NUMBER: InvertKeyValue<\n typeof TRPC_ERROR_CODES_BY_KEY\n> = {\n [-32700]: 'PARSE_ERROR',\n [-32600]: 'BAD_REQUEST',\n [-32603]: 'INTERNAL_SERVER_ERROR',\n [-32001]: 'UNAUTHORIZED',\n [-32002]: 'PAYMENT_REQUIRED',\n [-32003]: 'FORBIDDEN',\n [-32004]: 'NOT_FOUND',\n [-32005]: 'METHOD_NOT_SUPPORTED',\n [-32008]: 'TIMEOUT',\n [-32009]: 'CONFLICT',\n [-32012]: 'PRECONDITION_FAILED',\n [-32013]: 'PAYLOAD_TOO_LARGE',\n [-32015]: 'UNSUPPORTED_MEDIA_TYPE',\n [-32022]: 'UNPROCESSABLE_CONTENT',\n [-32028]: 'PRECONDITION_REQUIRED',\n [-32029]: 'TOO_MANY_REQUESTS',\n [-32099]: 'CLIENT_CLOSED_REQUEST',\n};\n\nexport type TRPC_ERROR_CODE_NUMBER = ValueOf<typeof TRPC_ERROR_CODES_BY_KEY>;\nexport type TRPC_ERROR_CODE_KEY = keyof typeof TRPC_ERROR_CODES_BY_KEY;\n\n/**\n * tRPC error codes that are considered retryable\n * With out of the box SSE, the client will reconnect when these errors are encountered\n */\nexport const retryableRpcCodes: TRPC_ERROR_CODE_NUMBER[] = [\n TRPC_ERROR_CODES_BY_KEY.BAD_GATEWAY,\n TRPC_ERROR_CODES_BY_KEY.SERVICE_UNAVAILABLE,\n TRPC_ERROR_CODES_BY_KEY.GATEWAY_TIMEOUT,\n TRPC_ERROR_CODES_BY_KEY.INTERNAL_SERVER_ERROR,\n];\n","import type { AnyRouter } from '@trpc/server/unstable-core-do-not-import';\nimport type { CreateTRPCClientOptions } from './internals/TRPCUntypedClient';\nimport { TRPCUntypedClient } from './internals/TRPCUntypedClient';\n\nexport function createTRPCUntypedClient<TRouter extends AnyRouter>(\n opts: CreateTRPCClientOptions<TRouter>,\n): TRPCUntypedClient<TRouter> {\n return new TRPCUntypedClient(opts);\n}\n\nexport type {\n CreateTRPCClientOptions,\n TRPCRequestOptions,\n} from './internals/TRPCUntypedClient';\nexport { TRPCUntypedClient } from './internals/TRPCUntypedClient';\n","/* eslint-disable @typescript-eslint/no-non-null-assertion */\nimport type { Unsubscribable } from '@trpc/server/observable';\nimport type {\n AnyProcedure,\n AnyRouter,\n inferClientTypes,\n inferProcedureInput,\n InferrableClientTypes,\n inferTransformedProcedureOutput,\n ProcedureType,\n RouterRecord,\n} from '@trpc/server/unstable-core-do-not-import';\nimport {\n createFlatProxy,\n createRecursiveProxy,\n} from '@trpc/server/unstable-core-do-not-import';\nimport type { CreateTRPCClientOptions } from './createTRPCUntypedClient';\nimport type { TRPCSubscriptionObserver } from './internals/TRPCUntypedClient';\nimport { TRPCUntypedClient } from './internals/TRPCUntypedClient';\nimport type { TRPCProcedureOptions } from './internals/types';\nimport type { TRPCClientError } from './TRPCClientError';\n\n/**\n * @public\n * @deprecated use {@link TRPCClient} instead, will be removed in v12\n **/\nexport type inferRouterClient<TRouter extends AnyRouter> = TRPCClient<TRouter>;\n\n/**\n * @public\n * @deprecated use {@link TRPCClient} instead, will be removed in v12\n **/\nexport type CreateTRPCClient<TRouter extends AnyRouter> = TRPCClient<TRouter>;\n\nconst untypedClientSymbol = Symbol.for('trpc_untypedClient');\n\n/**\n * @public\n **/\nexport type TRPCClient<TRouter extends AnyRouter> = DecoratedProcedureRecord<\n {\n transformer: TRouter['_def']['_config']['$types']['transformer'];\n errorShape: TRouter['_def']['_config']['$types']['errorShape'];\n },\n TRouter['_def']['record']\n> & {\n [untypedClientSymbol]: TRPCUntypedClient<TRouter>;\n};\n\n/** @internal */\nexport type TRPCResolverDef = {\n input: any;\n output: any;\n transformer: boolean;\n errorShape: any;\n};\n\ntype coerceAsyncGeneratorToIterable<T> =\n T extends AsyncGenerator<infer $T, infer $Return, infer $Next>\n ? AsyncIterable<$T, $Return, $Next>\n : T;\n\n/** @internal */\nexport type Resolver<TDef extends TRPCResolverDef> = (\n input: TDef['input'],\n opts?: TRPCProcedureOptions,\n) => Promise<coerceAsyncGeneratorToIterable<TDef['output']>>;\n\n/** @internal */\nexport type SubscriptionResolver<TDef extends TRPCResolverDef> = (\n input: TDef['input'],\n opts: Partial<\n TRPCSubscriptionObserver<TDef['output'], TRPCClientError<TDef>>\n > &\n TRPCProcedureOptions,\n) => Unsubscribable;\n\ntype DecorateProcedure<\n TType extends ProcedureType,\n TDef extends TRPCResolverDef,\n> = TType extends 'query'\n ? {\n query: Resolver<TDef>;\n }\n : TType extends 'mutation'\n ? {\n mutate: Resolver<TDef>;\n }\n : TType extends 'subscription'\n ? {\n subscribe: SubscriptionResolver<TDef>;\n }\n : never;\n\n/**\n * @internal\n */\ntype DecoratedProcedureRecord<\n TRoot extends InferrableClientTypes,\n TRecord extends RouterRecord,\n> = {\n [TKey in keyof TRecord]: TRecord[TKey] extends infer $Value\n ? $Value extends AnyProcedure\n ? DecorateProcedure<\n $Value['_def']['type'],\n {\n input: inferProcedureInput<$Value>;\n output: inferTransformedProcedureOutput<\n inferClientTypes<TRoot>,\n $Value\n >;\n errorShape: inferClientTypes<TRoot>['errorShape'];\n transformer: inferClientTypes<TRoot>['transformer'];\n }\n >\n : $Value extends RouterRecord\n ? DecoratedProcedureRecord<TRoot, $Value>\n : never\n : never;\n};\n\nconst clientCallTypeMap: Record<\n keyof DecorateProcedure<any, any>,\n ProcedureType\n> = {\n query: 'query',\n mutate: 'mutation',\n subscribe: 'subscription',\n};\n\n/** @internal */\nexport const clientCallTypeToProcedureType = (\n clientCallType: string,\n): ProcedureType => {\n return clientCallTypeMap[clientCallType as keyof typeof clientCallTypeMap];\n};\n\n/**\n * @internal\n */\nexport function createTRPCClientProxy<TRouter extends AnyRouter>(\n client: TRPCUntypedClient<TRouter>,\n): TRPCClient<TRouter> {\n const proxy = createRecursiveProxy<TRPCClient<TRouter>>(({ path, args }) => {\n const pathCopy = [...path];\n const procedureType = clientCallTypeToProcedureType(pathCopy.pop()!);\n\n const fullPath = pathCopy.join('.');\n\n return (client[procedureType] as any)(fullPath, ...(args as any));\n });\n return createFlatProxy<TRPCClient<TRouter>>((key) => {\n if (key === untypedClientSymbol) {\n return client;\n }\n return proxy[key];\n });\n}\n\nexport function createTRPCClient<TRouter extends AnyRouter>(\n opts: CreateTRPCClientOptions<TRouter>,\n): TRPCClient<TRouter> {\n const client = new TRPCUntypedClient(opts);\n const proxy = createTRPCClientProxy<TRouter>(client);\n return proxy;\n}\n\n/**\n * Get an untyped client from a proxy client\n * @internal\n */\nexport function getUntypedClient<TRouter extends AnyRouter>(\n client: TRPCClient<TRouter>,\n): TRPCUntypedClient<TRouter> {\n return client[untypedClientSymbol];\n}\n","import type { AnyTRPCRouter, inferRouterError } from '@trpc/server';\nimport type { Observer } from '@trpc/server/observable';\nimport type {\n TRPCClientOutgoingMessage,\n TRPCResponseMessage,\n} from '@trpc/server/unstable-core-do-not-import';\nimport type { TRPCClientError } from '../../../TRPCClientError';\nimport { withResolvers } from './utils';\n\nexport type TCallbacks = Observer<\n TRPCResponseMessage<unknown, inferRouterError<AnyTRPCRouter>>,\n TRPCClientError<AnyTRPCRouter>\n>;\n\ntype MessageId = string;\ntype MessageIdLike = string | number | null;\n\n/**\n * Represents a WebSocket request managed by the RequestManager.\n * Combines the network message, a utility promise (`end`) that mirrors the lifecycle\n * handled by `callbacks`, and a set of state monitoring callbacks.\n */\ninterface Request {\n message: TRPCClientOutgoingMessage;\n end: Promise<void>;\n callbacks: TCallbacks;\n}\n\n/**\n * Manages WebSocket requests, tracking their lifecycle and providing utility methods\n * for handling outgoing and pending requests.\n *\n * - **Outgoing requests**: Requests that are queued and waiting to be sent.\n * - **Pending requests**: Requests that have been sent and are in flight awaiting a response.\n * For subscriptions, multiple responses may be received until the subscription is closed.\n */\nexport class RequestManager {\n /**\n * Stores requests that are outgoing, meaning they are registered but not yet sent over the WebSocket.\n */\n private outgoingRequests = new Array<Request & { id: MessageId }>();\n\n /**\n * Stores requests that are pending (in flight), meaning they have been sent over the WebSocket\n * and are awaiting responses. For subscriptions, this includes requests\n * that may receive multiple responses.\n */\n private pendingRequests: Record<MessageId, Request> = {};\n\n /**\n * Registers a new request by adding it to the outgoing queue and setting up\n * callbacks for lifecycle events such as completion or error.\n *\n * @param message - The outgoing message to be sent.\n * @param callbacks - Callback functions to observe the request's state.\n * @returns A cleanup function to manually remove the request.\n */\n public register(message: TRPCClientOutgoingMessage, callbacks: TCallbacks) {\n const { promise: end, resolve } = withResolvers<void>();\n\n this.outgoingRequests.push({\n id: String(message.id),\n message,\n end,\n callbacks: {\n next: callbacks.next,\n complete: () => {\n callbacks.complete();\n resolve();\n },\n error: (e) => {\n callbacks.error(e);\n resolve();\n },\n },\n });\n\n return () => {\n this.delete(message.id);\n callbacks.complete();\n resolve();\n };\n }\n\n /**\n * Deletes a request from both the outgoing and pending collections, if it exists.\n */\n public delete(messageId: MessageIdLike) {\n if (messageId === null) return;\n\n this.outgoingRequests = this.outgoingRequests.filter(\n ({ id }) => id !== String(messageId),\n );\n delete this.pendingRequests[String(messageId)];\n }\n\n /**\n * Moves all outgoing requests to the pending state and clears the outgoing queue.\n *\n * The caller is expected to handle the actual sending of the requests\n * (e.g., sending them over the network) after this method is called.\n *\n * @returns The list of requests that were transitioned to the pending state.\n */\n public flush() {\n const requests = this.outgoingRequests;\n this.outgoingRequests = [];\n\n for (const request of requests) {\n this.pendingRequests[request.id] = request;\n }\n return requests;\n }\n\n /**\n * Retrieves all currently pending requests, which are in flight awaiting responses\n * or handling ongoing subscriptions.\n */\n public getPendingRequests() {\n return Object.values(this.pendingRequests);\n }\n\n /**\n * Retrieves a specific pending request by its message ID.\n */\n public getPendingRequest(messageId: MessageIdLike) {\n if (messageId === null) return null;\n\n return this.pendingRequests[String(messageId)];\n }\n\n /**\n * Retrieves all outgoing requests, which are waiting to be sent.\n */\n public getOutgoingRequests() {\n return this.outgoingRequests;\n }\n\n /**\n * Retrieves all requests, both outgoing and pending, with their respective states.\n *\n * @returns An array of all requests with their state (\"outgoing\" or \"pending\").\n */\n public getRequests() {\n return [\n ...this.getOutgoingRequests().map((request) => ({\n state: 'outgoing' as const,\n message: request.message,\n end: request.end,\n callbacks: request.callbacks,\n })),\n ...this.getPendingRequests().map((request) => ({\n state: 'pending' as const,\n message: request.message,\n end: request.end,\n callbacks: request.callbacks,\n })),\n ];\n }\n\n /**\n * Checks if there are any pending requests, including ongoing subscriptions.\n */\n public hasPendingRequests() {\n return this.getPendingRequests().length > 0;\n }\n\n /**\n * Checks if there are any pending subscriptions\n */\n public hasPendingSubscriptions() {\n return this.getPendingRequests().some(\n (request) => request.message.method === 'subscription',\n );\n }\n\n /**\n * Checks if there are any outgoing requests waiting to be sent.\n */\n public hasOutgoingRequests() {\n return this.outgoingRequests.length > 0;\n }\n}\n","import type { AnyRouter, ProcedureType } from '@trpc/server';\nimport { observable } from '@trpc/server/observable';\nimport { transformResult } from '@trpc/server/unstable-core-do-not-import';\nimport type { BatchLoader } from '../internals/dataLoader';\nimport { dataLoader } from '../internals/dataLoader';\nimport { allAbortSignals, raceAbortSignals } from '../internals/signals';\nimport type { NonEmptyArray } from '../internals/types';\nimport { TRPCClientError } from '../TRPCClientError';\nimport type { HTTPBatchLinkOptions } from './HTTPBatchLinkOptions';\nimport type { HTTPResult } from './internals/httpUtils';\nimport {\n getUrl,\n jsonHttpRequester,\n resolveHTTPLinkOptions,\n} from './internals/httpUtils';\nimport type { Operation, TRPCLink } from './types';\n\n/**\n * @see https://trpc.io/docs/client/links/httpBatchLink\n */\nexport function httpBatchLink<TRouter extends AnyRouter>(\n opts: HTTPBatchLinkOptions<TRouter['_def']['_config']['$types']>,\n): TRPCLink<TRouter> {\n const resolvedOpts = resolveHTTPLinkOptions(opts);\n const maxURLLength = opts.maxURLLength ?? Infinity;\n const maxItems = opts.maxItems ?? Infinity;\n\n return () => {\n const batchLoader = (\n type: ProcedureType,\n ): BatchLoader<Operation, HTTPResult> => {\n return {\n validate(batchOps) {\n if (maxURLLength === Infinity && maxItems === Infinity) {\n // escape hatch for quick calcs\n return true;\n }\n if (batchOps.length > maxItems) {\n return false;\n }\n const path = batchOps.map((op) => op.path).join(',');\n const inputs = batchOps.map((op) => op.input);\n\n const url = getUrl({\n ...resolvedOpts,\n type,\n path,\n inputs,\n signal: null,\n });\n\n return url.length <= maxURLLength;\n },\n async fetch(batchOps) {\n const path = batchOps.map((op) => op.path).join(',');\n const inputs = batchOps.map((op) => op.input);\n const signal = allAbortSignals(...batchOps.map((op) => op.signal));\n\n const res = await jsonHttpRequester({\n ...resolvedOpts,\n path,\n inputs,\n type,\n headers() {\n if (!opts.headers) {\n return {};\n }\n if (typeof opts.headers === 'function') {\n return opts.headers({\n opList: batchOps as NonEmptyArray<Operation>,\n });\n }\n return opts.headers;\n },\n signal,\n });\n const resJSON = Array.isArray(res.json)\n ? res.json\n : batchOps.map(() => res.json);\n const result = resJSON.map((item) => ({\n meta: res.meta,\n json: item,\n }));\n return result;\n },\n };\n };\n\n const query = dataLoader(batchLoader('query'));\n const mutation = dataLoader(batchLoader('mutation'));\n\n const loaders = { query, mutation };\n return ({ op }) => {\n return observable((observer) => {\n /* istanbul ignore if -- @preserve */\n if (op.type === 'subscription') {\n throw new Error(\n 'Subscriptions are unsupported by `httpLink` - use `httpSubscriptionLink` or `wsLink`',\n );\n }\n const ac = new AbortController();\n const loader = loaders[op.type];\n const promise = loader.load({\n ...op,\n signal: raceAbortSignals(op.signal, ac.signal),\n });\n\n let isDone = false;\n let _res = undefined as HTTPResult | undefined;\n promise\n .then((res) => {\n isDone = true;\n _res = res;\n const transformed = transformResult(\n res.json,\n resolvedOpts.transformer.output,\n );\n\n if (!transformed.ok) {\n observer.error(\n TRPCClientError.from(transformed.error, {\n meta: res.meta,\n }),\n );\n return;\n }\n observer.next({\n context: res.meta,\n result: transformed.result,\n });\n observer.complete();\n })\n .catch((err) => {\n isDone = true;\n observer.error(\n TRPCClientError.from(err, {\n meta: _res?.meta,\n }),\n );\n });\n\n return () => {\n if (!isDone) {\n ac.abort();\n }\n };\n });\n };\n };\n}\n","import type { Observable } from '../observable';\nimport { createRecursiveProxy } from './createProxy';\nimport { defaultFormatter } from './error/formatter';\nimport { getTRPCErrorFromUnknown, TRPCError } from './error/TRPCError';\nimport type {\n AnyProcedure,\n ErrorHandlerOptions,\n inferProcedureInput,\n inferProcedureOutput,\n LegacyObservableSubscriptionProcedure,\n} from './procedure';\nimport type { ProcedureCallOptions } from './procedureBuilder';\nimport type { AnyRootTypes, RootConfig } from './rootConfig';\nimport { defaultTransformer } from './transformer';\nimport type { MaybePromise, ValueOf } from './types';\nimport {\n emptyObject,\n isFunction,\n isObject,\n mergeWithoutOverrides,\n} from './utils';\n\nexport interface RouterRecord {\n [key: string]: AnyProcedure | RouterRecord;\n}\n\ntype DecorateProcedure<TProcedure extends AnyProcedure> = (\n input: inferProcedureInput<TProcedure>,\n) => Promise<\n TProcedure['_def']['type'] extends 'subscription'\n ? TProcedure extends LegacyObservableSubscriptionProcedure<any>\n ? Observable<inferProcedureOutput<TProcedure>, TRPCError>\n : inferProcedureOutput<TProcedure>\n : inferProcedureOutput<TProcedure>\n>;\n\n/**\n * @internal\n */\nexport type DecorateRouterRecord<TRecord extends RouterRecord> = {\n [TKey in keyof TRecord]: TRecord[TKey] extends infer $Value\n ? $Value extends AnyProcedure\n ? DecorateProcedure<$Value>\n : $Value extends RouterRecord\n ? DecorateRouterRecord<$Value>\n : never\n : never;\n};\n\n/**\n * @internal\n */\n\nexport type RouterCallerErrorHandler<TContext> = (\n opts: ErrorHandlerOptions<TContext>,\n) => void;\n\n/**\n * @internal\n */\nexport type RouterCaller<\n TRoot extends AnyRootTypes,\n TRecord extends RouterRecord,\n> = (\n /**\n * @note\n * If passing a function, we recommend it's a cached function\n * e.g. wrapped in `React.cache` to avoid unnecessary computations\n */\n ctx: TRoot['ctx'] | (() => MaybePromise<TRoot['ctx']>),\n options?: {\n onError?: RouterCallerErrorHandler<TRoot['ctx']>;\n signal?: AbortSignal;\n },\n) => DecorateRouterRecord<TRecord>;\n\n/**\n * @internal\n */\nconst lazyMarker = 'lazyMarker' as 'lazyMarker' & {\n __brand: 'lazyMarker';\n};\nexport type Lazy<TAny> = (() => Promise<TAny>) & { [lazyMarker]: true };\n\ntype LazyLoader<TAny> = {\n load: () => Promise<void>;\n ref: Lazy<TAny>;\n};\n\nfunction once<T>(fn: () => T): () => T {\n const uncalled = Symbol();\n let result: T | typeof uncalled = uncalled;\n return (): T => {\n if (result === uncalled) {\n result = fn();\n }\n return result;\n };\n}\n\n/**\n * Lazy load a router\n * @see https://trpc.io/docs/server/merging-routers#lazy-load\n */\nexport function lazy<TRouter extends AnyRouter>(\n importRouter: () => Promise<\n | TRouter\n | {\n [key: string]: TRouter;\n }\n >,\n): Lazy<NoInfer<TRouter>> {\n async function resolve(): Promise<TRouter> {\n const mod = await importRouter();\n\n // if the module is a router, return it\n if (isRouter(mod)) {\n return mod;\n }\n\n const routers = Object.values(mod);\n\n if (routers.length !== 1 || !isRouter(routers[0])) {\n throw new Error(\n \"Invalid router module - either define exactly 1 export or return the router directly.\\nExample: `lazy(() => import('./slow.js').then((m) => m.slowRouter))`\",\n );\n }\n\n return routers[0];\n }\n\n (resolve as Lazy<NoInfer<TRouter>>)[lazyMarker] = true as const;\n\n return resolve as Lazy<NoInfer<TRouter>>;\n}\n\nfunction isLazy<TAny>(input: unknown): input is Lazy<TAny> {\n return typeof input === 'function' && lazyMarker in input;\n}\n\n/**\n * @internal\n */\nexport interface RouterDef<\n TRoot extends AnyRootTypes,\n TRecord extends RouterRecord,\n> {\n _config: RootConfig<TRoot>;\n router: true;\n procedure?: never;\n procedures: TRecord;\n record: TRecord;\n lazy: Record<string, LazyLoader<AnyRouter>>;\n}\n\nexport interface Router<\n TRoot extends AnyRootTypes,\n TRecord extends RouterRecord,\n> {\n _def: RouterDef<TRoot, TRecord>;\n /**\n * @see https://trpc.io/docs/v11/server/server-side-calls\n */\n createCaller: RouterCaller<TRoot, TRecord>;\n}\n\nexport type BuiltRouter<\n TRoot extends AnyRootTypes,\n TRecord extends RouterRecord,\n> = Router<TRoot, TRecord> & TRecord;\n\nexport interface RouterBuilder<TRoot extends AnyRootTypes> {\n <TIn extends CreateRouterOptions>(\n _: TIn,\n ): BuiltRouter<TRoot, DecorateCreateRouterOptions<TIn>>;\n}\n\nexport type AnyRouter = Router<any, any>;\n\nexport type inferRouterRootTypes<TRouter extends AnyRouter> =\n TRouter['_def']['_config']['$types'];\n\nexport type inferRouterContext<TRouter extends AnyRouter> =\n inferRouterRootTypes<TRouter>['ctx'];\nexport type inferRouterError<TRouter extends AnyRouter> =\n inferRouterRootTypes<TRouter>['errorShape'];\nexport type inferRouterMeta<TRouter extends AnyRouter> =\n inferRouterRootTypes<TRouter>['meta'];\n\nfunction isRouter(value: unknown): value is AnyRouter {\n return (\n isObject(value) && isObject(value['_def']) && 'router' in value['_def']\n );\n}\n\nconst emptyRouter = {\n _ctx: null as any,\n _errorShape: null as any,\n _meta: null as any,\n queries: {},\n mutations: {},\n subscriptions: {},\n errorFormatter: defaultFormatter,\n transformer: defaultTransformer,\n};\n\n/**\n * Reserved words that can't be used as router or procedure names\n */\nconst reservedWords = [\n /**\n * Then is a reserved word because otherwise we can't return a promise that returns a Proxy\n * since JS will think that `.then` is something that exists\n */\n 'then',\n /**\n * `fn.call()` and `fn.apply()` are reserved words because otherwise we can't call a function using `.call` or `.apply`\n */\n 'call',\n 'apply',\n];\n\n/** @internal */\nexport type CreateRouterOptions = {\n [key: string]:\n AnyProcedure | AnyRouter | CreateRouterOptions | Lazy<AnyRouter>;\n};\n\n/** @internal */\nexport type DecorateCreateRouterOptions<\n TRouterOptions extends CreateRouterOptions,\n> = {\n [K in keyof TRouterOptions]: TRouterOptions[K] extends infer $Value\n ? $Value extends AnyProcedure\n ? $Value\n : $Value extends Router<any, infer TRecord>\n ? TRecord\n : $Value extends Lazy<Router<any, infer TRecord>>\n ? TRecord\n : $Value extends CreateRouterOptions\n ? DecorateCreateRouterOptions<$Value>\n : never\n : never;\n};\n\n/**\n * @internal\n */\nexport function createRouterFactory<TRoot extends AnyRootTypes>(\n config: RootConfig<TRoot>,\n) {\n function createRouterInner<TInput extends CreateRouterOptions>(\n input: TInput,\n ): BuiltRouter<TRoot, DecorateCreateRouterOptions<TInput>> {\n const reservedWordsUsed = new Set(\n Object.keys(input).filter((v) => reservedWords.includes(v)),\n );\n if (reservedWordsUsed.size > 0) {\n throw new Error(\n 'Reserved words used in `router({})` call: ' +\n Array.from(reservedWordsUsed).join(', '),\n );\n }\n\n const procedures: Record<string, AnyProcedure> = emptyObject();\n const lazy: Record<string, LazyLoader<AnyRouter>> = emptyObject();\n\n function createLazyLoader(opts: {\n ref: Lazy<AnyRouter>;\n path: readonly string[];\n key: string;\n aggregate: RouterRecord;\n }): LazyLoader<AnyRouter> {\n return {\n ref: opts.ref,\n load: once(async () => {\n const router = await opts.ref();\n const lazyPath = [...opts.path, opts.key];\n const lazyKey = lazyPath.join('.');\n\n opts.aggregate[opts.key] = step(router._def.record, lazyPath);\n\n delete lazy[lazyKey];\n\n // add lazy loaders for nested routers\n for (const [nestedKey, nestedItem] of Object.entries(\n router._def.lazy,\n )) {\n const nestedRouterKey = [...lazyPath, nestedKey].join('.');\n\n // console.log('adding lazy', nestedRouterKey);\n lazy[nestedRouterKey] = createLazyLoader({\n ref: nestedItem.ref,\n path: lazyPath,\n key: nestedKey,\n aggregate: opts.aggregate[opts.key] as RouterRecord,\n });\n }\n }),\n };\n }\n\n function step(from: CreateRouterOptions, path: readonly string[] = []) {\n const aggregate: RouterRecord = emptyObject();\n for (const [key, item] of Object.entries(from ?? {})) {\n if (isLazy(item)) {\n lazy[[...path, key].join('.')] = createLazyLoader({\n path,\n ref: item,\n key,\n aggregate,\n });\n continue;\n }\n if (isRouter(item)) {\n aggregate[key] = step(item._def.record, [...path, key]);\n continue;\n }\n if (!isProcedure(item)) {\n // RouterRecord\n aggregate[key] = step(item, [...path, key]);\n continue;\n }\n\n const newPath = [...path, key].join('.');\n\n if (procedures[newPath]) {\n throw new Error(`Duplicate key: ${newPath}`);\n }\n\n procedures[newPath] = item;\n aggregate[key] = item;\n }\n\n return aggregate;\n }\n const record = step(input);\n\n const _def: AnyRouter['_def'] = {\n _config: config,\n router: true,\n procedures,\n lazy,\n ...emptyRouter,\n record,\n };\n\n const router: BuiltRouter<TRoot, {}> = {\n ...(record as {}),\n _def,\n createCaller: createCallerFactory<TRoot>()({\n _def,\n }),\n };\n return router as BuiltRouter<TRoot, DecorateCreateRouterOptions<TInput>>;\n }\n\n return createRouterInner;\n}\n\nfunction isProcedure(\n procedureOrRouter: ValueOf<CreateRouterOptions>,\n): procedureOrRouter is AnyProcedure {\n return typeof procedureOrRouter === 'function';\n}\n\n/**\n * @internal\n */\nexport async function getProcedureAtPath(\n router: Pick<Router<any, any>, '_def'>,\n path: string,\n): Promise<AnyProcedure | null> {\n const { _def } = router;\n let procedure = _def.procedures[path];\n\n while (!procedure) {\n const key = Object.keys(_def.lazy).find(\n (key) => path === key || path.startsWith(key + '.'),\n );\n // console.log(`found lazy: ${key ?? 'NOPE'} (fullPath: ${fullPath})`);\n\n if (!key) {\n return null;\n }\n // console.log('loading', key, '.......');\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const lazyRouter = _def.lazy[key]!;\n await lazyRouter.load();\n\n procedure = _def.procedures[path];\n }\n\n return procedure;\n}\n\n/**\n * @internal\n */\nexport async function callProcedure(\n opts: ProcedureCallOptions<unknown> & {\n router: AnyRouter;\n allowMethodOverride?: boolean;\n },\n) {\n const { type, path } = opts;\n const proc = await getProcedureAtPath(opts.router, path);\n if (\n !proc ||\n !isProcedure(proc) ||\n (proc._def.type !== type && !opts.allowMethodOverride)\n ) {\n throw new TRPCError({\n code: 'NOT_FOUND',\n message: `No \"${type}\"-procedure on path \"${path}\"`,\n });\n }\n\n /* istanbul ignore if -- @preserve */\n if (\n proc._def.type !== type &&\n opts.allowMethodOverride &&\n proc._def.type === 'subscription'\n ) {\n throw new TRPCError({\n code: 'METHOD_NOT_SUPPORTED',\n message: `Method override is not supported for subscriptions`,\n });\n }\n\n return proc(opts);\n}\n\nexport interface RouterCallerFactory<TRoot extends AnyRootTypes> {\n <TRecord extends RouterRecord>(\n router: Pick<Router<TRoot, TRecord>, '_def'>,\n ): RouterCaller<TRoot, TRecord>;\n}\n\nexport function createCallerFactory<\n TRoot extends AnyRootTypes,\n>(): RouterCallerFactory<TRoot> {\n return function createCallerInner<TRecord extends RouterRecord>(\n router: Pick<Router<TRoot, TRecord>, '_def'>,\n ): RouterCaller<TRoot, TRecord> {\n const { _def } = router;\n type Context = TRoot['ctx'];\n\n return function createCaller(ctxOrCallback, opts) {\n return createRecursiveProxy<ReturnType<RouterCaller<any, any>>>(\n async (innerOpts) => {\n const { path, args } = innerOpts;\n const fullPath = path.join('.');\n\n if (path.length === 1 && path[0] === '_def') {\n return _def;\n }\n\n const procedure = await getProcedureAtPath(router, fullPath);\n\n let ctx: Context | undefined = undefined;\n try {\n if (!procedure) {\n throw new TRPCError({\n code: 'NOT_FOUND',\n message: `No procedure found on path \"${path}\"`,\n });\n }\n ctx = isFunction(ctxOrCallback)\n ? await Promise.resolve(ctxOrCallback())\n : ctxOrCallback;\n\n return await procedure({\n path: fullPath,\n getRawInput: async () => args[0],\n ctx,\n type: procedure._def.type,\n signal: opts?.signal,\n batchIndex: 0,\n });\n } catch (cause) {\n opts?.onError?.({\n ctx,\n error: getTRPCErrorFromUnknown(cause),\n input: args[0],\n path: fullPath,\n type: procedure?._def.type ?? 'unknown',\n });\n throw cause;\n }\n },\n );\n };\n };\n}\n\n/** @internal */\nexport type MergeRouters<\n TRouters extends AnyRouter[],\n TRoot extends AnyRootTypes = TRouters[0]['_def']['_config']['$types'],\n TRecord extends RouterRecord = {},\n> = TRouters extends [\n infer Head extends AnyRouter,\n ...infer Tail extends AnyRouter[],\n]\n ? MergeRouters<Tail, TRoot, Head['_def']['record'] & TRecord>\n : BuiltRouter<TRoot, TRecord>;\n\nexport function mergeRouters<TRouters extends AnyRouter[]>(\n ...routerList: [...TRouters]\n): MergeRouters<TRouters> {\n const record = mergeWithoutOverrides(\n {},\n ...routerList.map((r) => r._def.record),\n );\n const errorFormatter = routerList.reduce(\n (currentErrorFormatter, nextRouter) => {\n if (\n nextRouter._def._config.errorFormatter &&\n nextRouter._def._config.errorFormatter !== defaultFormatter\n ) {\n if (\n currentErrorFormatter !== defaultFormatter &&\n currentErrorFormatter !== nextRouter._def._config.errorFormatter\n ) {\n throw new Error('You seem to have several error formatters');\n }\n return nextRouter._def._config.errorFormatter;\n }\n return currentErrorFormatter;\n },\n defaultFormatter,\n );\n\n const transformer = routerList.reduce((prev, current) => {\n if (\n current._def._config.transformer &&\n current._def._config.transformer !== defaultTransformer\n ) {\n if (\n prev !== defaultTransformer &&\n prev !== current._def._config.transformer\n ) {\n throw new Error('You seem to have several transformers');\n }\n return current._def._config.transformer;\n }\n return prev;\n }, defaultTransformer);\n\n const router = createRouterFactory({\n errorFormatter,\n transformer,\n isDev: routerList.every((r) => r._def._config.isDev),\n allowOutsideOfServer: routerList.every(\n (r) => r._def._config.allowOutsideOfServer,\n ),\n isServer: routerList.every((r) => r._def._config.isServer),\n $types: routerList[0]?._def._config.$types,\n sse: routerList[0]?._def._config.sse,\n })(record);\n\n return router as MergeRouters<TRouters>;\n}\n","import { observable } from './observable';\nimport type { Observable, Observer } from './types';\n\nexport interface BehaviorSubject<TValue> extends Observable<TValue, never> {\n observable: Observable<TValue, never>;\n next: (value: TValue) => void;\n get: () => TValue;\n}\n\nexport interface ReadonlyBehaviorSubject<TValue> extends Omit<\n BehaviorSubject<TValue>,\n 'next'\n> {}\n\n/**\n * @internal\n * An observable that maintains and provides a \"current value\" to subscribers\n * @see https://www.learnrxjs.io/learn-rxjs/subjects/behaviorsubject\n */\nexport function behaviorSubject<TValue>(\n initialValue: TValue,\n): BehaviorSubject<TValue> {\n let value: TValue = initialValue;\n\n const observerList: Observer<TValue, never>[] = [];\n\n const addObserver = (observer: Observer<TValue, never>) => {\n if (value !== undefined) {\n observer.next(value);\n }\n observerList.push(observer);\n };\n const removeObserver = (observer: Observer<TValue, never>) => {\n observerList.splice(observerList.indexOf(observer), 1);\n };\n\n const obs = observable<TValue, never>((observer) => {\n addObserver(observer);\n return () => {\n removeObserver(observer);\n };\n }) as BehaviorSubject<TValue>;\n\n obs.next = (nextValue: TValue) => {\n if (value === nextValue) {\n return;\n }\n value = nextValue;\n for (const observer of observerList) {\n observer.next(nextValue);\n }\n };\n\n obs.get = () => value;\n\n return obs;\n}\n","import type { AnyRouter, ProcedureType } from '@trpc/server';\nimport { observable } from '@trpc/server/observable';\nimport type { TRPCErrorShape, TRPCResponse } from '@trpc/server/rpc';\nimport type { AnyClientTypes } from '@trpc/server/unstable-core-do-not-import';\nimport { jsonlStreamConsumer } from '@trpc/server/unstable-core-do-not-import';\nimport type { BatchLoader } from '../internals/dataLoader';\nimport { dataLoader } from '../internals/dataLoader';\nimport { allAbortSignals, raceAbortSignals } from '../internals/signals';\nimport type { NonEmptyArray } from '../internals/types';\nimport { TRPCClientError } from '../TRPCClientError';\nimport type { HTTPBatchLinkOptions } from './HTTPBatchLinkOptions';\nimport type { HTTPResult } from './internals/httpUtils';\nimport {\n fetchHTTPResponse,\n getBody,\n getUrl,\n resolveHTTPLinkOptions,\n} from './internals/httpUtils';\nimport type { Operation, TRPCLink } from './types';\n\nexport type HTTPBatchStreamLinkOptions<TRoot extends AnyClientTypes> =\n HTTPBatchLinkOptions<TRoot> & {\n /**\n * Which header to use to signal the server that the client wants a streaming response.\n * - `'trpc-accept'` (default): sends `trpc-accept: application/jsonl` header\n * - `'accept'`: sends `Accept: application/jsonl` header, which can avoid CORS preflight for cross-origin streaming queries. Be aware that `application/jsonl` is not an official MIME type and so this is not completely spec-compliant - you should test that your infrastructure supports this value.\n * @default 'trpc-accept'\n */\n streamHeader?: 'trpc-accept' | 'accept';\n };\n\n/**\n * @see https://trpc.io/docs/client/links/httpBatchStreamLink\n */\nexport function httpBatchStreamLink<TRouter extends AnyRouter>(\n opts: HTTPBatchStreamLinkOptions<TRouter['_def']['_config']['$types']>,\n): TRPCLink<TRouter> {\n const resolvedOpts = resolveHTTPLinkOptions(opts);\n const maxURLLength = opts.maxURLLength ?? Infinity;\n const maxItems = opts.maxItems ?? Infinity;\n\n return () => {\n const batchLoader = (\n type: ProcedureType,\n ): BatchLoader<Operation, HTTPResult> => {\n return {\n validate(batchOps) {\n if (maxURLLength === Infinity && maxItems === Infinity) {\n // escape hatch for quick calcs\n return true;\n }\n if (batchOps.length > maxItems) {\n return false;\n }\n const path = batchOps.map((op) => op.path).join(',');\n const inputs = batchOps.map((op) => op.input);\n\n const url = getUrl({\n ...resolvedOpts,\n type,\n path,\n inputs,\n signal: null,\n });\n\n return url.length <= maxURLLength;\n },\n async fetch(batchOps) {\n const path = batchOps.map((op) => op.path).join(',');\n const inputs = batchOps.map((op) => op.input);\n\n const batchSignals = allAbortSignals(\n ...batchOps.map((op) => op.signal),\n );\n const abortController = new AbortController();\n\n const responsePromise = fetchHTTPResponse({\n ...resolvedOpts,\n signal: raceAbortSignals(batchSignals, abortController.signal),\n type,\n contentTypeHeader: 'application/json',\n trpcAcceptHeader: 'application/jsonl',\n trpcAcceptHeaderKey: opts.streamHeader ?? 'trpc-accept',\n getUrl,\n getBody,\n inputs,\n path,\n headers() {\n if (!opts.headers) {\n return {};\n }\n if (typeof opts.headers === 'function') {\n return opts.headers({\n opList: batchOps as NonEmptyArray<Operation>,\n });\n }\n return opts.headers;\n },\n });\n\n const res = await responsePromise;\n\n if (!res.ok) {\n // Server returned a non-2xx response (e.g. batching disabled).\n // The body is plain JSON, not JSONL, so parse it directly and\n // propagate the same error to every operation in the batch.\n const json = (await res.json()) as TRPCResponse;\n if ('error' in json) {\n json.error = resolvedOpts.transformer.output.deserialize(\n json.error,\n );\n }\n\n return batchOps.map((): Promise<HTTPResult> =>\n Promise.resolve({\n json,\n meta: {\n response: res,\n },\n }),\n );\n }\n\n const [head] = await jsonlStreamConsumer<\n Record<string, Promise<any>>\n >({\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n from: res.body!,\n deserialize: (data) =>\n resolvedOpts.transformer.output.deserialize(data),\n // onError: console.error,\n formatError(opts) {\n const error = opts.error as TRPCErrorShape;\n return TRPCClientError.from({\n error,\n });\n },\n abortController,\n });\n const promises = Object.keys(batchOps).map(\n async (key): Promise<HTTPResult> => {\n let json: TRPCResponse = await Promise.resolve(head[key]);\n\n if ('result' in json) {\n /**\n * Not very pretty, but we need to unwrap nested data as promises\n * Our stream producer will only resolve top-level async values or async values that are directly nested in another async value\n */\n const result = await Promise.resolve(json.result);\n json = {\n result: {\n data: await Promise.resolve(result.data),\n },\n };\n }\n\n return {\n json,\n meta: {\n response: res,\n },\n };\n },\n );\n return promises;\n },\n };\n };\n\n const query = dataLoader(batchLoader('query'));\n const mutation = dataLoader(batchLoader('mutation'));\n\n const loaders = { query, mutation };\n return ({ op }) => {\n return observable((observer) => {\n /* istanbul ignore if -- @preserve */\n if (op.type === 'subscription') {\n throw new Error(\n 'Subscriptions are unsupported by `httpBatchStreamLink` - use `httpSubscriptionLink` or `wsLink`',\n );\n }\n const ac = new AbortController();\n const loader = loaders[op.type];\n const promise = loader.load({\n ...op,\n signal: raceAbortSignals(op.signal, ac.signal),\n });\n\n let isDone = false;\n let _res = undefined as HTTPResult | undefined;\n promise\n .then((res) => {\n isDone = true;\n _res = res;\n if ('error' in res.json) {\n observer.error(\n TRPCClientError.from(res.json, {\n meta: res.meta,\n }),\n );\n return;\n } else if ('result' in res.json) {\n observer.next({\n context: res.meta,\n result: res.json.result,\n });\n observer.complete();\n return;\n }\n\n observer.complete();\n })\n .catch((err) => {\n isDone = true;\n observer.error(\n TRPCClientError.from(err, {\n meta: _res?.meta,\n }),\n );\n });\n\n return () => {\n if (!isDone) {\n ac.abort();\n }\n };\n });\n };\n };\n}\n\n/**\n * @deprecated use {@link httpBatchStreamLink} instead\n */\nexport const unstable_httpBatchStreamLink = httpBatchStreamLink;\n","import { getHTTPStatusCodeFromError } from '../http/getHTTPStatusCode';\nimport type { ProcedureType } from '../procedure';\nimport type { AnyRootTypes, RootConfig } from '../rootConfig';\nimport { TRPC_ERROR_CODES_BY_KEY } from '../rpc';\nimport type { DefaultErrorShape } from './formatter';\nimport type { TRPCError } from './TRPCError';\n\n/**\n * @internal\n */\nexport function getErrorShape<TRoot extends AnyRootTypes>(opts: {\n config: RootConfig<TRoot>;\n error: TRPCError;\n type: ProcedureType | 'unknown';\n path: string | undefined;\n input: unknown;\n ctx: TRoot['ctx'] | undefined;\n}): TRoot['errorShape'] {\n const { path, error, config } = opts;\n const { code } = opts.error;\n const shape: DefaultErrorShape = {\n message: error.message,\n code: TRPC_ERROR_CODES_BY_KEY[code],\n data: {\n code,\n httpStatus: getHTTPStatusCodeFromError(error),\n },\n };\n if (config.isDev && typeof opts.error.stack === 'string') {\n shape.data.stack = opts.error.stack;\n }\n if (typeof path === 'string') {\n shape.data.path = path;\n }\n return config.errorFormatter({ ...opts, shape });\n}\n","import { behaviorSubject } from '@trpc/server/observable';\nimport type { UrlOptionsWithConnectionParams } from '../../internals/urlWithConnectionParams';\nimport type { Encoder } from './encoder';\nimport { buildConnectionMessage, prepareUrl, withResolvers } from './utils';\n\n/**\n * Opens a WebSocket connection asynchronously and returns a promise\n * that resolves when the connection is successfully established.\n * The promise rejects if an error occurs during the connection attempt.\n */\nfunction asyncWsOpen(ws: WebSocket) {\n const { promise, resolve, reject } = withResolvers<void>();\n\n ws.addEventListener('open', () => {\n ws.removeEventListener('error', reject);\n resolve();\n });\n ws.addEventListener('error', reject);\n\n return promise;\n}\n\ninterface PingPongOptions {\n /**\n * The interval (in milliseconds) between \"PING\" messages.\n */\n intervalMs: number;\n\n /**\n * The timeout (in milliseconds) to wait for a \"PONG\" response before closing the connection.\n */\n pongTimeoutMs: number;\n}\n\n/**\n * Sets up a periodic ping-pong mechanism to keep the WebSocket connection alive.\n *\n * - Sends \"PING\" messages at regular intervals defined by `intervalMs`.\n * - If a \"PONG\" response is not received within the `pongTimeoutMs`, the WebSocket is closed.\n * - The ping timer resets upon receiving any message to maintain activity.\n * - Automatically starts the ping process when the WebSocket connection is opened.\n * - Cleans up timers when the WebSocket is closed.\n *\n * @param ws - The WebSocket instance to manage.\n * @param options - Configuration options for ping-pong intervals and timeouts.\n */\nfunction setupPingInterval(\n ws: WebSocket,\n { intervalMs, pongTimeoutMs }: PingPongOptions,\n) {\n let pingTimeout: ReturnType<typeof setTimeout> | undefined;\n let pongTimeout: ReturnType<typeof setTimeout> | undefined;\n\n function start() {\n pingTimeout = setTimeout(() => {\n ws.send('PING');\n pongTimeout = setTimeout(() => {\n ws.close();\n }, pongTimeoutMs);\n }, intervalMs);\n }\n\n function reset() {\n clearTimeout(pingTimeout);\n start();\n }\n\n function pong() {\n clearTimeout(pongTimeout);\n reset();\n }\n\n ws.addEventListener('open', start);\n ws.addEventListener('message', ({ data }) => {\n clearTimeout(pingTimeout);\n start();\n\n if (data === 'PONG') {\n pong();\n }\n });\n ws.addEventListener('close', () => {\n clearTimeout(pingTimeout);\n clearTimeout(pongTimeout);\n });\n}\n\nexport interface WebSocketConnectionOptions {\n WebSocketPonyfill?: typeof WebSocket;\n urlOptions: UrlOptionsWithConnectionParams;\n keepAlive: PingPongOptions & {\n enabled: boolean;\n };\n encoder: Encoder;\n}\n\n/**\n * Manages a WebSocket connection with support for reconnection, keep-alive mechanisms,\n * and observable state tracking.\n */\nexport class WsConnection {\n static connectCount = 0;\n public id = ++WsConnection.connectCount;\n\n private readonly WebSocketPonyfill: typeof WebSocket;\n private readonly urlOptions: UrlOptionsWithConnectionParams;\n private readonly keepAliveOpts: WebSocketConnectionOptions['keepAlive'];\n private readonly encoder: Encoder;\n public readonly wsObservable = behaviorSubject<WebSocket | null>(null);\n\n constructor(opts: WebSocketConnectionOptions) {\n this.WebSocketPonyfill = opts.WebSocketPonyfill ?? WebSocket;\n if (!this.WebSocketPonyfill) {\n throw new Error(\n \"No WebSocket implementation found - you probably don't want to use this on the server, but if you do you need to pass a `WebSocket`-ponyfill\",\n );\n }\n\n this.urlOptions = opts.urlOptions;\n this.keepAliveOpts = opts.keepAlive;\n this.encoder = opts.encoder;\n }\n\n public get ws() {\n return this.wsObservable.get();\n }\n\n private set ws(ws) {\n this.wsObservable.next(ws);\n }\n\n /**\n * Checks if the WebSocket connection is open and ready to communicate.\n */\n public isOpen(): this is { ws: WebSocket } {\n return (\n !!this.ws &&\n this.ws.readyState === this.WebSocketPonyfill.OPEN &&\n !this.openPromise\n );\n }\n\n /**\n * Checks if the WebSocket connection is closed or in the process of closing.\n */\n public isClosed(): this is { ws: WebSocket } {\n return (\n !!this.ws &&\n (this.ws.readyState === this.WebSocketPonyfill.CLOSING ||\n this.ws.readyState === this.WebSocketPonyfill.CLOSED)\n );\n }\n\n /**\n * Manages the WebSocket opening process, ensuring that only one open operation\n * occurs at a time. Tracks the ongoing operation with `openPromise` to avoid\n * redundant calls and ensure proper synchronization.\n *\n * Sets up the keep-alive mechanism and necessary event listeners for the connection.\n *\n * @returns A promise that resolves once the WebSocket connection is successfully opened.\n */\n private openPromise: Promise<void> | null = null;\n public async open() {\n if (this.openPromise) return this.openPromise;\n\n this.id = ++WsConnection.connectCount;\n const wsPromise = prepareUrl(this.urlOptions).then(\n (url) => new this.WebSocketPonyfill(url),\n );\n this.openPromise = wsPromise.then(async (ws) => {\n this.ws = ws;\n\n // Set binaryType to handle both text and binary messages consistently\n ws.binaryType = 'arraybuffer';\n\n // Setup ping listener\n ws.addEventListener('message', function ({ data }) {\n if (data === 'PING') {\n this.send('PONG');\n }\n });\n\n if (this.keepAliveOpts.enabled) {\n setupPingInterval(ws, this.keepAliveOpts);\n }\n\n ws.addEventListener('close', () => {\n if (this.ws === ws) {\n this.ws = null;\n }\n });\n\n await asyncWsOpen(ws);\n\n if (this.urlOptions.connectionParams) {\n ws.send(\n await buildConnectionMessage(\n this.urlOptions.connectionParams,\n this.encoder,\n ),\n );\n }\n });\n\n try {\n await this.openPromise;\n } finally {\n this.openPromise = null;\n }\n }\n\n /**\n * Closes the WebSocket connection gracefully.\n * Waits for any ongoing open operation to complete before closing.\n */\n public async close() {\n try {\n await this.openPromise;\n } finally {\n this.ws?.close();\n }\n }\n}\n\n/**\n * Provides a backward-compatible representation of the connection state.\n */\nexport function backwardCompatibility(connection: WsConnection) {\n if (connection.isOpen()) {\n return {\n id: connection.id,\n state: 'open',\n ws: connection.ws,\n } as const;\n }\n\n if (connection.isClosed()) {\n return {\n id: connection.id,\n state: 'closed',\n ws: connection.ws,\n } as const;\n }\n\n if (!connection.ws) {\n return null;\n }\n\n return {\n id: connection.id,\n state: 'connecting',\n ws: connection.ws,\n } as const;\n}\n","import { isObject } from '../utils';\n\nexport function isAbortError(\n error: unknown,\n): error is DOMException | Error | { name: 'AbortError' } {\n return isObject(error) && error['name'] === 'AbortError';\n}\n\nexport function throwAbortError(message = 'AbortError'): never {\n throw new DOMException(message, 'AbortError');\n}\n","/*!\n * is-plain-object <https://github.com/jonschlinkert/is-plain-object>\n *\n * Copyright (c) 2014-2017, Jon Schlinkert.\n * Released under the MIT License.\n */\n\nfunction isObject(o: unknown): o is Record<string, unknown> {\n return Object.prototype.toString.call(o) === '[object Object]';\n}\n \nexport function isPlainObject(o: unknown): o is Record<string, unknown> {\n var ctor,prot;\n\n if (isObject(o) === false) return false;\n\n // If has modified constructor\n ctor = o.constructor;\n if (ctor === undefined) return true;\n\n // If has modified prototype\n prot = ctor.prototype;\n if (isObject(prot) === false) return false;\n\n // If constructor does not have an Object-specific method\n if (prot.hasOwnProperty('isPrototypeOf') === false) {\n return false;\n }\n\n // Most likely a plain Object\n return true;\n};\n","export function inputWithTrackedEventId(\n input: unknown,\n lastEventId: string | undefined,\n) {\n if (!lastEventId) {\n return input;\n }\n if (input != null && typeof input !== 'object') {\n return input;\n }\n return {\n ...(input ?? {}),\n lastEventId,\n };\n}\n","/* eslint-disable @typescript-eslint/unbound-method */\n \n \n\nimport type {\n PromiseExecutor,\n PromiseWithResolvers,\n ProxyPromise,\n SubscribedPromise,\n} from \"./types\";\n\n/** Memory safe (weakmapped) cache of the ProxyPromise for each Promise,\n * which is retained for the lifetime of the original Promise.\n */\nconst subscribableCache = new WeakMap<\n PromiseLike<unknown>,\n ProxyPromise<unknown>\n>();\n\n/** A NOOP function allowing a consistent interface for settled\n * SubscribedPromises (settled promises are not subscribed - they resolve\n * immediately). */\nconst NOOP = () => {\n // noop\n};\n\n/**\n * Every `Promise<T>` can be shadowed by a single `ProxyPromise<T>`. It is\n * created once, cached and reused throughout the lifetime of the Promise. Get a\n * Promise's ProxyPromise using `Unpromise.proxy(promise)`.\n *\n * The `ProxyPromise<T>` attaches handlers to the original `Promise<T>`\n * `.then()` and `.catch()` just once. Promises derived from it use a\n * subscription- (and unsubscription-) based mechanism that monitors these\n * handlers.\n *\n * Every time you call `.subscribe()`, `.then()` `.catch()` or `.finally()` on a\n * `ProxyPromise<T>` it returns a `SubscribedPromise<T>` having an additional\n * `unsubscribe()` method. Calling `unsubscribe()` detaches reference chains\n * from the original, potentially long-lived Promise, eliminating memory leaks.\n *\n * This approach can eliminate the memory leaks that otherwise come about from\n * repeated `race()` or `any()` calls invoking `.then()` and `.catch()` multiple\n * times on the same long-lived native Promise (subscriptions which can never be\n * cleaned up).\n *\n * `Unpromise.race(promises)` is a reference implementation of `Promise.race`\n * avoiding memory leaks when using long-lived unsettled Promises.\n *\n * `Unpromise.any(promises)` is a reference implementation of `Promise.any`\n * avoiding memory leaks when using long-lived unsettled Promises.\n *\n * `Unpromise.resolve(promise)` returns an ephemeral `SubscribedPromise<T>` for\n * any given `Promise<T>` facilitating arbitrary async/await patterns. Behind\n * the scenes, `resolve` is implemented simply as\n * `Unpromise.proxy(promise).subscribe()`. Don't forget to call `.unsubscribe()`\n * to tidy up!\n *\n */\nexport class Unpromise<T> implements ProxyPromise<T> {\n /** INSTANCE IMPLEMENTATION */\n\n /** The promise shadowed by this Unpromise<T> */\n protected readonly promise: Promise<T> | PromiseLike<T>;\n\n /** Promises expecting eventual settlement (unless unsubscribed first). This list is deleted\n * after the original promise settles - no further notifications will be issued. */\n protected subscribers: ReadonlyArray<PromiseWithResolvers<T>> | null = [];\n\n /** The Promise's settlement (recorded when it fulfils or rejects). This is consulted when\n * calling .subscribe() .then() .catch() .finally() to see if an immediately-resolving Promise\n * can be returned, and therefore subscription can be bypassed. */\n protected settlement: PromiseSettledResult<T> | null = null;\n\n /** Constructor accepts a normal Promise executor function like `new\n * Unpromise((resolve, reject) => {...})` or accepts a pre-existing Promise\n * like `new Unpromise(existingPromise)`. Adds `.then()` and `.catch()`\n * handlers to the Promise. These handlers pass fulfilment and rejection\n * notifications to downstream subscribers and maintains records of value\n * or error if the Promise ever settles. */\n protected constructor(promise: Promise<T>);\n protected constructor(promise: PromiseLike<T>);\n protected constructor(executor: PromiseExecutor<T>);\n protected constructor(arg: Promise<T> | PromiseLike<T> | PromiseExecutor<T>) {\n // handle either a Promise or a Promise executor function\n if (typeof arg === \"function\") {\n this.promise = new Promise(arg);\n } else {\n this.promise = arg;\n }\n\n // subscribe for eventual fulfilment and rejection\n\n // handle PromiseLike objects (that at least have .then)\n const thenReturn = this.promise.then((value) => {\n // atomically record fulfilment and detach subscriber list\n const { subscribers } = this;\n this.subscribers = null;\n this.settlement = {\n status: \"fulfilled\",\n value,\n };\n // notify fulfilment to subscriber list\n subscribers?.forEach(({ resolve }) => {\n resolve(value);\n });\n });\n\n // handle Promise (that also have a .catch behaviour)\n if (\"catch\" in thenReturn) {\n thenReturn.catch((reason) => {\n // atomically record rejection and detach subscriber list\n const { subscribers } = this;\n this.subscribers = null;\n this.settlement = {\n status: \"rejected\",\n reason,\n };\n // notify rejection to subscriber list\n subscribers?.forEach(({ reject }) => {\n reject(reason);\n });\n });\n }\n }\n\n /** Create a promise that mitigates uncontrolled subscription to a long-lived\n * Promise via .then() and .catch() - otherwise a source of memory leaks.\n *\n * The returned promise has an `unsubscribe()` method which can be called when\n * the Promise is no longer being tracked by application logic, and which\n * ensures that there is no reference chain from the original promise to the\n * new one, and therefore no memory leak.\n *\n * If original promise has not yet settled, this adds a new unique promise\n * that listens to then/catch events, along with an `unsubscribe()` method to\n * detach it.\n *\n * If original promise has settled, then creates a new Promise.resolve() or\n * Promise.reject() and provided unsubscribe is a noop.\n *\n * If you call `unsubscribe()` before the returned Promise has settled, it\n * will never settle.\n */\n subscribe(): SubscribedPromise<T> {\n // in all cases we will combine some promise with its unsubscribe function\n let promise: Promise<T>;\n let unsubscribe: () => void;\n\n const { settlement } = this;\n if (settlement === null) {\n // not yet settled - subscribe new promise. Expect eventual settlement\n if (this.subscribers === null) {\n // invariant - it is not settled, so it must have subscribers\n throw new Error(\"Unpromise settled but still has subscribers\");\n }\n const subscriber = withResolvers<T>();\n this.subscribers = listWithMember(this.subscribers, subscriber);\n promise = subscriber.promise;\n unsubscribe = () => {\n if (this.subscribers !== null) {\n this.subscribers = listWithoutMember(this.subscribers, subscriber);\n }\n };\n } else {\n // settled - don't create subscribed promise. Just resolve or reject\n const { status } = settlement;\n if (status === \"fulfilled\") {\n promise = Promise.resolve(settlement.value);\n } else {\n promise = Promise.reject(settlement.reason);\n }\n unsubscribe = NOOP;\n }\n\n // extend promise signature with the extra method\n return Object.assign(promise, { unsubscribe });\n }\n\n /** STANDARD PROMISE METHODS (but returning a SubscribedPromise) */\n\n then<TResult1 = T, TResult2 = never>(\n onfulfilled?:\n | ((value: T) => TResult1 | PromiseLike<TResult1>)\n | null\n ,\n onrejected?:\n | ((reason: any) => TResult2 | PromiseLike<TResult2>)\n | null\n \n ): SubscribedPromise<TResult1 | TResult2> {\n const subscribed = this.subscribe();\n const { unsubscribe } = subscribed;\n return Object.assign(subscribed.then(onfulfilled, onrejected), {\n unsubscribe,\n });\n }\n\n catch<TResult = never>(\n onrejected?:\n | ((reason: any) => TResult | PromiseLike<TResult>)\n | null\n \n ): SubscribedPromise<T | TResult> {\n const subscribed = this.subscribe();\n const { unsubscribe } = subscribed;\n return Object.assign(subscribed.catch(onrejected), {\n unsubscribe,\n });\n }\n\n finally(onfinally?: (() => void) | null ): SubscribedPromise<T> {\n const subscribed = this.subscribe();\n const { unsubscribe } = subscribed;\n return Object.assign(subscribed.finally(onfinally), {\n unsubscribe,\n });\n }\n\n /** TOSTRING SUPPORT */\n\n readonly [Symbol.toStringTag] = \"Unpromise\";\n\n /** Unpromise STATIC METHODS */\n\n /** Create or Retrieve the proxy Unpromise (a re-used Unpromise for the VM lifetime\n * of the provided Promise reference) */\n static proxy<T>(promise: PromiseLike<T>): ProxyPromise<T> {\n const cached = Unpromise.getSubscribablePromise(promise);\n return typeof cached !== \"undefined\"\n ? cached\n : Unpromise.createSubscribablePromise(promise);\n }\n\n /** Create and store an Unpromise keyed by an original Promise. */\n protected static createSubscribablePromise<T>(promise: PromiseLike<T>) {\n const created = new Unpromise<T>(promise);\n subscribableCache.set(promise, created as Unpromise<unknown>); // resolve promise to unpromise\n subscribableCache.set(created, created as Unpromise<unknown>); // resolve the unpromise to itself\n return created;\n }\n\n /** Retrieve a previously-created Unpromise keyed by an original Promise. */\n protected static getSubscribablePromise<T>(promise: PromiseLike<T>) {\n return subscribableCache.get(promise) as ProxyPromise<T> | undefined;\n }\n\n /** Promise STATIC METHODS */\n\n /** Lookup the Unpromise for this promise, and derive a SubscribedPromise from\n * it (that can be later unsubscribed to eliminate Memory leaks) */\n static resolve<T>(value: T | PromiseLike<T>) {\n const promise: PromiseLike<T> =\n typeof value === \"object\" &&\n value !== null &&\n \"then\" in value &&\n typeof value.then === \"function\"\n ? value\n : Promise.resolve(value);\n return Unpromise.proxy(promise).subscribe() as SubscribedPromise<\n Awaited<T>\n >;\n }\n\n /** Perform Promise.any() via SubscribedPromises, then unsubscribe them.\n * Equivalent to Promise.any but eliminates memory leaks from long-lived\n * promises accumulating .then() and .catch() subscribers. */\n static async any<T extends readonly unknown[] | []>(\n values: T\n ): Promise<Awaited<T[number]>>;\n static async any<T>(\n values: Iterable<T | PromiseLike<T>>\n ): Promise<Awaited<T>> {\n const valuesArray = Array.isArray(values) ? values : [...values];\n const subscribedPromises = valuesArray.map(Unpromise.resolve);\n try {\n return await Promise.any(subscribedPromises);\n } finally {\n subscribedPromises.forEach(({ unsubscribe }) => {\n unsubscribe();\n });\n }\n }\n\n /** Perform Promise.race via SubscribedPromises, then unsubscribe them.\n * Equivalent to Promise.race but eliminates memory leaks from long-lived\n * promises accumulating .then() and .catch() subscribers. */\n static async race<T extends readonly unknown[] | []>(\n values: T\n ): Promise<Awaited<T[number]>>;\n static async race<T>(\n values: Iterable<T | PromiseLike<T>>\n ): Promise<Awaited<T>> {\n const valuesArray = Array.isArray(values) ? values : [...values];\n const subscribedPromises = valuesArray.map(Unpromise.resolve);\n try {\n return await Promise.race(subscribedPromises);\n } finally {\n subscribedPromises.forEach(({ unsubscribe }) => {\n unsubscribe();\n });\n }\n }\n\n /** Create a race of SubscribedPromises that will fulfil to a single winning\n * Promise (in a 1-Tuple). Eliminates memory leaks from long-lived promises\n * accumulating .then() and .catch() subscribers. Allows simple logic to\n * consume the result, like...\n * ```ts\n * const [ winner ] = await Unpromise.race([ promiseA, promiseB ]);\n * if(winner === promiseB){\n * const result = await promiseB;\n * // do the thing\n * }\n * ```\n * */\n static async raceReferences<TPromise extends Promise<unknown>>(\n promises: readonly TPromise[]\n ) {\n // map each promise to an eventual 1-tuple containing itself\n const selfPromises = promises.map(resolveSelfTuple);\n\n // now race them. They will fulfil to a readonly [P] or reject.\n try {\n return await Promise.race(selfPromises);\n } finally {\n for (const promise of selfPromises) {\n // unsubscribe proxy promises when the race is over to mitigate memory leaks\n promise.unsubscribe();\n }\n }\n }\n}\n\n/** Promises a 1-tuple containing the original promise when it resolves. Allows\n * awaiting the eventual Promise ***reference*** (easy to destructure and\n * exactly compare with ===). Avoids resolving to the Promise ***value*** (which\n * may be ambiguous and therefore hard to identify as the winner of a race).\n * You can call unsubscribe on the Promise to mitigate memory leaks.\n * */\nexport function resolveSelfTuple<TPromise extends Promise<unknown>>(\n promise: TPromise\n): SubscribedPromise<readonly [TPromise]> {\n return Unpromise.proxy(promise).then(() => [promise] as const);\n}\n\n/** VENDORED (Future) PROMISE UTILITIES */\n\n/** Reference implementation of https://github.com/tc39/proposal-promise-with-resolvers */\nfunction withResolvers<T>(): PromiseWithResolvers<T> {\n let resolve!: PromiseWithResolvers<T>[\"resolve\"];\n let reject!: PromiseWithResolvers<T>[\"reject\"];\n const promise = new Promise<T>((_resolve, _reject) => {\n resolve = _resolve;\n reject = _reject;\n });\n return {\n promise,\n resolve,\n reject,\n };\n}\n\n/** IMMUTABLE LIST OPERATIONS */\n\nfunction listWithMember<T>(arr: readonly T[], member: T): readonly T[] {\n return [...arr, member];\n}\n\nfunction listWithoutIndex<T>(arr: readonly T[], index: number) {\n return [...arr.slice(0, index), ...arr.slice(index + 1)];\n}\n\nfunction listWithoutMember<T>(arr: readonly T[], member: unknown) {\n const index = arr.indexOf(member as T);\n if (index !== -1) {\n return listWithoutIndex(arr, index);\n }\n return arr;\n}\n","import { behaviorSubject, observable } from '@trpc/server/observable';\nimport type { TRPCErrorShape, TRPCResult } from '@trpc/server/rpc';\nimport type {\n AnyClientTypes,\n EventSourceLike,\n inferClientTypes,\n InferrableClientTypes,\n} from '@trpc/server/unstable-core-do-not-import';\nimport {\n retryableRpcCodes,\n run,\n sseStreamConsumer,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { inputWithTrackedEventId } from '../internals/inputWithTrackedEventId';\nimport { raceAbortSignals } from '../internals/signals';\nimport { TRPCClientError } from '../TRPCClientError';\nimport type { TRPCConnectionState } from '../unstable-internals';\nimport { getTransformer, type TransformerOptions } from '../unstable-internals';\nimport { getUrl } from './internals/httpUtils';\nimport {\n resultOf,\n type UrlOptionsWithConnectionParams,\n} from './internals/urlWithConnectionParams';\nimport type { Operation, TRPCLink } from './types';\n\nasync function urlWithConnectionParams(\n opts: UrlOptionsWithConnectionParams,\n): Promise<string> {\n let url = await resultOf(opts.url);\n if (opts.connectionParams) {\n const params = await resultOf(opts.connectionParams);\n\n const prefix = url.includes('?') ? '&' : '?';\n url +=\n prefix + 'connectionParams=' + encodeURIComponent(JSON.stringify(params));\n }\n\n return url;\n}\n\ntype HTTPSubscriptionLinkOptions<\n TRoot extends AnyClientTypes,\n TEventSource extends EventSourceLike.AnyConstructor = typeof EventSource,\n> = {\n /**\n * EventSource ponyfill\n */\n EventSource?: TEventSource;\n /**\n * EventSource options or a callback that returns them\n */\n eventSourceOptions?:\n | EventSourceLike.InitDictOf<TEventSource>\n | ((opts: {\n op: Operation;\n }) =>\n | EventSourceLike.InitDictOf<TEventSource>\n | Promise<EventSourceLike.InitDictOf<TEventSource>>);\n} & TransformerOptions<TRoot> &\n UrlOptionsWithConnectionParams;\n\n/**\n * @see https://trpc.io/docs/client/links/httpSubscriptionLink\n */\nexport function httpSubscriptionLink<\n TInferrable extends InferrableClientTypes,\n TEventSource extends EventSourceLike.AnyConstructor,\n>(\n opts: HTTPSubscriptionLinkOptions<\n inferClientTypes<TInferrable>,\n TEventSource\n >,\n): TRPCLink<TInferrable> {\n const transformer = getTransformer(opts.transformer);\n\n return () => {\n return ({ op }) => {\n return observable((observer) => {\n const { type, path, input } = op;\n\n /* istanbul ignore if -- @preserve */\n if (type !== 'subscription') {\n throw new Error('httpSubscriptionLink only supports subscriptions');\n }\n\n let lastEventId: string | undefined = undefined;\n const ac = new AbortController();\n const signal = raceAbortSignals(op.signal, ac.signal);\n const eventSourceStream = sseStreamConsumer<{\n EventSource: TEventSource;\n data: Partial<{\n id?: string;\n data: unknown;\n }>;\n error: TRPCErrorShape;\n }>({\n url: async () =>\n getUrl({\n transformer,\n url: await urlWithConnectionParams(opts),\n input: inputWithTrackedEventId(input, lastEventId),\n path,\n type,\n signal: null,\n }),\n init: () => resultOf(opts.eventSourceOptions, { op }),\n signal,\n deserialize: (data) => transformer.output.deserialize(data),\n EventSource: opts.EventSource ?? (globalThis.EventSource as never),\n });\n\n const connectionState = behaviorSubject<\n TRPCConnectionState<TRPCClientError<any>>\n >({\n type: 'state',\n state: 'connecting',\n error: null,\n });\n\n const connectionSub = connectionState.subscribe({\n next(state) {\n observer.next({\n result: state,\n });\n },\n });\n run(async () => {\n for await (const chunk of eventSourceStream) {\n switch (chunk.type) {\n case 'ping':\n // do nothing\n break;\n case 'data':\n const chunkData = chunk.data;\n\n let result: TRPCResult<unknown>;\n if (chunkData.id) {\n // if the `tracked()`-helper is used, we always have an `id` field\n lastEventId = chunkData.id;\n result = {\n id: chunkData.id,\n data: chunkData,\n };\n } else {\n result = {\n data: chunkData.data,\n };\n }\n\n observer.next({\n result,\n context: {\n eventSource: chunk.eventSource,\n },\n });\n break;\n case 'connected': {\n observer.next({\n result: {\n type: 'started',\n },\n context: {\n eventSource: chunk.eventSource,\n },\n });\n connectionState.next({\n type: 'state',\n state: 'pending',\n error: null,\n });\n break;\n }\n case 'serialized-error': {\n const error = TRPCClientError.from({ error: chunk.error });\n\n if (retryableRpcCodes.includes(chunk.error.code)) {\n //\n connectionState.next({\n type: 'state',\n state: 'connecting',\n error,\n });\n break;\n }\n //\n // non-retryable error, cancel the subscription\n throw error;\n }\n case 'connecting': {\n const lastState = connectionState.get();\n\n const error = chunk.event && TRPCClientError.from(chunk.event);\n if (!error && lastState.state === 'connecting') {\n break;\n }\n\n connectionState.next({\n type: 'state',\n state: 'connecting',\n error,\n });\n break;\n }\n case 'timeout': {\n connectionState.next({\n type: 'state',\n state: 'connecting',\n error: new TRPCClientError(\n `Timeout of ${chunk.ms}ms reached while waiting for a response`,\n ),\n });\n }\n }\n }\n observer.next({\n result: {\n type: 'stopped',\n },\n });\n connectionState.next({\n type: 'state',\n state: 'idle',\n error: null,\n });\n observer.complete();\n }).catch((error) => {\n observer.error(TRPCClientError.from(error));\n });\n\n return () => {\n observer.complete();\n ac.abort();\n connectionSub.unsubscribe();\n };\n });\n };\n };\n}\n\n/**\n * @deprecated use {@link httpSubscriptionLink} instead\n */\nexport const unstable_httpSubscriptionLink = httpSubscriptionLink;\n","const trackedSymbol = Symbol();\n\ntype TrackedId = string & {\n __brand: 'TrackedId';\n};\nexport type TrackedEnvelope<TData> = [TrackedId, TData, typeof trackedSymbol];\n\nexport interface TrackedData<TData> {\n /**\n * The id of the message to keep track of in case the connection gets lost\n */\n id: string;\n /**\n * The data field of the message\n */\n data: TData;\n}\n/**\n * Produce a typed server-sent event message\n * @deprecated use `tracked(id, data)` instead\n */\nexport function sse<TData>(event: { id: string; data: TData }) {\n return tracked(event.id, event.data);\n}\n\nexport function isTrackedEnvelope<TData>(\n value: unknown,\n): value is TrackedEnvelope<TData> {\n return Array.isArray(value) && value[2] === trackedSymbol;\n}\n\n/**\n * Automatically track an event so that it can be resumed from a given id if the connection is lost\n */\nexport function tracked<TData>(\n id: string,\n data: TData,\n): TrackedEnvelope<TData> {\n if (id === '') {\n // This limitation could be removed by using different SSE event names / channels for tracked event and non-tracked event\n throw new Error(\n '`id` must not be an empty string as empty string is the same as not setting the id at all',\n );\n }\n return [id as TrackedId, data, trackedSymbol];\n}\n\nexport type inferTrackedOutput<TData> =\n TData extends TrackedEnvelope<infer $Data> ? TrackedData<$Data> : TData;\n","import type { AnyTRPCRouter } from '@trpc/server';\nimport type { BehaviorSubject } from '@trpc/server/observable';\nimport { behaviorSubject, observable } from '@trpc/server/observable';\nimport type {\n CombinedDataTransformer,\n TRPCClientIncomingMessage,\n TRPCClientIncomingRequest,\n TRPCClientOutgoingMessage,\n TRPCResponseMessage,\n} from '@trpc/server/unstable-core-do-not-import';\nimport {\n run,\n sleep,\n transformResult,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { TRPCClientError } from '../../../TRPCClientError';\nimport type { TRPCConnectionState } from '../../internals/subscriptions';\nimport type { Operation, OperationResultEnvelope } from '../../types';\nimport type { Encoder } from './encoder';\nimport { jsonEncoder } from './encoder';\nimport type { WebSocketClientOptions } from './options';\nimport { exponentialBackoff, keepAliveDefaults, lazyDefaults } from './options';\nimport type { TCallbacks } from './requestManager';\nimport { RequestManager } from './requestManager';\nimport { ResettableTimeout, TRPCWebSocketClosedError } from './utils';\nimport { backwardCompatibility, WsConnection } from './wsConnection';\n\n/**\n * A WebSocket client for managing TRPC operations, supporting lazy initialization,\n * reconnection, keep-alive, and request management.\n */\nexport class WsClient {\n /**\n * Observable tracking the current connection state, including errors.\n */\n public readonly connectionState: BehaviorSubject<\n TRPCConnectionState<TRPCClientError<AnyTRPCRouter>>\n >;\n\n private allowReconnect = false;\n private requestManager = new RequestManager();\n private readonly activeConnection: WsConnection;\n private readonly reconnectRetryDelay: (attemptIndex: number) => number;\n private inactivityTimeout: ResettableTimeout;\n private readonly callbacks: Pick<\n WebSocketClientOptions,\n 'onOpen' | 'onClose' | 'onError'\n >;\n private readonly lazyMode: boolean;\n private readonly encoder: Encoder;\n\n constructor(opts: WebSocketClientOptions) {\n this.encoder = opts.experimental_encoder ?? jsonEncoder;\n // Initialize callbacks, connection parameters, and options.\n this.callbacks = {\n onOpen: opts.onOpen,\n onClose: opts.onClose,\n onError: opts.onError,\n };\n\n const lazyOptions = {\n ...lazyDefaults,\n ...opts.lazy,\n };\n\n // Set up inactivity timeout for lazy connections.\n this.inactivityTimeout = new ResettableTimeout(() => {\n if (\n this.requestManager.hasOutgoingRequests() ||\n this.requestManager.hasPendingRequests()\n ) {\n this.inactivityTimeout.reset();\n return;\n }\n\n this.close().catch(() => null);\n }, lazyOptions.closeMs);\n\n // Initialize the WebSocket connection.\n this.activeConnection = new WsConnection({\n WebSocketPonyfill: opts.WebSocket,\n urlOptions: opts,\n keepAlive: {\n ...keepAliveDefaults,\n ...opts.keepAlive,\n },\n encoder: this.encoder,\n });\n this.activeConnection.wsObservable.subscribe({\n next: (ws) => {\n if (!ws) return;\n this.setupWebSocketListeners(ws);\n },\n });\n this.reconnectRetryDelay = opts.retryDelayMs ?? exponentialBackoff;\n\n this.lazyMode = lazyOptions.enabled;\n\n this.connectionState = behaviorSubject<\n TRPCConnectionState<TRPCClientError<AnyTRPCRouter>>\n >({\n type: 'state',\n state: lazyOptions.enabled ? 'idle' : 'connecting',\n error: null,\n });\n\n // Automatically open the connection if lazy mode is disabled.\n if (!this.lazyMode) {\n this.open().catch(() => null);\n }\n }\n\n /**\n * Opens the WebSocket connection. Handles reconnection attempts and updates\n * the connection state accordingly.\n */\n private async open() {\n this.allowReconnect = true;\n if (this.connectionState.get().state === 'idle') {\n this.connectionState.next({\n type: 'state',\n state: 'connecting',\n error: null,\n });\n }\n\n try {\n await this.activeConnection.open();\n } catch (error) {\n this.reconnect(\n new TRPCWebSocketClosedError({\n message: 'Initialization error',\n cause: error,\n }),\n );\n return this.reconnecting;\n }\n }\n\n /**\n * Closes the WebSocket connection and stops managing requests.\n * Ensures all outgoing and pending requests are properly finalized.\n */\n public async close() {\n this.allowReconnect = false;\n this.inactivityTimeout.stop();\n\n const requestsToAwait: Promise<void>[] = [];\n for (const request of this.requestManager.getRequests()) {\n if (request.message.method === 'subscription') {\n request.callbacks.complete();\n } else if (request.state === 'outgoing') {\n request.callbacks.error(\n TRPCClientError.from(\n new TRPCWebSocketClosedError({\n message: 'Closed before connection was established',\n }),\n ),\n );\n } else {\n requestsToAwait.push(request.end);\n }\n }\n\n await Promise.all(requestsToAwait).catch(() => null);\n await this.activeConnection.close().catch(() => null);\n\n this.connectionState.next({\n type: 'state',\n state: 'idle',\n error: null,\n });\n }\n\n /**\n * Method to request the server.\n * Handles data transformation, batching of requests, and subscription lifecycle.\n *\n * @param op - The operation details including id, type, path, input and signal\n * @param transformer - Data transformer for serializing requests and deserializing responses\n * @param lastEventId - Optional ID of the last received event for subscriptions\n *\n * @returns An observable that emits operation results and handles cleanup\n */\n public request({\n op: { id, type, path, input, signal },\n transformer,\n lastEventId,\n }: {\n op: Pick<Operation, 'id' | 'type' | 'path' | 'input' | 'signal'>;\n transformer: CombinedDataTransformer;\n lastEventId?: string;\n }) {\n return observable<\n OperationResultEnvelope<unknown, TRPCClientError<AnyTRPCRouter>>,\n TRPCClientError<AnyTRPCRouter>\n >((observer) => {\n const abort = this.batchSend(\n {\n id,\n method: type,\n params: {\n input: transformer.input.serialize(input),\n path,\n lastEventId,\n },\n },\n {\n ...observer,\n next(event) {\n const transformed = transformResult(event, transformer.output);\n\n if (!transformed.ok) {\n observer.error(TRPCClientError.from(transformed.error));\n return;\n }\n\n observer.next({\n result: transformed.result,\n });\n },\n },\n );\n\n const onAbort = () => observer.complete();\n if (signal?.aborted) {\n onAbort();\n } else {\n signal?.addEventListener('abort', onAbort, { once: true });\n }\n\n return () => {\n abort();\n\n if (type === 'subscription' && this.activeConnection.isOpen()) {\n this.send({\n id,\n method: 'subscription.stop',\n });\n }\n\n signal?.removeEventListener('abort', onAbort);\n };\n });\n }\n\n public get connection() {\n return backwardCompatibility(this.activeConnection);\n }\n\n /**\n * Manages the reconnection process for the WebSocket using retry logic.\n * Ensures that only one reconnection attempt is active at a time by tracking the current\n * reconnection state in the `reconnecting` promise.\n */\n private reconnecting: Promise<void> | null = null;\n private reconnect(closedError: TRPCWebSocketClosedError) {\n this.connectionState.next({\n type: 'state',\n state: 'connecting',\n error: TRPCClientError.from(closedError),\n });\n if (this.reconnecting) return;\n\n const tryReconnect = async (attemptIndex: number) => {\n try {\n await sleep(this.reconnectRetryDelay(attemptIndex));\n if (this.allowReconnect) {\n await this.activeConnection.close();\n await this.activeConnection.open();\n\n if (this.requestManager.hasPendingRequests()) {\n this.send(\n this.requestManager\n .getPendingRequests()\n .map(({ message }) => message),\n );\n }\n }\n this.reconnecting = null;\n } catch {\n await tryReconnect(attemptIndex + 1);\n }\n };\n\n this.reconnecting = tryReconnect(0);\n }\n\n private setupWebSocketListeners(ws: WebSocket) {\n const handleCloseOrError = (cause: unknown) => {\n const reqs = this.requestManager.getPendingRequests();\n for (const { message, callbacks } of reqs) {\n if (message.method === 'subscription') continue;\n\n callbacks.error(\n TRPCClientError.from(\n cause ??\n new TRPCWebSocketClosedError({\n message: 'WebSocket closed',\n cause,\n }),\n ),\n );\n this.requestManager.delete(message.id);\n }\n };\n\n ws.addEventListener('open', () => {\n run(async () => {\n if (this.lazyMode) {\n this.inactivityTimeout.start();\n }\n\n this.callbacks.onOpen?.();\n\n this.connectionState.next({\n type: 'state',\n state: 'pending',\n error: null,\n });\n }).catch((error) => {\n ws.close(3000);\n handleCloseOrError(error);\n });\n });\n\n ws.addEventListener('message', ({ data }) => {\n this.inactivityTimeout.reset();\n\n // Handle PING/PONG as text regardless of encoder\n if (['PING', 'PONG'].includes(data)) return;\n\n const incomingMessage = this.encoder.decode(\n data,\n ) as TRPCClientIncomingMessage;\n if ('method' in incomingMessage) {\n this.handleIncomingRequest(incomingMessage);\n return;\n }\n\n this.handleResponseMessage(incomingMessage);\n });\n\n ws.addEventListener('close', (event) => {\n handleCloseOrError(event);\n this.callbacks.onClose?.(event);\n\n if (!this.lazyMode || this.requestManager.hasPendingSubscriptions()) {\n this.reconnect(\n new TRPCWebSocketClosedError({\n message: 'WebSocket closed',\n cause: event,\n }),\n );\n }\n });\n\n ws.addEventListener('error', (event) => {\n handleCloseOrError(event);\n this.callbacks.onError?.(event);\n\n this.reconnect(\n new TRPCWebSocketClosedError({\n message: 'WebSocket closed',\n cause: event,\n }),\n );\n });\n }\n\n private handleResponseMessage(message: TRPCResponseMessage) {\n const request = this.requestManager.getPendingRequest(message.id);\n if (!request) return;\n\n request.callbacks.next(message);\n\n let completed = true;\n if ('result' in message && request.message.method === 'subscription') {\n if (message.result.type === 'data') {\n request.message.params.lastEventId = message.result.id;\n }\n\n if (message.result.type !== 'stopped') {\n completed = false;\n }\n }\n\n if (completed) {\n request.callbacks.complete();\n this.requestManager.delete(message.id);\n }\n }\n\n private handleIncomingRequest(message: TRPCClientIncomingRequest) {\n if (message.method === 'reconnect') {\n this.reconnect(\n new TRPCWebSocketClosedError({\n message: 'Server requested reconnect',\n }),\n );\n }\n }\n\n /**\n * Sends a message or batch of messages directly to the server.\n */\n private send(\n messageOrMessages: TRPCClientOutgoingMessage | TRPCClientOutgoingMessage[],\n ) {\n if (!this.activeConnection.isOpen()) {\n throw new Error('Active connection is not open');\n }\n\n const messages =\n messageOrMessages instanceof Array\n ? messageOrMessages\n : [messageOrMessages];\n this.activeConnection.ws.send(\n this.encoder.encode(messages.length === 1 ? messages[0] : messages),\n );\n }\n\n /**\n * Groups requests for batch sending.\n *\n * @returns A function to abort the batched request.\n */\n private batchSend(message: TRPCClientOutgoingMessage, callbacks: TCallbacks) {\n this.inactivityTimeout.reset();\n\n run(async () => {\n if (!this.activeConnection.isOpen()) {\n await this.open();\n }\n await sleep(0);\n\n if (!this.requestManager.hasOutgoingRequests()) return;\n\n this.send(this.requestManager.flush().map(({ message }) => message));\n }).catch((err) => {\n this.requestManager.delete(message.id);\n callbacks.error(TRPCClientError.from(err));\n });\n\n return this.requestManager.register(message, callbacks);\n }\n}\n","/* istanbul ignore file -- @preserve */\n// We're not actually exporting this link\nimport type { Unsubscribable } from '@trpc/server/observable';\nimport { observable } from '@trpc/server/observable';\nimport type { InferrableClientTypes } from '@trpc/server/unstable-core-do-not-import';\nimport { inputWithTrackedEventId } from '../internals/inputWithTrackedEventId';\nimport type { TRPCClientError } from '../TRPCClientError';\nimport type { Operation, TRPCLink } from './types';\n\ninterface RetryLinkOptions<TInferrable extends InferrableClientTypes> {\n /**\n * The retry function\n */\n retry: (opts: RetryFnOptions<TInferrable>) => boolean;\n /**\n * The delay between retries in ms (defaults to 0)\n */\n retryDelayMs?: (attempt: number) => number;\n}\n\ninterface RetryFnOptions<TInferrable extends InferrableClientTypes> {\n /**\n * The operation that failed\n */\n op: Operation;\n /**\n * The error that occurred\n */\n error: TRPCClientError<TInferrable>;\n /**\n * The number of attempts that have been made (including the first call)\n */\n attempts: number;\n}\n\n/**\n * @see https://trpc.io/docs/v11/client/links/retryLink\n */\nexport function retryLink<TInferrable extends InferrableClientTypes>(\n opts: RetryLinkOptions<TInferrable>,\n): TRPCLink<TInferrable> {\n // initialized config\n return () => {\n // initialized in app\n return (callOpts) => {\n // initialized for request\n return observable((observer) => {\n let next$: Unsubscribable;\n let callNextTimeout: ReturnType<typeof setTimeout> | undefined =\n undefined;\n\n let lastEventId: string | undefined = undefined;\n\n attempt(1);\n\n function opWithLastEventId() {\n const op = callOpts.op;\n if (!lastEventId) {\n return op;\n }\n\n return {\n ...op,\n input: inputWithTrackedEventId(op.input, lastEventId),\n };\n }\n\n function attempt(attempts: number) {\n const op = opWithLastEventId();\n\n next$ = callOpts.next(op).subscribe({\n error(error) {\n const shouldRetry = opts.retry({\n op,\n attempts,\n error,\n });\n if (!shouldRetry) {\n observer.error(error);\n return;\n }\n const delayMs = opts.retryDelayMs?.(attempts) ?? 0;\n\n if (delayMs <= 0) {\n attempt(attempts + 1);\n return;\n }\n callNextTimeout = setTimeout(\n () => attempt(attempts + 1),\n delayMs,\n );\n },\n next(envelope) {\n //\n if (\n (!envelope.result.type || envelope.result.type === 'data') &&\n envelope.result.id\n ) {\n //\n lastEventId = envelope.result.id;\n }\n\n observer.next(envelope);\n },\n complete() {\n observer.complete();\n },\n });\n }\n return () => {\n next$.unsubscribe();\n clearTimeout(callNextTimeout);\n };\n });\n };\n };\n}\n","// @ts-expect-error - polyfilling symbol\n// eslint-disable-next-line no-restricted-syntax\nSymbol.dispose ??= Symbol();\n\n// @ts-expect-error - polyfilling symbol\n// eslint-disable-next-line no-restricted-syntax\nSymbol.asyncDispose ??= Symbol();\n\n/**\n * Takes a value and a dispose function and returns a new object that implements the Disposable interface.\n * The returned object is the original value augmented with a Symbol.dispose method.\n * @param thing The value to make disposable\n * @param dispose Function to call when disposing the resource\n * @returns The original value with Symbol.dispose method added\n */\nexport function makeResource<T>(thing: T, dispose: () => void): T & Disposable {\n const it = thing as T & Partial<Disposable>;\n\n // eslint-disable-next-line no-restricted-syntax\n const existing = it[Symbol.dispose];\n\n // eslint-disable-next-line no-restricted-syntax\n it[Symbol.dispose] = () => {\n dispose();\n existing?.call(it);\n };\n\n return it as T & Disposable;\n}\n\n/**\n * Takes a value and an async dispose function and returns a new object that implements the AsyncDisposable interface.\n * The returned object is the original value augmented with a Symbol.asyncDispose method.\n * @param thing The value to make async disposable\n * @param dispose Async function to call when disposing the resource\n * @returns The original value with Symbol.asyncDispose method added\n */\nexport function makeAsyncResource<T>(\n thing: T,\n dispose: () => Promise<void>,\n): T & AsyncDisposable {\n const it = thing as T & Partial<AsyncDisposable>;\n\n // eslint-disable-next-line no-restricted-syntax\n const existing = it[Symbol.asyncDispose];\n\n // eslint-disable-next-line no-restricted-syntax\n it[Symbol.asyncDispose] = async () => {\n await dispose();\n await existing?.call(it);\n };\n\n return it as T & AsyncDisposable;\n}\n","import { makeResource } from './disposable';\n\nexport const disposablePromiseTimerResult = Symbol();\n\nexport function timerResource(ms: number) {\n let timer: ReturnType<typeof setTimeout> | null = null;\n\n return makeResource(\n {\n start() {\n if (timer) {\n throw new Error('Timer already started');\n }\n\n const promise = new Promise<typeof disposablePromiseTimerResult>(\n (resolve) => {\n timer = setTimeout(() => resolve(disposablePromiseTimerResult), ms);\n },\n );\n return promise;\n },\n },\n () => {\n if (timer) {\n clearTimeout(timer);\n }\n },\n );\n}\n","import type { Encoder } from './wsClient/encoder';\nimport { jsonEncoder } from './wsClient/encoder';\nimport type { WebSocketClientOptions } from './wsClient/options';\nimport { WsClient } from './wsClient/wsClient';\n\nexport function createWSClient(opts: WebSocketClientOptions) {\n return new WsClient(opts);\n}\n\nexport type TRPCWebSocketClient = ReturnType<typeof createWSClient>;\n\nexport { jsonEncoder, type Encoder, type WebSocketClientOptions };\n","import { observable } from '@trpc/server/observable';\nimport type {\n AnyRouter,\n inferClientTypes,\n} from '@trpc/server/unstable-core-do-not-import';\nimport type { TransformerOptions } from '../../unstable-internals';\nimport { getTransformer } from '../../unstable-internals';\nimport type { TRPCLink } from '../types';\nimport type {\n Encoder,\n TRPCWebSocketClient,\n WebSocketClientOptions,\n} from './createWsClient';\nimport { createWSClient, jsonEncoder } from './createWsClient';\n\nexport type WebSocketLinkOptions<TRouter extends AnyRouter> = {\n client: TRPCWebSocketClient;\n} & TransformerOptions<inferClientTypes<TRouter>>;\n\nexport function wsLink<TRouter extends AnyRouter>(\n opts: WebSocketLinkOptions<TRouter>,\n): TRPCLink<TRouter> {\n const { client } = opts;\n const transformer = getTransformer(opts.transformer);\n return () => {\n return ({ op }) => {\n return observable((observer) => {\n const connStateSubscription =\n op.type === 'subscription'\n ? client.connectionState.subscribe({\n next(result) {\n observer.next({\n result,\n context: op.context,\n });\n },\n })\n : null;\n\n const requestSubscription = client\n .request({\n op,\n transformer,\n })\n .subscribe(observer);\n\n return () => {\n requestSubscription.unsubscribe();\n connStateSubscription?.unsubscribe();\n };\n });\n };\n };\n}\n\nexport {\n createWSClient,\n jsonEncoder,\n type Encoder,\n type TRPCWebSocketClient,\n type WebSocketClientOptions,\n};\n","import {\n getTRPCErrorFromUnknown,\n getTRPCErrorShape,\n isTrackedEnvelope,\n} from '@trpc/server';\nimport { behaviorSubject, observable } from '@trpc/server/observable';\nimport { TRPC_ERROR_CODES_BY_KEY, type TRPCResult } from '@trpc/server/rpc';\nimport {\n callProcedure,\n isAbortError,\n isAsyncIterable,\n iteratorResource,\n makeResource,\n retryableRpcCodes,\n run,\n type AnyRouter,\n type ErrorHandlerOptions,\n type inferClientTypes,\n type inferRouterContext,\n} from '@trpc/server/unstable-core-do-not-import';\nimport { inputWithTrackedEventId } from '../internals/inputWithTrackedEventId';\nimport { abortSignalToPromise, raceAbortSignals } from '../internals/signals';\nimport { getTransformer } from '../internals/transformer';\nimport type { TransformerOptions } from '../internals/transformer';\nimport { isTRPCClientError, TRPCClientError } from '../TRPCClientError';\nimport type { TRPCConnectionState } from './internals/subscriptions';\nimport type { TRPCLink } from './types';\n\nexport type LocalLinkOptions<TRouter extends AnyRouter> = {\n router: TRouter;\n createContext: () => Promise<inferRouterContext<TRouter>>;\n onError?: (opts: ErrorHandlerOptions<inferRouterContext<TRouter>>) => void;\n} & TransformerOptions<inferClientTypes<TRouter>>;\n\n/**\n * localLink is a terminating link that allows you to make tRPC procedure calls directly in your application without going through HTTP.\n *\n * @see https://trpc.io/docs/links/localLink\n */\nexport function unstable_localLink<TRouter extends AnyRouter>(\n opts: LocalLinkOptions<TRouter>,\n): TRPCLink<TRouter> {\n const transformer = getTransformer(opts.transformer);\n\n const transformChunk = (chunk: unknown) => {\n if (opts.transformer) {\n // assume transformer will do the right thing\n return chunk;\n }\n // Special case for undefined, because `JSON.stringify(undefined)` throws\n if (chunk === undefined) {\n return chunk;\n }\n const serialized = JSON.stringify(transformer.input.serialize(chunk));\n const deserialized = JSON.parse(transformer.output.deserialize(serialized));\n return deserialized;\n };\n\n return () =>\n ({ op }) =>\n observable((observer) => {\n let ctx: inferRouterContext<TRouter> | undefined = undefined;\n const ac = new AbortController();\n\n const signal = raceAbortSignals(op.signal, ac.signal);\n const signalPromise = abortSignalToPromise(signal);\n\n signalPromise.catch(() => {\n // prevent unhandled rejection\n });\n\n let input = op.input;\n async function runProcedure(newInput: unknown): Promise<unknown> {\n input = newInput;\n\n ctx = await opts.createContext();\n\n return callProcedure({\n router: opts.router,\n path: op.path,\n getRawInput: async () => newInput,\n ctx,\n type: op.type,\n signal,\n batchIndex: 0,\n });\n }\n\n function onErrorCallback(cause: unknown) {\n if (isAbortError(cause)) {\n return;\n }\n opts.onError?.({\n error: getTRPCErrorFromUnknown(cause),\n type: op.type,\n path: op.path,\n input,\n ctx,\n });\n }\n\n function coerceToTRPCClientError(cause: unknown) {\n if (isTRPCClientError<TRouter>(cause)) {\n return cause;\n }\n const error = getTRPCErrorFromUnknown(cause);\n\n const shape = getTRPCErrorShape({\n config: opts.router._def._config,\n ctx,\n error,\n input,\n path: op.path,\n type: op.type,\n });\n return TRPCClientError.from(\n { error: transformChunk(shape) },\n { cause: cause instanceof Error ? cause : undefined },\n );\n }\n\n run(async () => {\n switch (op.type) {\n case 'query':\n case 'mutation': {\n const result = await runProcedure(op.input);\n if (!isAsyncIterable(result)) {\n observer.next({\n result: { data: transformChunk(result) },\n });\n observer.complete();\n break;\n }\n\n observer.next({\n result: {\n data: (async function* () {\n await using iterator = iteratorResource(result);\n using _finally = makeResource({}, () => {\n observer.complete();\n });\n try {\n while (true) {\n const res = await Promise.race([\n iterator.next(),\n signalPromise,\n ]);\n if (res.done) {\n return transformChunk(res.value);\n }\n yield transformChunk(res.value);\n }\n } catch (cause) {\n onErrorCallback(cause);\n throw coerceToTRPCClientError(cause);\n }\n })(),\n },\n });\n break;\n }\n case 'subscription': {\n const connectionState = behaviorSubject<\n TRPCConnectionState<TRPCClientError<any>>\n >({\n type: 'state',\n state: 'connecting',\n error: null,\n });\n\n const connectionSub = connectionState.subscribe({\n next(state) {\n observer.next({\n result: state,\n });\n },\n });\n let lastEventId: string | undefined = undefined;\n\n using _finally = makeResource({}, async () => {\n observer.complete();\n\n connectionState.next({\n type: 'state',\n state: 'idle',\n error: null,\n });\n connectionSub.unsubscribe();\n });\n while (true) {\n const result = await runProcedure(\n inputWithTrackedEventId(op.input, lastEventId),\n );\n if (!isAsyncIterable(result)) {\n throw new Error('Expected an async iterable');\n }\n await using iterator = iteratorResource(result);\n\n observer.next({\n result: {\n type: 'started',\n },\n });\n connectionState.next({\n type: 'state',\n state: 'pending',\n error: null,\n });\n\n // Use a while loop to handle errors and reconnects\n while (true) {\n let res;\n try {\n res = await Promise.race([iterator.next(), signalPromise]);\n } catch (cause) {\n if (isAbortError(cause)) {\n return;\n }\n const error = getTRPCErrorFromUnknown(cause);\n\n if (\n !retryableRpcCodes.includes(\n TRPC_ERROR_CODES_BY_KEY[error.code],\n )\n ) {\n throw coerceToTRPCClientError(error);\n }\n\n onErrorCallback(error);\n connectionState.next({\n type: 'state',\n state: 'connecting',\n error: coerceToTRPCClientError(error),\n });\n\n break;\n }\n\n if (res.done) {\n return;\n }\n let chunk: TRPCResult<unknown>;\n if (isTrackedEnvelope(res.value)) {\n lastEventId = res.value[0];\n\n chunk = {\n id: res.value[0],\n data: {\n id: res.value[0],\n data: res.value[1],\n },\n };\n } else {\n chunk = {\n data: res.value,\n };\n }\n\n observer.next({\n result: {\n ...chunk,\n data: transformChunk(chunk.data),\n },\n });\n }\n }\n break;\n }\n }\n }).catch((cause) => {\n onErrorCallback(cause);\n observer.error(coerceToTRPCClientError(cause));\n });\n\n return () => {\n ac.abort();\n };\n });\n}\n/**\n * @deprecated Renamed to `unstable_localLink`. This alias will be removed in a future major release.\n */\nexport const experimental_localLink: typeof unstable_localLink =\n unstable_localLink;\n","import { Unpromise } from '../../../vendor/unpromise';\nimport { throwAbortError } from '../../http/abortError';\nimport { makeAsyncResource } from './disposable';\nimport { disposablePromiseTimerResult, timerResource } from './timerResource';\n\nexport function iteratorResource<TYield, TReturn, TNext>(\n iterable: AsyncIterable<TYield, TReturn, TNext>,\n): AsyncIterator<TYield, TReturn, TNext> & AsyncDisposable {\n const iterator = iterable[Symbol.asyncIterator]();\n\n // @ts-expect-error - this is added in node 24 which we don't officially support yet\n // eslint-disable-next-line no-restricted-syntax\n if (iterator[Symbol.asyncDispose]) {\n return iterator as AsyncIterator<TYield, TReturn, TNext> & AsyncDisposable;\n }\n\n return makeAsyncResource(iterator, async () => {\n await iterator.return?.();\n });\n}\n\n/**\n * Derives a new {@link AsyncGenerator} based of {@link iterable}, that yields its first\n * {@link count} values. Then, a grace period of {@link gracePeriodMs} is started in which further\n * values may still come through. After this period, the generator aborts.\n */\nexport async function* takeWithGrace<T>(\n iterable: AsyncIterable<T>,\n opts: {\n count: number;\n gracePeriodMs: number;\n },\n): AsyncGenerator<T> {\n await using iterator = iteratorResource(iterable);\n\n // declaration outside the loop for garbage collection reasons\n let result: null | IteratorResult<T> | typeof disposablePromiseTimerResult;\n\n using timer = timerResource(opts.gracePeriodMs);\n\n let count = opts.count;\n\n let timerPromise = new Promise<typeof disposablePromiseTimerResult>(() => {\n // never resolves\n });\n\n while (true) {\n result = await Unpromise.race([iterator.next(), timerPromise]);\n if (result === disposablePromiseTimerResult) {\n throwAbortError();\n }\n if (result.done) {\n return result.value;\n }\n yield result.value;\n if (--count === 0) {\n timerPromise = timer.start();\n }\n // free up reference for garbage collection\n result = null;\n }\n}\n","/* eslint-disable @typescript-eslint/no-non-null-assertion */\nexport function createDeferred<TValue = void>() {\n let resolve: (value: TValue) => void;\n let reject: (error: unknown) => void;\n const promise = new Promise<TValue>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n\n return { promise, resolve: resolve!, reject: reject! };\n}\nexport type Deferred<TValue> = ReturnType<typeof createDeferred<TValue>>;\n","import { createDeferred } from './createDeferred';\nimport { makeAsyncResource } from './disposable';\n\ntype ManagedIteratorResult<TYield, TReturn> =\n | { status: 'yield'; value: TYield }\n | { status: 'return'; value: TReturn }\n | { status: 'error'; error: unknown };\nfunction createManagedIterator<TYield, TReturn>(\n iterable: AsyncIterable<TYield, TReturn>,\n onResult: (result: ManagedIteratorResult<TYield, TReturn>) => void,\n) {\n const iterator = iterable[Symbol.asyncIterator]();\n let state: 'idle' | 'pending' | 'done' = 'idle';\n\n function cleanup() {\n state = 'done';\n onResult = () => {\n // noop\n };\n }\n\n function pull() {\n if (state !== 'idle') {\n return;\n }\n state = 'pending';\n\n const next = iterator.next();\n next\n .then((result) => {\n if (result.done) {\n state = 'done';\n onResult({ status: 'return', value: result.value });\n cleanup();\n return;\n }\n state = 'idle';\n onResult({ status: 'yield', value: result.value });\n })\n .catch((cause) => {\n onResult({ status: 'error', error: cause });\n cleanup();\n });\n }\n\n return {\n pull,\n destroy: async () => {\n cleanup();\n await iterator.return?.();\n },\n };\n}\ntype ManagedIterator<TYield, TReturn> = ReturnType<\n typeof createManagedIterator<TYield, TReturn>\n>;\n\ninterface MergedAsyncIterables<TYield> extends AsyncIterable<\n TYield,\n void,\n unknown\n> {\n add(iterable: AsyncIterable<TYield>): void;\n}\n\n/**\n * Creates a new async iterable that merges multiple async iterables into a single stream.\n * Values from the input iterables are yielded in the order they resolve, similar to Promise.race().\n *\n * New iterables can be added dynamically using the returned {@link MergedAsyncIterables.add} method, even after iteration has started.\n *\n * If any of the input iterables throws an error, that error will be propagated through the merged stream.\n * Other iterables will not continue to be processed.\n *\n * @template TYield The type of values yielded by the input iterables\n */\nexport function mergeAsyncIterables<TYield>(): MergedAsyncIterables<TYield> {\n let state: 'idle' | 'pending' | 'done' = 'idle';\n let flushSignal = createDeferred();\n\n /**\n * used while {@link state} is `idle`\n */\n const iterables: AsyncIterable<TYield, void, unknown>[] = [];\n /**\n * used while {@link state} is `pending`\n */\n const iterators = new Set<ManagedIterator<TYield, void>>();\n\n const buffer: Array<\n [\n iterator: ManagedIterator<TYield, void>,\n result: Exclude<\n ManagedIteratorResult<TYield, void>,\n { status: 'return' }\n >,\n ]\n > = [];\n\n function initIterable(iterable: AsyncIterable<TYield, void, unknown>) {\n if (state !== 'pending') {\n // shouldn't happen\n return;\n }\n const iterator = createManagedIterator(iterable, (result) => {\n if (state !== 'pending') {\n // shouldn't happen\n return;\n }\n switch (result.status) {\n case 'yield':\n buffer.push([iterator, result]);\n break;\n case 'return':\n iterators.delete(iterator);\n break;\n case 'error':\n buffer.push([iterator, result]);\n iterators.delete(iterator);\n break;\n }\n flushSignal.resolve();\n });\n iterators.add(iterator);\n iterator.pull();\n }\n\n return {\n add(iterable: AsyncIterable<TYield, void, unknown>) {\n switch (state) {\n case 'idle':\n iterables.push(iterable);\n break;\n case 'pending':\n initIterable(iterable);\n break;\n case 'done': {\n // shouldn't happen\n break;\n }\n }\n },\n async *[Symbol.asyncIterator]() {\n if (state !== 'idle') {\n throw new Error('Cannot iterate twice');\n }\n state = 'pending';\n\n await using _finally = makeAsyncResource({}, async () => {\n state = 'done';\n\n const errors: unknown[] = [];\n await Promise.all(\n Array.from(iterators.values()).map(async (it) => {\n try {\n await it.destroy();\n } catch (cause) {\n errors.push(cause);\n }\n }),\n );\n buffer.length = 0;\n iterators.clear();\n flushSignal.resolve();\n\n if (errors.length > 0) {\n throw new AggregateError(errors);\n }\n });\n\n while (iterables.length > 0) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n initIterable(iterables.shift()!);\n }\n\n while (iterators.size > 0) {\n await flushSignal.promise;\n\n while (buffer.length > 0) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const [iterator, result] = buffer.shift()!;\n\n switch (result.status) {\n case 'yield':\n yield result.value;\n iterator.pull();\n break;\n case 'error':\n throw result.error;\n }\n }\n flushSignal = createDeferred();\n }\n },\n };\n}\n","/**\n * Creates a ReadableStream from an AsyncIterable.\n *\n * @param iterable - The source AsyncIterable to stream from\n * @returns A ReadableStream that yields values from the AsyncIterable\n */\nexport function readableStreamFrom<TYield>(\n iterable: AsyncIterable<TYield, void>,\n): ReadableStream<TYield> {\n const iterator = iterable[Symbol.asyncIterator]();\n\n return new ReadableStream({\n async cancel() {\n await iterator.return?.();\n },\n\n async pull(controller) {\n const result = await iterator.next();\n\n if (result.done) {\n controller.close();\n return;\n }\n\n controller.enqueue(result.value);\n },\n });\n}\n","import { Unpromise } from '../../../vendor/unpromise';\nimport { iteratorResource } from './asyncIterable';\nimport { disposablePromiseTimerResult, timerResource } from './timerResource';\n\nexport const PING_SYM = Symbol('ping');\n\n/**\n * Derives a new {@link AsyncGenerator} based of {@link iterable}, that yields {@link PING_SYM}\n * whenever no value has been yielded for {@link pingIntervalMs}.\n */\nexport async function* withPing<TValue>(\n iterable: AsyncIterable<TValue>,\n pingIntervalMs: number,\n): AsyncGenerator<TValue | typeof PING_SYM> {\n await using iterator = iteratorResource(iterable);\n\n // declaration outside the loop for garbage collection reasons\n let result:\n null | IteratorResult<TValue> | typeof disposablePromiseTimerResult;\n\n let nextPromise = iterator.next();\n\n while (true) {\n using pingPromise = timerResource(pingIntervalMs);\n\n result = await Unpromise.race([nextPromise, pingPromise.start()]);\n\n if (result === disposablePromiseTimerResult) {\n // cancelled\n\n yield PING_SYM;\n continue;\n }\n\n if (result.done) {\n return result.value;\n }\n\n nextPromise = iterator.next();\n yield result.value;\n\n // free up reference for garbage collection\n result = null;\n }\n}\n","import { isPlainObject } from '@trpc/server/vendor/is-plain-object';\nimport {\n emptyObject,\n isAsyncIterable,\n isFunction,\n isObject,\n run,\n} from '../utils';\nimport { iteratorResource } from './utils/asyncIterable';\nimport type { Deferred } from './utils/createDeferred';\nimport { createDeferred } from './utils/createDeferred';\nimport { makeResource } from './utils/disposable';\nimport { mergeAsyncIterables } from './utils/mergeAsyncIterables';\nimport { readableStreamFrom } from './utils/readableStreamFrom';\nimport { PING_SYM, withPing } from './utils/withPing';\n\n/**\n * A subset of the standard ReadableStream properties needed by tRPC internally.\n * @see ReadableStream from lib.dom.d.ts\n */\nexport type WebReadableStreamEsque = {\n getReader: () => ReadableStreamDefaultReader<Uint8Array>;\n};\n\nexport type NodeJSReadableStreamEsque = {\n on(\n eventName: string | symbol,\n listener: (...args: any[]) => void,\n ): NodeJSReadableStreamEsque;\n};\n\n// ---------- types\nconst CHUNK_VALUE_TYPE_PROMISE = 0;\ntype CHUNK_VALUE_TYPE_PROMISE = typeof CHUNK_VALUE_TYPE_PROMISE;\nconst CHUNK_VALUE_TYPE_ASYNC_ITERABLE = 1;\ntype CHUNK_VALUE_TYPE_ASYNC_ITERABLE = typeof CHUNK_VALUE_TYPE_ASYNC_ITERABLE;\n\nconst PROMISE_STATUS_FULFILLED = 0;\ntype PROMISE_STATUS_FULFILLED = typeof PROMISE_STATUS_FULFILLED;\nconst PROMISE_STATUS_REJECTED = 1;\ntype PROMISE_STATUS_REJECTED = typeof PROMISE_STATUS_REJECTED;\n\nconst ASYNC_ITERABLE_STATUS_RETURN = 0;\ntype ASYNC_ITERABLE_STATUS_RETURN = typeof ASYNC_ITERABLE_STATUS_RETURN;\nconst ASYNC_ITERABLE_STATUS_YIELD = 1;\ntype ASYNC_ITERABLE_STATUS_YIELD = typeof ASYNC_ITERABLE_STATUS_YIELD;\nconst ASYNC_ITERABLE_STATUS_ERROR = 2;\ntype ASYNC_ITERABLE_STATUS_ERROR = typeof ASYNC_ITERABLE_STATUS_ERROR;\n\ntype ChunkDefinitionKey =\n // root should be replaced\n | null\n // at array path\n | number\n // at key path\n | string;\n\ntype ChunkIndex = number & { __chunkIndex: true };\ntype ChunkValueType =\n CHUNK_VALUE_TYPE_PROMISE | CHUNK_VALUE_TYPE_ASYNC_ITERABLE;\ntype ChunkDefinition = [\n key: ChunkDefinitionKey,\n type: ChunkValueType,\n chunkId: ChunkIndex,\n];\ntype EncodedValue = [\n // data\n [unknown] | [],\n // chunk descriptions\n ...ChunkDefinition[],\n];\n\ntype Head = Record<string, EncodedValue>;\ntype PromiseChunk =\n | [\n chunkIndex: ChunkIndex,\n status: PROMISE_STATUS_FULFILLED,\n value: EncodedValue,\n ]\n | [chunkIndex: ChunkIndex, status: PROMISE_STATUS_REJECTED, error: unknown];\ntype IterableChunk =\n | [\n chunkIndex: ChunkIndex,\n status: ASYNC_ITERABLE_STATUS_RETURN,\n value: EncodedValue,\n ]\n | [\n chunkIndex: ChunkIndex,\n status: ASYNC_ITERABLE_STATUS_YIELD,\n value: EncodedValue,\n ]\n | [\n chunkIndex: ChunkIndex,\n status: ASYNC_ITERABLE_STATUS_ERROR,\n error: unknown,\n ];\ntype ChunkData = PromiseChunk | IterableChunk;\ntype PlaceholderValue = 0 & { __placeholder: true };\nexport function isPromise(value: unknown): value is Promise<unknown> {\n return (\n (isObject(value) || isFunction(value)) &&\n typeof value?.['then'] === 'function' &&\n typeof value?.['catch'] === 'function'\n );\n}\n\ntype Serialize = (value: any) => any;\ntype Deserialize = (value: any) => any;\n\ntype PathArray = readonly (string | number)[];\nexport type ProducerOnError = (opts: {\n error: unknown;\n path: PathArray;\n}) => void;\nexport interface JSONLProducerOptions {\n serialize?: Serialize;\n data: Record<string, unknown> | unknown[];\n onError?: ProducerOnError;\n formatError?: (opts: { error: unknown; path: PathArray }) => unknown;\n maxDepth?: number;\n /**\n * Interval in milliseconds to send a ping to the client to keep the connection alive\n * This will be sent as a whitespace character\n * @default undefined\n */\n pingMs?: number;\n}\n\nclass MaxDepthError extends Error {\n constructor(public path: (string | number)[]) {\n super('Max depth reached at path: ' + path.join('.'));\n }\n}\n\nasync function* createBatchStreamProducer(\n opts: JSONLProducerOptions,\n): AsyncIterable<Head | ChunkData | typeof PING_SYM, void> {\n const { data } = opts;\n let counter = 0 as ChunkIndex;\n const placeholder = 0 as PlaceholderValue;\n\n const mergedIterables = mergeAsyncIterables<ChunkData>();\n function registerAsync(\n callback: (idx: ChunkIndex) => AsyncIterable<ChunkData, void>,\n ) {\n const idx = counter++ as ChunkIndex;\n\n const iterable = callback(idx);\n mergedIterables.add(iterable);\n\n return idx;\n }\n\n function encodePromise(promise: Promise<unknown>, path: (string | number)[]) {\n return registerAsync(async function* (idx) {\n const error = checkMaxDepth(path);\n if (error) {\n // Catch any errors from the original promise to ensure they're reported\n promise.catch((cause) => {\n opts.onError?.({ error: cause, path });\n });\n // Replace the promise with a rejected one containing the max depth error\n promise = Promise.reject(error);\n }\n try {\n const next = await promise;\n yield [idx, PROMISE_STATUS_FULFILLED, encode(next, path)];\n } catch (cause) {\n opts.onError?.({ error: cause, path });\n yield [\n idx,\n PROMISE_STATUS_REJECTED,\n opts.formatError?.({ error: cause, path }),\n ];\n }\n });\n }\n function encodeAsyncIterable(\n iterable: AsyncIterable<unknown>,\n path: (string | number)[],\n ) {\n return registerAsync(async function* (idx) {\n const error = checkMaxDepth(path);\n if (error) {\n throw error;\n }\n await using iterator = iteratorResource(iterable);\n\n try {\n while (true) {\n const next = await iterator.next();\n if (next.done) {\n yield [idx, ASYNC_ITERABLE_STATUS_RETURN, encode(next.value, path)];\n break;\n }\n yield [idx, ASYNC_ITERABLE_STATUS_YIELD, encode(next.value, path)];\n }\n } catch (cause) {\n opts.onError?.({ error: cause, path });\n\n yield [\n idx,\n ASYNC_ITERABLE_STATUS_ERROR,\n opts.formatError?.({ error: cause, path }),\n ];\n }\n });\n }\n function checkMaxDepth(path: (string | number)[]) {\n if (opts.maxDepth && path.length > opts.maxDepth) {\n return new MaxDepthError(path);\n }\n return null;\n }\n function encodeAsync(\n value: unknown,\n path: (string | number)[],\n ): null | [type: ChunkValueType, chunkId: ChunkIndex] {\n if (isPromise(value)) {\n return [CHUNK_VALUE_TYPE_PROMISE, encodePromise(value, path)];\n }\n if (isAsyncIterable(value)) {\n if (opts.maxDepth && path.length >= opts.maxDepth) {\n throw new Error('Max depth reached');\n }\n return [\n CHUNK_VALUE_TYPE_ASYNC_ITERABLE,\n encodeAsyncIterable(value, path),\n ];\n }\n return null;\n }\n function encode(value: unknown, path: (string | number)[]): EncodedValue {\n if (value === undefined) {\n return [[]];\n }\n const reg = encodeAsync(value, path);\n if (reg) {\n return [[placeholder], [null, ...reg]];\n }\n\n if (!isPlainObject(value)) {\n return [[value]];\n }\n\n const newObj: Record<string, unknown> = emptyObject();\n const asyncValues: ChunkDefinition[] = [];\n for (const [key, item] of Object.entries(value)) {\n const transformed = encodeAsync(item, [...path, key]);\n if (!transformed) {\n newObj[key] = item;\n continue;\n }\n newObj[key] = placeholder;\n asyncValues.push([key, ...transformed]);\n }\n return [[newObj], ...asyncValues];\n }\n\n const newHead: Head = emptyObject();\n for (const [key, item] of Object.entries(data)) {\n newHead[key] = encode(item, [key]);\n }\n\n yield newHead;\n\n let iterable: AsyncIterable<ChunkData | typeof PING_SYM, void> =\n mergedIterables;\n if (opts.pingMs) {\n iterable = withPing(mergedIterables, opts.pingMs);\n }\n\n for await (const value of iterable) {\n yield value;\n }\n}\n/**\n * JSON Lines stream producer\n * @see https://jsonlines.org/\n */\nexport function jsonlStreamProducer(opts: JSONLProducerOptions) {\n let stream = readableStreamFrom(createBatchStreamProducer(opts));\n\n const { serialize } = opts;\n if (serialize) {\n stream = stream.pipeThrough(\n new TransformStream({\n transform(chunk, controller) {\n if (chunk === PING_SYM) {\n controller.enqueue(PING_SYM);\n } else {\n controller.enqueue(serialize(chunk));\n }\n },\n }),\n );\n }\n\n return stream\n .pipeThrough(\n new TransformStream({\n transform(chunk, controller) {\n if (chunk === PING_SYM) {\n controller.enqueue(' ');\n } else {\n controller.enqueue(JSON.stringify(chunk) + '\\n');\n }\n },\n }),\n )\n .pipeThrough(new TextEncoderStream());\n}\n\nclass AsyncError extends Error {\n constructor(public readonly data: unknown) {\n super('Received error from server');\n }\n}\nexport type ConsumerOnError = (opts: { error: unknown }) => void;\n\nconst nodeJsStreamToReaderEsque = (source: NodeJSReadableStreamEsque) => {\n return {\n getReader() {\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n source.on('data', (chunk) => {\n controller.enqueue(chunk);\n });\n source.on('end', () => {\n controller.close();\n });\n source.on('error', (error) => {\n controller.error(error);\n });\n },\n });\n return stream.getReader();\n },\n };\n};\n\nfunction createLineAccumulator(\n from: NodeJSReadableStreamEsque | WebReadableStreamEsque,\n) {\n const reader =\n 'getReader' in from\n ? from.getReader()\n : nodeJsStreamToReaderEsque(from).getReader();\n\n let lineAggregate = '';\n\n return new ReadableStream({\n async pull(controller) {\n const { done, value } = await reader.read();\n\n if (done) {\n controller.close();\n } else {\n controller.enqueue(value);\n }\n },\n cancel() {\n return reader.cancel();\n },\n })\n .pipeThrough(new TextDecoderStream())\n .pipeThrough(\n new TransformStream<string, string>({\n transform(chunk, controller) {\n lineAggregate += chunk;\n const parts = lineAggregate.split('\\n');\n lineAggregate = parts.pop() ?? '';\n for (const part of parts) {\n controller.enqueue(part);\n }\n },\n }),\n );\n}\nfunction createConsumerStream<THead>(\n from: NodeJSReadableStreamEsque | WebReadableStreamEsque,\n) {\n const stream = createLineAccumulator(from);\n\n let sentHead = false;\n return stream.pipeThrough(\n new TransformStream<string, ChunkData | THead>({\n transform(line, controller) {\n if (!sentHead) {\n const head = JSON.parse(line);\n controller.enqueue(head as THead);\n sentHead = true;\n } else {\n const chunk: ChunkData = JSON.parse(line);\n controller.enqueue(chunk);\n }\n },\n }),\n );\n}\n\n/**\n * Creates a handler for managing stream controllers and their lifecycle\n */\nfunction createStreamsManager(abortController: AbortController) {\n const controllerMap = new Map<\n ChunkIndex,\n ReturnType<typeof createStreamController>\n >();\n\n /**\n * Checks if there are no pending controllers or deferred promises\n */\n function isEmpty() {\n return Array.from(controllerMap.values()).every((c) => c.closed);\n }\n\n /**\n * Creates a stream controller\n */\n function createStreamController() {\n let originalController: ReadableStreamDefaultController<ChunkData>;\n const stream = new ReadableStream<ChunkData>({\n start(controller) {\n originalController = controller;\n },\n });\n\n const streamController = {\n enqueue: (v: ChunkData) => originalController.enqueue(v),\n close: () => {\n originalController.close();\n\n clear();\n\n if (isEmpty()) {\n abortController.abort();\n }\n },\n closed: false,\n getReaderResource: () => {\n const reader = stream.getReader();\n\n return makeResource(reader, () => {\n streamController.close();\n reader.releaseLock();\n });\n },\n error: (reason: unknown) => {\n originalController.error(reason);\n\n clear();\n },\n };\n function clear() {\n Object.assign(streamController, {\n closed: true,\n close: () => {\n // noop\n },\n enqueue: () => {\n // noop\n },\n getReaderResource: null,\n error: () => {\n // noop\n },\n });\n }\n\n return streamController;\n }\n\n /**\n * Gets or creates a stream controller\n */\n function getOrCreate(chunkId: ChunkIndex) {\n let c = controllerMap.get(chunkId);\n if (!c) {\n c = createStreamController();\n controllerMap.set(chunkId, c);\n }\n return c;\n }\n\n /**\n * Cancels all pending controllers and rejects deferred promises\n */\n function cancelAll(reason: unknown) {\n for (const controller of controllerMap.values()) {\n controller.error(reason);\n }\n }\n\n /**\n * Closes all pending controllers to preserve buffered data\n */\n function closeAll() {\n for (const controller of controllerMap.values()) {\n controller.close();\n }\n }\n\n return {\n getOrCreate,\n cancelAll,\n closeAll,\n };\n}\n\n/**\n * JSON Lines stream consumer\n * @see https://jsonlines.org/\n */\nexport async function jsonlStreamConsumer<THead>(opts: {\n from: NodeJSReadableStreamEsque | WebReadableStreamEsque;\n deserialize?: Deserialize;\n onError?: ConsumerOnError;\n formatError?: (opts: { error: unknown }) => Error;\n /**\n * This `AbortController` will be triggered when there are no more listeners to the stream.\n */\n abortController: AbortController;\n}) {\n const { deserialize = (v) => v } = opts;\n\n let source = createConsumerStream<Head>(opts.from);\n if (deserialize) {\n source = source.pipeThrough(\n new TransformStream({\n transform(chunk, controller) {\n controller.enqueue(deserialize(chunk));\n },\n }),\n );\n }\n let headDeferred: null | Deferred<THead> = createDeferred();\n\n const streamManager = createStreamsManager(opts.abortController);\n\n function decodeChunkDefinition(value: ChunkDefinition) {\n const [_path, type, chunkId] = value;\n\n const controller = streamManager.getOrCreate(chunkId);\n\n switch (type) {\n case CHUNK_VALUE_TYPE_PROMISE: {\n return run(async () => {\n using reader = controller.getReaderResource();\n\n const { value } = await reader.read();\n const [_chunkId, status, data] = value as PromiseChunk;\n switch (status) {\n case PROMISE_STATUS_FULFILLED:\n return decode(data);\n case PROMISE_STATUS_REJECTED:\n throw opts.formatError?.({ error: data }) ?? new AsyncError(data);\n }\n });\n }\n case CHUNK_VALUE_TYPE_ASYNC_ITERABLE: {\n return run(async function* () {\n using reader = controller.getReaderResource();\n\n while (true) {\n const { value } = await reader.read();\n\n const [_chunkId, status, data] = value as IterableChunk;\n\n switch (status) {\n case ASYNC_ITERABLE_STATUS_YIELD:\n yield decode(data);\n break;\n case ASYNC_ITERABLE_STATUS_RETURN:\n return decode(data);\n case ASYNC_ITERABLE_STATUS_ERROR:\n throw (\n opts.formatError?.({ error: data }) ?? new AsyncError(data)\n );\n }\n }\n });\n }\n }\n }\n\n function decode(value: EncodedValue): unknown {\n const [[data], ...asyncProps] = value;\n\n for (const value of asyncProps) {\n const [key] = value;\n const decoded = decodeChunkDefinition(value);\n\n if (key === null) {\n return decoded;\n }\n\n (data as any)[key] = decoded;\n }\n return data;\n }\n\n const handleClose = () => {\n // If the stream closes before emitting any head data,\n // we need to reject the headDeferred to prevent hanging\n if (headDeferred) {\n headDeferred.reject(new Error('Stream closed before head was received'));\n headDeferred = null;\n }\n // Close stream controllers (not error them)\n // to preserve any buffered chunks\n streamManager.closeAll();\n };\n\n const handleAbort = (reason?: unknown) => {\n headDeferred?.reject(reason);\n headDeferred = null;\n streamManager.cancelAll(reason);\n };\n\n source\n .pipeTo(\n new WritableStream({\n write(chunkOrHead) {\n if (headDeferred) {\n const head = chunkOrHead as Record<number | string, unknown>;\n\n for (const [key, value] of Object.entries(chunkOrHead)) {\n const parsed = decode(value as any);\n head[key] = parsed;\n }\n headDeferred.resolve(head as THead);\n headDeferred = null;\n\n return;\n }\n const chunk = chunkOrHead as ChunkData;\n const [idx] = chunk;\n\n const controller = streamManager.getOrCreate(idx);\n controller.enqueue(chunk);\n },\n close: handleClose,\n abort: handleAbort,\n }),\n )\n .catch((error) => {\n opts.onError?.({ error });\n handleAbort(error);\n });\n\n return [await headDeferred.promise] as const;\n}\n","import { Unpromise } from '../../vendor/unpromise';\nimport { getTRPCErrorFromUnknown } from '../error/TRPCError';\nimport { isAbortError } from '../http/abortError';\nimport type { MaybePromise } from '../types';\nimport { emptyObject, identity, run } from '../utils';\nimport type { EventSourceLike } from './sse.types';\nimport type { inferTrackedOutput } from './tracked';\nimport { isTrackedEnvelope } from './tracked';\nimport { takeWithGrace } from './utils/asyncIterable';\nimport { makeAsyncResource } from './utils/disposable';\nimport { readableStreamFrom } from './utils/readableStreamFrom';\nimport {\n disposablePromiseTimerResult,\n timerResource,\n} from './utils/timerResource';\nimport { PING_SYM, withPing } from './utils/withPing';\n\ntype Serialize = (value: any) => any;\ntype Deserialize = (value: any) => any;\n\n/**\n * @internal\n */\nexport interface SSEPingOptions {\n /**\n * Enable ping comments sent from the server\n * @default false\n */\n enabled: boolean;\n /**\n * Interval in milliseconds\n * @default 1000\n */\n intervalMs?: number;\n}\n\nexport interface SSEClientOptions {\n /**\n * Timeout and reconnect after inactivity in milliseconds\n * @default undefined\n */\n reconnectAfterInactivityMs?: number;\n}\n\nexport interface SSEStreamProducerOptions<TValue = unknown> {\n serialize?: Serialize;\n data: AsyncIterable<TValue>;\n\n maxDepth?: number;\n ping?: SSEPingOptions;\n /**\n * Maximum duration in milliseconds for the request before ending the stream\n * @default undefined\n */\n maxDurationMs?: number;\n /**\n * End the request immediately after data is sent\n * Only useful for serverless runtimes that do not support streaming responses\n * @default false\n */\n emitAndEndImmediately?: boolean;\n formatError?: (opts: { error: unknown }) => unknown;\n /**\n * Client-specific options - these will be sent to the client as part of the first message\n * @default {}\n */\n client?: SSEClientOptions;\n}\n\nconst PING_EVENT = 'ping';\nconst SERIALIZED_ERROR_EVENT = 'serialized-error';\nconst CONNECTED_EVENT = 'connected';\nconst RETURN_EVENT = 'return';\n\ninterface SSEvent {\n id?: string;\n data: unknown;\n comment?: string;\n event?: string;\n}\n/**\n *\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html\n */\nexport function sseStreamProducer<TValue = unknown>(\n opts: SSEStreamProducerOptions<TValue>,\n) {\n const { serialize = identity } = opts;\n\n const ping: Required<SSEPingOptions> = {\n enabled: opts.ping?.enabled ?? false,\n intervalMs: opts.ping?.intervalMs ?? 1000,\n };\n const client: SSEClientOptions = opts.client ?? {};\n\n if (\n ping.enabled &&\n client.reconnectAfterInactivityMs &&\n ping.intervalMs > client.reconnectAfterInactivityMs\n ) {\n throw new Error(\n `Ping interval must be less than client reconnect interval to prevent unnecessary reconnection - ping.intervalMs: ${ping.intervalMs} client.reconnectAfterInactivityMs: ${client.reconnectAfterInactivityMs}`,\n );\n }\n\n async function* generator(): AsyncIterable<SSEvent, void> {\n yield {\n event: CONNECTED_EVENT,\n data: JSON.stringify(client),\n };\n\n type TIteratorValue = Awaited<TValue> | typeof PING_SYM;\n\n let iterable: AsyncIterable<TValue | typeof PING_SYM> = opts.data;\n\n if (opts.emitAndEndImmediately) {\n iterable = takeWithGrace(iterable, {\n count: 1,\n gracePeriodMs: 1,\n });\n }\n\n if (ping.enabled && ping.intervalMs !== Infinity && ping.intervalMs > 0) {\n iterable = withPing(iterable, ping.intervalMs);\n }\n\n // We need those declarations outside the loop for garbage collection reasons. If they were\n // declared inside, they would not be freed until the next value is present.\n let value: null | TIteratorValue;\n let chunk: null | SSEvent;\n\n for await (value of iterable) {\n if (value === PING_SYM) {\n yield { event: PING_EVENT, data: '' };\n continue;\n }\n\n chunk = isTrackedEnvelope(value)\n ? { id: value[0], data: value[1] }\n : { data: value };\n\n chunk.data = JSON.stringify(serialize(chunk.data));\n\n yield chunk;\n\n // free up references for garbage collection\n value = null;\n chunk = null;\n }\n }\n\n async function* generatorWithErrorHandling(): AsyncIterable<SSEvent, void> {\n try {\n yield* generator();\n\n yield {\n event: RETURN_EVENT,\n data: '',\n };\n } catch (cause) {\n if (isAbortError(cause)) {\n // ignore abort errors, send any other errors\n return;\n }\n // `err` must be caused by `opts.data`, `JSON.stringify` or `serialize`.\n // So, a user error in any case.\n const error = getTRPCErrorFromUnknown(cause);\n const data = opts.formatError?.({ error }) ?? null;\n yield {\n event: SERIALIZED_ERROR_EVENT,\n data: JSON.stringify(serialize(data)),\n };\n }\n }\n\n const stream = readableStreamFrom(generatorWithErrorHandling());\n\n return stream\n .pipeThrough(\n new TransformStream({\n transform(chunk, controller: TransformStreamDefaultController<string>) {\n if ('event' in chunk) {\n controller.enqueue(`event: ${chunk.event}\\n`);\n }\n if ('data' in chunk) {\n controller.enqueue(`data: ${chunk.data}\\n`);\n }\n if ('id' in chunk) {\n controller.enqueue(`id: ${chunk.id}\\n`);\n }\n if ('comment' in chunk) {\n controller.enqueue(`: ${chunk.comment}\\n`);\n }\n controller.enqueue('\\n\\n');\n },\n }),\n )\n .pipeThrough(new TextEncoderStream());\n}\n\ninterface ConsumerStreamResultBase<TConfig extends ConsumerConfig> {\n eventSource: InstanceType<TConfig['EventSource']> | null;\n}\n\ninterface ConsumerStreamResultData<\n TConfig extends ConsumerConfig,\n> extends ConsumerStreamResultBase<TConfig> {\n type: 'data';\n data: inferTrackedOutput<TConfig['data']>;\n}\n\ninterface ConsumerStreamResultError<\n TConfig extends ConsumerConfig,\n> extends ConsumerStreamResultBase<TConfig> {\n type: 'serialized-error';\n error: TConfig['error'];\n}\n\ninterface ConsumerStreamResultConnecting<\n TConfig extends ConsumerConfig,\n> extends ConsumerStreamResultBase<TConfig> {\n type: 'connecting';\n event: EventSourceLike.EventOf<TConfig['EventSource']> | null;\n}\ninterface ConsumerStreamResultTimeout<\n TConfig extends ConsumerConfig,\n> extends ConsumerStreamResultBase<TConfig> {\n type: 'timeout';\n ms: number;\n}\ninterface ConsumerStreamResultPing<\n TConfig extends ConsumerConfig,\n> extends ConsumerStreamResultBase<TConfig> {\n type: 'ping';\n}\n\ninterface ConsumerStreamResultConnected<\n TConfig extends ConsumerConfig,\n> extends ConsumerStreamResultBase<TConfig> {\n type: 'connected';\n options: SSEClientOptions;\n}\n\ntype ConsumerStreamResult<TConfig extends ConsumerConfig> =\n | ConsumerStreamResultData<TConfig>\n | ConsumerStreamResultError<TConfig>\n | ConsumerStreamResultConnecting<TConfig>\n | ConsumerStreamResultTimeout<TConfig>\n | ConsumerStreamResultPing<TConfig>\n | ConsumerStreamResultConnected<TConfig>;\n\nexport interface SSEStreamConsumerOptions<TConfig extends ConsumerConfig> {\n url: () => MaybePromise<string>;\n init: () =>\n | MaybePromise<EventSourceLike.InitDictOf<TConfig['EventSource']>>\n | undefined;\n signal: AbortSignal;\n deserialize?: Deserialize;\n EventSource: TConfig['EventSource'];\n}\n\ninterface ConsumerConfig {\n data: unknown;\n error: unknown;\n EventSource: EventSourceLike.AnyConstructor;\n}\n\nasync function withTimeout<T>(opts: {\n promise: Promise<T>;\n timeoutMs: number;\n onTimeout: () => Promise<NoInfer<T>>;\n}): Promise<T> {\n using timeoutPromise = timerResource(opts.timeoutMs);\n const res = await Unpromise.race([opts.promise, timeoutPromise.start()]);\n\n if (res === disposablePromiseTimerResult) {\n return await opts.onTimeout();\n }\n return res;\n}\n\n/**\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html\n */\nexport function sseStreamConsumer<TConfig extends ConsumerConfig>(\n opts: SSEStreamConsumerOptions<TConfig>,\n): AsyncIterable<ConsumerStreamResult<TConfig>> {\n const { deserialize = (v) => v } = opts;\n\n let clientOptions: SSEClientOptions = emptyObject();\n\n const signal = opts.signal;\n\n let _es: InstanceType<TConfig['EventSource']> | null = null;\n\n const createStream = () =>\n new ReadableStream<ConsumerStreamResult<TConfig>>({\n async start(controller) {\n const [url, init] = await Promise.all([opts.url(), opts.init()]);\n const eventSource = (_es = new opts.EventSource(\n url,\n init,\n ) as InstanceType<TConfig['EventSource']>);\n\n controller.enqueue({\n type: 'connecting',\n eventSource: _es,\n event: null,\n });\n\n eventSource.addEventListener(CONNECTED_EVENT, (_msg) => {\n const msg = _msg as EventSourceLike.MessageEvent;\n\n const options: SSEClientOptions = JSON.parse(msg.data);\n\n clientOptions = options;\n controller.enqueue({\n type: 'connected',\n options,\n eventSource,\n });\n });\n\n eventSource.addEventListener(SERIALIZED_ERROR_EVENT, (_msg) => {\n const msg = _msg as EventSourceLike.MessageEvent;\n\n controller.enqueue({\n type: 'serialized-error',\n error: deserialize(JSON.parse(msg.data)),\n eventSource,\n });\n });\n eventSource.addEventListener(PING_EVENT, () => {\n controller.enqueue({\n type: 'ping',\n eventSource,\n });\n });\n eventSource.addEventListener(RETURN_EVENT, () => {\n eventSource.close();\n controller.close();\n _es = null;\n });\n eventSource.addEventListener('error', (event) => {\n if (eventSource.readyState === eventSource.CLOSED) {\n controller.error(event);\n } else {\n controller.enqueue({\n type: 'connecting',\n eventSource,\n event,\n });\n }\n });\n eventSource.addEventListener('message', (_msg) => {\n const msg = _msg as EventSourceLike.MessageEvent;\n\n const chunk = deserialize(JSON.parse(msg.data));\n\n const def: SSEvent = {\n data: chunk,\n };\n if (msg.lastEventId) {\n def.id = msg.lastEventId;\n }\n controller.enqueue({\n type: 'data',\n data: def as inferTrackedOutput<TConfig['data']>,\n eventSource,\n });\n });\n\n const onAbort = () => {\n try {\n eventSource.close();\n controller.close();\n } catch {\n // ignore errors in case the controller is already closed\n }\n };\n if (signal.aborted) {\n onAbort();\n } else {\n signal.addEventListener('abort', onAbort);\n }\n },\n cancel() {\n _es?.close();\n },\n });\n\n const getStreamResource = () => {\n let stream = createStream();\n let reader = stream.getReader();\n\n async function dispose() {\n await reader.cancel();\n _es = null;\n }\n\n return makeAsyncResource(\n {\n read() {\n return reader.read();\n },\n async recreate() {\n await dispose();\n\n stream = createStream();\n reader = stream.getReader();\n },\n },\n dispose,\n );\n };\n\n return run(async function* () {\n await using stream = getStreamResource();\n\n while (true) {\n let promise = stream.read();\n\n const timeoutMs = clientOptions.reconnectAfterInactivityMs;\n if (timeoutMs) {\n promise = withTimeout({\n promise,\n timeoutMs,\n onTimeout: async () => {\n const res: Awaited<typeof promise> = {\n value: {\n type: 'timeout',\n ms: timeoutMs,\n eventSource: _es,\n },\n done: false,\n };\n // Close and release old reader\n await stream.recreate();\n\n return res;\n },\n });\n }\n\n const result = await promise;\n\n if (result.done) {\n return result.value;\n }\n yield result.value;\n }\n });\n}\n\nexport const sseHeaders = {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache, no-transform',\n 'X-Accel-Buffering': 'no',\n Connection: 'keep-alive',\n} as const;\n","/* eslint-disable @typescript-eslint/no-non-null-assertion */\nimport {\n isObservable,\n observableToAsyncIterable,\n} from '../../observable/observable';\nimport { getErrorShape } from '../error/getErrorShape';\nimport { getTRPCErrorFromUnknown, TRPCError } from '../error/TRPCError';\nimport type { ProcedureType } from '../procedure';\nimport {\n type AnyRouter,\n type inferRouterContext,\n type inferRouterError,\n} from '../router';\nimport type { TRPCResponse } from '../rpc';\nimport { isPromise, jsonlStreamProducer } from '../stream/jsonl';\nimport { sseHeaders, sseStreamProducer } from '../stream/sse';\nimport { transformTRPCResponse } from '../transformer';\nimport {\n abortSignalsAnyPonyfill,\n isAsyncIterable,\n isObject,\n run,\n} from '../utils';\nimport { getAcceptHeader, getRequestInfo } from './contentType';\nimport { getHTTPStatusCode } from './getHTTPStatusCode';\nimport type {\n HTTPBaseHandlerOptions,\n ResolveHTTPRequestOptionsContextFn,\n TRPCRequestInfo,\n} from './types';\n\nfunction errorToAsyncIterable(err: TRPCError): AsyncIterable<never> {\n return run(async function* () {\n throw err;\n });\n}\ntype HTTPMethods =\n 'GET' | 'POST' | 'HEAD' | 'OPTIONS' | 'PUT' | 'DELETE' | 'PATCH';\n\nfunction combinedAbortController(signal: AbortSignal) {\n const controller = new AbortController();\n const combinedSignal = abortSignalsAnyPonyfill([signal, controller.signal]);\n return {\n signal: combinedSignal,\n controller,\n };\n}\n\nconst TYPE_ACCEPTED_METHOD_MAP: Record<ProcedureType, HTTPMethods[]> = {\n mutation: ['POST'],\n query: ['GET'],\n subscription: ['GET'],\n};\nconst TYPE_ACCEPTED_METHOD_MAP_WITH_METHOD_OVERRIDE: Record<\n ProcedureType,\n HTTPMethods[]\n> = {\n // never allow GET to do a mutation\n mutation: ['POST'],\n query: ['GET', 'POST'],\n subscription: ['GET', 'POST'],\n};\n\ninterface ResolveHTTPRequestOptions<\n TRouter extends AnyRouter,\n> extends HTTPBaseHandlerOptions<TRouter, Request> {\n createContext: ResolveHTTPRequestOptionsContextFn<TRouter>;\n req: Request;\n path: string;\n /**\n * If the request had an issue before reaching the handler\n */\n error: TRPCError | null;\n}\n\nfunction initResponse<TRouter extends AnyRouter, TRequest>(initOpts: {\n ctx: inferRouterContext<TRouter> | undefined;\n info: TRPCRequestInfo | undefined;\n responseMeta?: HTTPBaseHandlerOptions<TRouter, TRequest>['responseMeta'];\n untransformedJSON:\n | TRPCResponse<unknown, inferRouterError<TRouter>>\n | TRPCResponse<unknown, inferRouterError<TRouter>>[]\n | null;\n errors: TRPCError[];\n headers: Headers;\n}) {\n const {\n ctx,\n info,\n responseMeta,\n untransformedJSON,\n errors = [],\n headers,\n } = initOpts;\n\n let status = untransformedJSON ? getHTTPStatusCode(untransformedJSON) : 200;\n\n const eagerGeneration = !untransformedJSON;\n const data = eagerGeneration\n ? []\n : Array.isArray(untransformedJSON)\n ? untransformedJSON\n : [untransformedJSON];\n\n const meta =\n responseMeta?.({\n ctx,\n info,\n paths: info?.calls.map((call) => call.path),\n data,\n errors,\n eagerGeneration,\n type:\n info?.calls.find((call) => call.procedure?._def.type)?.procedure?._def\n .type ?? 'unknown',\n }) ?? {};\n\n if (meta.headers) {\n if (meta.headers instanceof Headers) {\n for (const [key, value] of meta.headers.entries()) {\n headers.append(key, value);\n }\n } else {\n /**\n * @deprecated, delete in v12\n */\n for (const [key, value] of Object.entries(meta.headers)) {\n if (Array.isArray(value)) {\n for (const v of value) {\n headers.append(key, v);\n }\n } else if (typeof value === 'string') {\n headers.set(key, value);\n }\n }\n }\n }\n if (meta.status) {\n status = meta.status;\n }\n\n return {\n status,\n };\n}\n\nfunction caughtErrorToData<TRouter extends AnyRouter>(\n cause: unknown,\n errorOpts: {\n opts: Pick<\n ResolveHTTPRequestOptions<TRouter>,\n 'onError' | 'req' | 'router'\n >;\n ctx: inferRouterContext<TRouter> | undefined;\n type: ProcedureType | 'unknown';\n path?: string;\n input?: unknown;\n },\n) {\n const { router, req, onError } = errorOpts.opts;\n const error = getTRPCErrorFromUnknown(cause);\n onError?.({\n error,\n path: errorOpts.path,\n input: errorOpts.input,\n ctx: errorOpts.ctx,\n type: errorOpts.type,\n req,\n });\n const untransformedJSON = {\n error: getErrorShape({\n config: router._def._config,\n error,\n type: errorOpts.type,\n path: errorOpts.path,\n input: errorOpts.input,\n ctx: errorOpts.ctx,\n }),\n };\n const transformedJSON = transformTRPCResponse(\n router._def._config,\n untransformedJSON,\n );\n const body = JSON.stringify(transformedJSON);\n return {\n error,\n untransformedJSON,\n body,\n };\n}\n\n/**\n * Check if a value is a stream-like object\n * - if it's an async iterable\n * - if it's an object with async iterables or promises\n */\nfunction isDataStream(v: unknown) {\n if (!isObject(v)) {\n return false;\n }\n\n if (isAsyncIterable(v)) {\n return true;\n }\n\n return (\n Object.values(v).some(isPromise) || Object.values(v).some(isAsyncIterable)\n );\n}\n\ntype ResultTuple<T> = [undefined, T] | [TRPCError, undefined];\n\nexport async function resolveResponse<TRouter extends AnyRouter>(\n opts: ResolveHTTPRequestOptions<TRouter>,\n): Promise<Response> {\n const { router, req } = opts;\n const headers = new Headers([['vary', 'trpc-accept, accept']]);\n const config = router._def._config;\n\n const url = new URL(req.url);\n\n if (req.method === 'HEAD') {\n // can be used for lambda warmup\n return new Response(null, {\n status: 204,\n });\n }\n\n const allowBatching = opts.allowBatching ?? opts.batching?.enabled ?? true;\n const allowMethodOverride =\n (opts.allowMethodOverride ?? false) && req.method === 'POST';\n\n type $Context = inferRouterContext<TRouter>;\n\n const infoTuple: ResultTuple<TRPCRequestInfo> = await run(async () => {\n try {\n return [\n undefined,\n await getRequestInfo({\n req,\n path: decodeURIComponent(opts.path),\n router,\n searchParams: url.searchParams,\n headers: opts.req.headers,\n url,\n maxBatchSize: opts.maxBatchSize,\n }),\n ];\n } catch (cause) {\n return [getTRPCErrorFromUnknown(cause), undefined];\n }\n });\n\n interface ContextManager {\n valueOrUndefined: () => $Context | undefined;\n value: () => $Context;\n create: (info: TRPCRequestInfo) => Promise<void>;\n }\n const ctxManager: ContextManager = run(() => {\n let result: ResultTuple<$Context> | undefined = undefined;\n return {\n valueOrUndefined: () => {\n if (!result) {\n return undefined;\n }\n return result[1];\n },\n value: () => {\n const [err, ctx] = result!;\n if (err) {\n throw err;\n }\n return ctx;\n },\n create: async (info) => {\n if (result) {\n throw new Error(\n 'This should only be called once - report a bug in tRPC',\n );\n }\n try {\n const ctx = await opts.createContext({\n info,\n });\n result = [undefined, ctx];\n } catch (cause) {\n result = [getTRPCErrorFromUnknown(cause), undefined];\n }\n },\n };\n });\n\n const methodMapper = allowMethodOverride\n ? TYPE_ACCEPTED_METHOD_MAP_WITH_METHOD_OVERRIDE\n : TYPE_ACCEPTED_METHOD_MAP;\n\n /**\n * @deprecated\n */\n const isStreamCall = getAcceptHeader(req.headers) === 'application/jsonl';\n\n const experimentalSSE = config.sse?.enabled ?? true;\n try {\n const [infoError, info] = infoTuple;\n if (infoError) {\n throw infoError;\n }\n if (info.isBatchCall && !allowBatching) {\n throw new TRPCError({\n code: 'BAD_REQUEST',\n message: `Batching is not enabled on the server`,\n });\n }\n /* istanbul ignore if -- @preserve */\n if (isStreamCall && !info.isBatchCall) {\n throw new TRPCError({\n message: `Streaming requests must be batched (you can do a batch of 1)`,\n code: 'BAD_REQUEST',\n });\n }\n await ctxManager.create(info);\n\n interface RPCResultOk {\n data: unknown;\n signal?: AbortSignal;\n }\n type RPCResult = ResultTuple<RPCResultOk>;\n const rpcCalls = info.calls.map(async (call): Promise<RPCResult> => {\n const proc = call.procedure;\n const combinedAbort = combinedAbortController(opts.req.signal);\n try {\n if (opts.error) {\n throw opts.error;\n }\n\n if (!proc) {\n throw new TRPCError({\n code: 'NOT_FOUND',\n message: `No procedure found on path \"${call.path}\"`,\n });\n }\n\n if (!methodMapper[proc._def.type].includes(req.method as HTTPMethods)) {\n throw new TRPCError({\n code: 'METHOD_NOT_SUPPORTED',\n message: `Unsupported ${req.method}-request to ${proc._def.type} procedure at path \"${call.path}\"`,\n });\n }\n\n if (proc._def.type === 'subscription') {\n /* istanbul ignore if -- @preserve */\n if (info.isBatchCall) {\n throw new TRPCError({\n code: 'BAD_REQUEST',\n message: `Cannot batch subscription calls`,\n });\n }\n\n if (config.sse?.maxDurationMs) {\n function cleanup() {\n clearTimeout(timer);\n combinedAbort.signal.removeEventListener('abort', cleanup);\n\n combinedAbort.controller.abort();\n }\n const timer = setTimeout(cleanup, config.sse.maxDurationMs);\n combinedAbort.signal.addEventListener('abort', cleanup);\n }\n }\n const data: unknown = await proc({\n path: call.path,\n getRawInput: call.getRawInput,\n ctx: ctxManager.value(),\n type: proc._def.type,\n signal: combinedAbort.signal,\n batchIndex: call.batchIndex,\n });\n return [\n undefined,\n {\n data,\n signal:\n proc._def.type === 'subscription'\n ? combinedAbort.signal\n : undefined,\n },\n ];\n } catch (cause) {\n const error = getTRPCErrorFromUnknown(cause);\n const input = call.result();\n\n opts.onError?.({\n error,\n path: call.path,\n input,\n ctx: ctxManager.valueOrUndefined(),\n type: call.procedure?._def.type ?? 'unknown',\n req: opts.req,\n });\n\n return [error, undefined];\n }\n });\n\n // ----------- response handlers -----------\n if (!info.isBatchCall) {\n const [call] = info.calls;\n const [error, result] = await rpcCalls[0]!;\n\n switch (info.type) {\n case 'unknown':\n case 'mutation':\n case 'query': {\n // httpLink\n headers.set('content-type', 'application/json');\n\n if (isDataStream(result?.data)) {\n throw new TRPCError({\n code: 'UNSUPPORTED_MEDIA_TYPE',\n message:\n 'Cannot use stream-like response in non-streaming request - use httpBatchStreamLink',\n });\n }\n const res: TRPCResponse<unknown, inferRouterError<TRouter>> = error\n ? {\n error: getErrorShape({\n config,\n ctx: ctxManager.valueOrUndefined(),\n error,\n input: call!.result(),\n path: call!.path,\n type: info.type,\n }),\n }\n : { result: { data: result.data } };\n\n const headResponse = initResponse({\n ctx: ctxManager.valueOrUndefined(),\n info,\n responseMeta: opts.responseMeta,\n errors: error ? [error] : [],\n headers,\n untransformedJSON: [res],\n });\n return new Response(\n JSON.stringify(transformTRPCResponse(config, res)),\n {\n status: headResponse.status,\n headers,\n },\n );\n }\n case 'subscription': {\n // httpSubscriptionLink\n\n const iterable: AsyncIterable<unknown> = run(() => {\n if (error) {\n return errorToAsyncIterable(error);\n }\n if (!experimentalSSE) {\n return errorToAsyncIterable(\n new TRPCError({\n code: 'METHOD_NOT_SUPPORTED',\n message: 'Missing experimental flag \"sseSubscriptions\"',\n }),\n );\n }\n\n if (!isObservable(result.data) && !isAsyncIterable(result.data)) {\n return errorToAsyncIterable(\n new TRPCError({\n message: `Subscription ${\n call!.path\n } did not return an observable or a AsyncGenerator`,\n code: 'INTERNAL_SERVER_ERROR',\n }),\n );\n }\n const dataAsIterable = isObservable(result.data)\n ? observableToAsyncIterable(result.data, opts.req.signal)\n : result.data;\n return dataAsIterable;\n });\n\n const stream = sseStreamProducer({\n ...config.sse,\n data: iterable,\n serialize: (v) => config.transformer.output.serialize(v),\n formatError(errorOpts) {\n const error = getTRPCErrorFromUnknown(errorOpts.error);\n const input = call?.result();\n const path = call?.path;\n const type = call?.procedure?._def.type ?? 'unknown';\n\n opts.onError?.({\n error,\n path,\n input,\n ctx: ctxManager.valueOrUndefined(),\n req: opts.req,\n type,\n });\n\n const shape = getErrorShape({\n config,\n ctx: ctxManager.valueOrUndefined(),\n error,\n input,\n path,\n type,\n });\n\n return shape;\n },\n });\n for (const [key, value] of Object.entries(sseHeaders)) {\n headers.set(key, value);\n }\n\n const headResponse = initResponse({\n ctx: ctxManager.valueOrUndefined(),\n info,\n responseMeta: opts.responseMeta,\n errors: [],\n headers,\n untransformedJSON: null,\n });\n\n const abortSignal = result?.signal;\n let responseBody: ReadableStream<Uint8Array> = stream;\n\n // Fixes: https://github.com/trpc/trpc/issues/7094\n if (abortSignal) {\n const reader = stream.getReader();\n const onAbort = () => void reader.cancel();\n if (abortSignal.aborted) {\n onAbort();\n } else {\n abortSignal.addEventListener('abort', onAbort, { once: true });\n }\n\n responseBody = new ReadableStream({\n async pull(controller) {\n const chunk = await reader.read();\n if (chunk.done) {\n abortSignal.removeEventListener('abort', onAbort);\n controller.close();\n } else {\n controller.enqueue(chunk.value);\n }\n },\n cancel() {\n abortSignal.removeEventListener('abort', onAbort);\n return reader.cancel();\n },\n });\n }\n\n return new Response(responseBody, {\n headers,\n status: headResponse.status,\n });\n }\n }\n }\n\n // batch response handlers\n if (info.accept === 'application/jsonl') {\n // httpBatchStreamLink\n headers.set('content-type', 'application/json');\n headers.set('transfer-encoding', 'chunked');\n const headResponse = initResponse({\n ctx: ctxManager.valueOrUndefined(),\n info,\n responseMeta: opts.responseMeta,\n errors: [],\n headers,\n untransformedJSON: null,\n });\n const stream = jsonlStreamProducer({\n ...config.jsonl,\n /**\n * Example structure for `maxDepth: 4`:\n * {\n * // 1\n * 0: {\n * // 2\n * result: {\n * // 3\n * data: // 4\n * }\n * }\n * }\n */\n maxDepth: Infinity,\n data: rpcCalls.map(async (res, index) => {\n const [error, result] = await res;\n\n const call = info.calls[index];\n\n if (error) {\n return {\n error: getErrorShape({\n config,\n ctx: ctxManager.valueOrUndefined(),\n error,\n input: call!.result(),\n path: call!.path,\n type: call!.procedure?._def.type ?? 'unknown',\n }),\n };\n }\n\n /**\n * Not very pretty, but we need to wrap nested data in promises\n * Our stream producer will only resolve top-level async values or async values that are directly nested in another async value\n */\n const iterable = isObservable(result.data)\n ? observableToAsyncIterable(result.data, opts.req.signal)\n : Promise.resolve(result.data);\n return {\n result: Promise.resolve({\n data: iterable,\n }),\n };\n }),\n serialize: (data) => config.transformer.output.serialize(data),\n onError: (cause) => {\n opts.onError?.({\n error: getTRPCErrorFromUnknown(cause.error),\n path: undefined,\n input: undefined,\n ctx: ctxManager.valueOrUndefined(),\n req: opts.req,\n type: info?.type ?? 'unknown',\n });\n },\n\n formatError(errorOpts) {\n const call = info?.calls[errorOpts.path[0] as any];\n\n const error = getTRPCErrorFromUnknown(errorOpts.error);\n const input = call?.result();\n const path = call?.path;\n const type = call?.procedure?._def.type ?? 'unknown';\n\n // no need to call `onError` here as it will be propagated through the stream itself\n\n const shape = getErrorShape({\n config,\n ctx: ctxManager.valueOrUndefined(),\n error,\n input,\n path,\n type,\n });\n\n return shape;\n },\n });\n\n return new Response(stream, {\n headers,\n status: headResponse.status,\n });\n }\n\n // httpBatchLink\n /**\n * Non-streaming response:\n * - await all responses in parallel, blocking on the slowest one\n * - create headers with known response body\n * - return a complete HTTPResponse\n */\n headers.set('content-type', 'application/json');\n const results: RPCResult[] = (await Promise.all(rpcCalls)).map(\n (res): RPCResult => {\n const [error, result] = res;\n if (error) {\n return res;\n }\n\n if (isDataStream(result.data)) {\n return [\n new TRPCError({\n code: 'UNSUPPORTED_MEDIA_TYPE',\n message:\n 'Cannot use stream-like response in non-streaming request - use httpBatchStreamLink',\n }),\n undefined,\n ];\n }\n return res;\n },\n );\n const resultAsRPCResponse = results.map(\n (\n [error, result],\n index,\n ): TRPCResponse<unknown, inferRouterError<TRouter>> => {\n const call = info.calls[index]!;\n if (error) {\n return {\n error: getErrorShape({\n config,\n ctx: ctxManager.valueOrUndefined(),\n error,\n input: call.result(),\n path: call.path,\n type: call.procedure?._def.type ?? 'unknown',\n }),\n };\n }\n return {\n result: { data: result.data },\n };\n },\n );\n\n const errors = results\n .map(([error]) => error)\n .filter(Boolean) as TRPCError[];\n\n const headResponse = initResponse({\n ctx: ctxManager.valueOrUndefined(),\n info,\n responseMeta: opts.responseMeta,\n untransformedJSON: resultAsRPCResponse,\n errors,\n headers,\n });\n\n return new Response(\n JSON.stringify(transformTRPCResponse(config, resultAsRPCResponse)),\n {\n status: headResponse.status,\n headers,\n },\n );\n } catch (cause) {\n const [_infoError, info] = infoTuple;\n const ctx = ctxManager.valueOrUndefined();\n // we get here if\n // - batching is called when it's not enabled\n // - `createContext()` throws\n // - `router._def._config.transformer.output.serialize()` throws\n // - post body is too large\n // - input deserialization fails\n // - `errorFormatter` return value is malformed\n const { error, untransformedJSON, body } = caughtErrorToData(cause, {\n opts,\n ctx: ctxManager.valueOrUndefined(),\n type: info?.type ?? 'unknown',\n });\n\n const headResponse = initResponse({\n ctx,\n info,\n responseMeta: opts.responseMeta,\n untransformedJSON,\n errors: [error],\n headers,\n });\n\n return new Response(body, {\n status: headResponse.status,\n headers,\n });\n }\n}\n","export * from '../client/components/navigation.react-server'\n","import {\n HTTP_ERROR_FALLBACK_ERROR_CODE,\n type HTTPAccessFallbackError,\n} from './http-access-fallback/http-access-fallback'\n\n// TODO: Add `forbidden` docs\n/**\n * @experimental\n * This function allows you to render the [forbidden.js file](https://nextjs.org/docs/app/api-reference/file-conventions/forbidden)\n * within a route segment as well as inject a tag.\n *\n * `forbidden()` can be used in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).\n *\n * Read more: [Next.js Docs: `forbidden`](https://nextjs.org/docs/app/api-reference/functions/forbidden)\n */\n\nconst DIGEST = `${HTTP_ERROR_FALLBACK_ERROR_CODE};403`\n\nexport function forbidden(): never {\n if (!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS) {\n throw new Error(\n `\\`forbidden()\\` is experimental and only allowed to be enabled when \\`experimental.authInterrupts\\` is enabled.`\n )\n }\n\n const error = new Error(DIGEST) as HTTPAccessFallbackError\n ;(error as HTTPAccessFallbackError).digest = DIGEST\n throw error\n}\n","export const HTTPAccessErrorStatus = {\n NOT_FOUND: 404,\n FORBIDDEN: 403,\n UNAUTHORIZED: 401,\n}\n\nconst ALLOWED_CODES = new Set(Object.values(HTTPAccessErrorStatus))\n\nexport const HTTP_ERROR_FALLBACK_ERROR_CODE = 'NEXT_HTTP_ERROR_FALLBACK'\n\nexport type HTTPAccessFallbackError = Error & {\n digest: `${typeof HTTP_ERROR_FALLBACK_ERROR_CODE};${string}`\n}\n\n/**\n * Checks an error to determine if it's an error generated by\n * the HTTP navigation APIs `notFound()`, `forbidden()` or `unauthorized()`.\n *\n * @param error the error that may reference a HTTP access error\n * @returns true if the error is a HTTP access error\n */\nexport function isHTTPAccessFallbackError(\n error: unknown\n): error is HTTPAccessFallbackError {\n if (\n typeof error !== 'object' ||\n error === null ||\n !('digest' in error) ||\n typeof error.digest !== 'string'\n ) {\n return false\n }\n const [prefix, httpStatus] = error.digest.split(';')\n\n return (\n prefix === HTTP_ERROR_FALLBACK_ERROR_CODE &&\n ALLOWED_CODES.has(Number(httpStatus))\n )\n}\n\nexport function getAccessFallbackHTTPStatus(\n error: HTTPAccessFallbackError\n): number {\n const httpStatus = error.digest.split(';')[1]\n return Number(httpStatus)\n}\n\nexport function getAccessFallbackErrorTypeByStatus(\n status: number\n): 'not-found' | 'forbidden' | 'unauthorized' | undefined {\n switch (status) {\n case 401:\n return 'unauthorized'\n case 403:\n return 'forbidden'\n case 404:\n return 'not-found'\n default:\n return\n }\n}\n","import {\n isHTTPAccessFallbackError,\n type HTTPAccessFallbackError,\n} from './http-access-fallback/http-access-fallback'\nimport { isRedirectError, type RedirectError } from './redirect-error'\n\n/**\n * Returns true if the error is a navigation signal error. These errors are\n * thrown by user code to perform navigation operations and interrupt the React\n * render.\n */\nexport function isNextRouterError(\n error: unknown\n): error is RedirectError | HTTPAccessFallbackError {\n return isRedirectError(error) || isHTTPAccessFallbackError(error)\n}\n","import { ReadonlyURLSearchParams } from './readonly-url-search-params'\n\nexport function unstable_isUnrecognizedActionError(): boolean {\n throw new Error(\n '`unstable_isUnrecognizedActionError` can only be used on the client.'\n )\n}\n\nexport { redirect, permanentRedirect } from './redirect'\nexport { notFound } from './not-found'\nexport { forbidden } from './forbidden'\nexport { unauthorized } from './unauthorized'\nexport { unstable_rethrow } from './unstable-rethrow'\nexport { ReadonlyURLSearchParams }\n\nexport const RedirectType = {\n push: 'push',\n replace: 'replace',\n} as const\n","import {\n HTTP_ERROR_FALLBACK_ERROR_CODE,\n type HTTPAccessFallbackError,\n} from './http-access-fallback/http-access-fallback'\n\n/**\n * This function allows you to render the [not-found.js file](https://nextjs.org/docs/app/api-reference/file-conventions/not-found)\n * within a route segment as well as inject a tag.\n *\n * `notFound()` can be used in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).\n *\n * - In a Server Component, this will insert a `<meta name=\"robots\" content=\"noindex\" />` meta tag and set the status code to 404.\n * - In a Route Handler or Server Action, it will serve a 404 to the caller.\n *\n * Read more: [Next.js Docs: `notFound`](https://nextjs.org/docs/app/api-reference/functions/not-found)\n */\n\nconst DIGEST = `${HTTP_ERROR_FALLBACK_ERROR_CODE};404`\n\nexport function notFound(): never {\n const error = new Error(DIGEST) as HTTPAccessFallbackError\n ;(error as HTTPAccessFallbackError).digest = DIGEST\n\n throw error\n}\n","/**\n * ReadonlyURLSearchParams implementation shared between client and server.\n * This file is intentionally not marked as 'use client' or 'use server'\n * so it can be imported by both environments.\n */\n\n/** @internal */\nclass ReadonlyURLSearchParamsError extends Error {\n constructor() {\n super(\n 'Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams'\n )\n }\n}\n\n/**\n * A read-only version of URLSearchParams that throws errors when mutation methods are called.\n * This ensures that the URLSearchParams returned by useSearchParams() cannot be mutated.\n */\nexport class ReadonlyURLSearchParams extends URLSearchParams {\n /** @deprecated Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams */\n append() {\n throw new ReadonlyURLSearchParamsError()\n }\n /** @deprecated Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams */\n delete() {\n throw new ReadonlyURLSearchParamsError()\n }\n /** @deprecated Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams */\n set() {\n throw new ReadonlyURLSearchParamsError()\n }\n /** @deprecated Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams */\n sort() {\n throw new ReadonlyURLSearchParamsError()\n }\n}\n","import { RedirectStatusCode } from './redirect-status-code'\n\nexport const REDIRECT_ERROR_CODE = 'NEXT_REDIRECT'\n\nexport type RedirectType = 'push' | 'replace'\n\nexport type RedirectError = Error & {\n digest: `${typeof REDIRECT_ERROR_CODE};${RedirectType};${string};${RedirectStatusCode};`\n}\n\n/**\n * Checks an error to determine if it's an error generated by the\n * `redirect(url)` helper.\n *\n * @param error the error that may reference a redirect error\n * @returns true if the error is a redirect error\n */\nexport function isRedirectError(error: unknown): error is RedirectError {\n if (\n typeof error !== 'object' ||\n error === null ||\n !('digest' in error) ||\n typeof error.digest !== 'string'\n ) {\n return false\n }\n\n const digest = error.digest.split(';')\n const [errorCode, type] = digest\n const destination = digest.slice(2, -2).join(';')\n const status = digest.at(-2)\n\n const statusCode = Number(status)\n\n return (\n errorCode === REDIRECT_ERROR_CODE &&\n (type === 'replace' || type === 'push') &&\n typeof destination === 'string' &&\n !isNaN(statusCode) &&\n statusCode in RedirectStatusCode\n )\n}\n","export enum RedirectStatusCode {\n SeeOther = 303,\n TemporaryRedirect = 307,\n PermanentRedirect = 308,\n}\n","import { RedirectStatusCode } from './redirect-status-code'\nimport {\n type RedirectType,\n type RedirectError,\n isRedirectError,\n REDIRECT_ERROR_CODE,\n} from './redirect-error'\nimport { actionAsyncStorage } from './server-async-storage'\n\nexport function getRedirectError(\n url: string,\n type: RedirectType,\n statusCode: RedirectStatusCode = RedirectStatusCode.TemporaryRedirect\n): RedirectError {\n const error = new Error(REDIRECT_ERROR_CODE) as RedirectError\n error.digest = `${REDIRECT_ERROR_CODE};${type};${url};${statusCode};`\n return error\n}\n\n/**\n * This function allows you to redirect the user to another URL. It can be used in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).\n *\n * - In a Server Component, this will insert a meta tag to redirect the user to the target page.\n * - In a Route Handler, it will serve a 307 to the caller.\n * - In a Server Action, it will perform a client-side navigation when JavaScript is available or serve a 303 for a progressive enhancement form submission.\n * - In a Server Action, type defaults to 'push' and 'replace' elsewhere.\n *\n * Read more: [Next.js Docs: `redirect`](https://nextjs.org/docs/app/api-reference/functions/redirect)\n */\nexport function redirect(\n /** The URL to redirect to */\n url: string,\n type?: RedirectType\n): never {\n type ??= actionAsyncStorage?.getStore()?.isAction ? 'push' : 'replace'\n\n throw getRedirectError(url, type, RedirectStatusCode.TemporaryRedirect)\n}\n\n/**\n * This function allows you to redirect the user to another URL. It can be used in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).\n *\n * - In a Server Component, this will insert a meta tag to redirect the user to the target page.\n * - In a Route Handler, it will serve a 308 to the caller.\n * - In a Server Action, it will perform a client-side navigation when JavaScript is available or serve a 303 for a progressive enhancement form submission.\n *\n * Read more: [Next.js Docs: `redirect`](https://nextjs.org/docs/app/api-reference/functions/redirect)\n */\nexport function permanentRedirect(\n /** The URL to redirect to */\n url: string,\n type: RedirectType = 'replace'\n): never {\n throw getRedirectError(url, type, RedirectStatusCode.PermanentRedirect)\n}\n\n/**\n * Returns the encoded URL from the error if it's a RedirectError, null\n * otherwise. Note that this does not validate the URL returned.\n *\n * @param error the error that may be a redirect error\n * @return the url if the error was a redirect error\n */\nexport function getURLFromRedirectError(error: RedirectError): string\nexport function getURLFromRedirectError(error: unknown): string | null {\n if (!isRedirectError(error)) return null\n\n // Slices off the beginning of the digest that contains the code and the\n // separating ';'.\n return error.digest.split(';').slice(2, -2).join(';')\n}\n\nexport function getRedirectTypeFromError(error: RedirectError): RedirectType {\n if (!isRedirectError(error)) {\n throw new Error('Not a redirect error')\n }\n\n return error.digest.split(';', 2)[1] as RedirectType\n}\n\nexport function getRedirectStatusCodeFromError(error: RedirectError): number {\n if (!isRedirectError(error)) {\n throw new Error('Not a redirect error')\n }\n\n return Number(error.digest.split(';').at(-2))\n}\n","// Client-safe access to the server-only async-storage singletons. On the\n// server these re-export the real storages; in the browser bundle this module\n// is aliased to `./server-async-storage.browser` (see\n// scripts/generate-browser-variant-aliases.mjs), which exports `undefined`\n// stubs so the AsyncLocalStorage modules are never bundled into the client.\n// Consumers must guard usage so the stubs are not dereferenced in the browser.\nexport { actionAsyncStorage } from '../../server/app-render/action-async-storage.external'\nexport { workAsyncStorage } from '../../server/app-render/work-async-storage.external'\nexport { workUnitAsyncStorage } from '../../server/app-render/work-unit-async-storage.external'\n","import {\n HTTP_ERROR_FALLBACK_ERROR_CODE,\n type HTTPAccessFallbackError,\n} from './http-access-fallback/http-access-fallback'\n\n// TODO: Add `unauthorized` docs\n/**\n * @experimental\n * This function allows you to render the [unauthorized.js file](https://nextjs.org/docs/app/api-reference/file-conventions/unauthorized)\n * within a route segment as well as inject a tag.\n *\n * `unauthorized()` can be used in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).\n *\n *\n * Read more: [Next.js Docs: `unauthorized`](https://nextjs.org/docs/app/api-reference/functions/unauthorized)\n */\n\nconst DIGEST = `${HTTP_ERROR_FALLBACK_ERROR_CODE};401`\n\nexport function unauthorized(): never {\n if (!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS) {\n throw new Error(\n `\\`unauthorized()\\` is experimental and only allowed to be used when \\`experimental.authInterrupts\\` is enabled.`\n )\n }\n\n const error = new Error(DIGEST) as HTTPAccessFallbackError\n ;(error as HTTPAccessFallbackError).digest = DIGEST\n throw error\n}\n","import { isHangingPromiseRejectionError } from '../../server/dynamic-rendering-utils'\nimport { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'\nimport { isNextRouterError } from './is-next-router-error'\nimport { isPrerenderInterruptedError } from '../../server/app-render/dynamic-rendering'\nimport { isDynamicServerError } from './hooks-server-context'\n\n/**\n * This function should be used to rethrow internal Next.js errors so that they can be handled by the framework.\n * When wrapping an API that uses errors to interrupt control flow, you should use this function before you do any error handling.\n * This function will rethrow the error if it is a Next.js error so it can be handled, otherwise it will do nothing.\n *\n * In the browser bundle this module is aliased to `./unstable-rethrow.browser`, which performs a\n * subset of these checks (the server-only ones can never occur in the browser). This default\n * module holds the full server logic and is used on every server runtime (Node, edge) and in any\n * context where the alias does not apply.\n *\n * Read more: [Next.js Docs: `unstable_rethrow`](https://nextjs.org/docs/app/api-reference/functions/unstable_rethrow)\n */\nexport function unstable_rethrow(error: unknown): void {\n if (\n isNextRouterError(error) ||\n isBailoutToCSRError(error) ||\n isDynamicServerError(error) ||\n isHangingPromiseRejectionError(error) ||\n isPrerenderInterruptedError(error)\n ) {\n throw error\n }\n\n if (error instanceof Error && 'cause' in error) {\n unstable_rethrow(error.cause)\n }\n}\n","// This has to be a shared module which is shared between client component error boundary and dynamic component\nconst BAILOUT_TO_CSR = 'BAILOUT_TO_CLIENT_SIDE_RENDERING'\n\n/** An error that should be thrown when we want to bail out to client-side rendering. */\nexport class BailoutToCSRError extends Error {\n public readonly digest = BAILOUT_TO_CSR\n\n constructor(public readonly reason: string) {\n super(`Bail out to client-side rendering: ${reason}`)\n }\n}\n\n/** Checks if a passed argument is an error that is thrown if we want to bail out to client-side rendering. */\nexport function isBailoutToCSRError(err: unknown): err is BailoutToCSRError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === BAILOUT_TO_CSR\n}\n","import { globalConfig } from \"./core.js\";\n// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function toZod() {\n return (schema) => schema;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\n// the accessor lives on a shared prototype: an own accessor makes every box a dictionary-mode object (~360 B and a slow load per read against ~100 B and an inlined getter here)\nclass Cached {\n constructor(getter) {\n this._getter = getter;\n this._value = undefined;\n }\n get value() {\n const getter = this._getter;\n if (getter !== undefined) {\n this._value = getter();\n this._getter = undefined;\n }\n return this._value;\n }\n}\nexport function cached(getter) {\n return new Cached(getter);\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const ratio = val / step;\n const roundedRatio = Math.round(ratio);\n // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin.\n const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1);\n if (Math.abs(ratio - roundedRatio) < tolerance)\n return 0;\n return ratio - roundedRatio;\n}\nconst EVALUATING = /* @__PURE__*/ Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\n/**\n * Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it.\n *\n * Its keys and descriptors read without invoking anything, which is what lets a discriminated union check its discriminator, and the cycle walk read a shape, without resolving a getter that references the schema being constructed. A def that answers `shape` from an accessor of its own has none.\n */\nexport function rawShape(def) {\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n return desc?.get ? desc.get.raw : desc?.value;\n}\n// where a builder reads its source's keys and descriptors, resolving only a shape a def answers for itself. A shape resolves by object spread, so only its enumerable keys are ever part of it.\nfunction sourceShape(schema) {\n return rawShape(schema._zod.def) ?? schema._zod.def.shape;\n}\n// a key whose value is not settled yet, self-caching so every read after the first gets the same one\nfunction deferProp(target, key, getter) {\n Object.defineProperty(target, key, {\n get() {\n const value = getter();\n assignProp(this, key, value);\n return value;\n },\n enumerable: true,\n configurable: true,\n });\n}\n// Writes a settled key. A plain assignment is much cheaper than `defineProperty` and produces the same descriptor, but it runs whatever setter already answers to the key — an accessor this shape deferred, or an inherited one, which `__proto__` has on every object and prototype pollution can add for any name.\nfunction putProp(target, key, value) {\n if (key in target)\n assignProp(target, key, value);\n else\n target[key] = value;\n}\n/**\n * Copies `keys` of `source`'s shape onto `target`, each value passed through `wrap`.\n *\n * A key the source has resolved is copied through now, so the derived shape states it outright and nothing has to resolve it to learn what it holds. A key the source still defers stays deferred, and reads back through the source's own `shape`, so it resolves once and both shapes get that one schema.\n */\nfunction mirrorShape(target, source, keys, wrap) {\n const raw = sourceShape(source);\n for (const key of keys) {\n const desc = Object.getOwnPropertyDescriptor(raw, key);\n if (!desc.enumerable)\n continue;\n if (desc.get) {\n deferProp(target, key, () => {\n const value = source._zod.def.shape[key];\n return wrap ? wrap(value, key) : value;\n });\n }\n else\n putProp(target, key, wrap ? wrap(desc.value, key) : desc.value);\n }\n}\n// same, for a plain shape a caller passed rather than a schema's\nfunction mirrorProps(target, source) {\n for (const key of Reflect.ownKeys(source)) {\n const desc = Object.getOwnPropertyDescriptor(source, key);\n if (!desc.enumerable)\n continue;\n if (desc.get)\n deferProp(target, key, () => source[key]);\n else\n putProp(target, key, desc.value);\n }\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = /* @__PURE__*/ cached(() => {\n // Skip the probe under `jitless`: strict CSPs report the caught `new Function` as a `securitypolicyviolation` even though the throw is swallowed.\n if (globalConfig.jitless) {\n return false;\n }\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n if (o instanceof Map)\n return new Map(o);\n if (o instanceof Set)\n return new Set(o);\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = /* @__PURE__*/ new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = /* @__PURE__*/ new Set([\n \"string\",\n \"number\",\n \"bigint\",\n \"boolean\",\n \"symbol\",\n \"undefined\",\n]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === \"optional\";\n });\n}\n// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle.\nexport const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n}))();\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const newShape = {};\n mirrorShape(newShape, schema, maskedKeys(schema, mask));\n return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));\n}\n// the mask keys that select something, checked against the source's shape without resolving it\nfunction maskedKeys(schema, mask) {\n const raw = sourceShape(schema);\n const keys = [];\n // `for...in` skips symbols, so a symbol in the mask would select nothing\n for (const key of Reflect.ownKeys(mask)) {\n if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) {\n throw new Error(`Unrecognized key: \"${String(key)}\"`);\n }\n if (mask[key])\n keys.push(key);\n }\n return keys;\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const omitted = new Set(maskedKeys(schema, mask));\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key)));\n return clone(schema, mergeDefs(currDef, { shape: newShape, checks: [] }));\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape. Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = sourceShape(schema);\n for (const key of Reflect.ownKeys(shape)) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));\n}\n// the source's keys, then the caller's overlaid on top\nfunction extended(schema, shape) {\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)));\n mirrorProps(newShape, shape);\n return newShape;\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));\n}\nexport function merge(a, b) {\n if (!b?._zod?.def) {\n throw new Error(\"Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.\");\n }\n if (a._zod.def.checks?.length) {\n throw new Error(\".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.\");\n }\n const newShape = {};\n mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a)));\n mirrorShape(newShape, b, Reflect.ownKeys(sourceShape(b)));\n const def = mergeDefs(a._zod.def, {\n shape: newShape,\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: b._zod.def.checks ?? [],\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask, name = \"partial\") {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(`.${name}() cannot be used on object schemas containing refinements`);\n }\n const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class &&\n ((value, key) => (selected && !selected.has(key) ? value : new Class({ type: \"optional\", innerType: value }))));\n return clone(schema, mergeDefs(schema._zod.def, { shape: newShape, checks: [] }));\n}\nexport function required(Class, schema, mask) {\n const selected = mask ? new Set(maskedKeys(schema, mask)) : undefined;\n const newShape = {};\n mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => \n // overwrite with non-optional\n selected && !selected.has(key) ? value : new Class({ type: \"nonoptional\", innerType: value }));\n return clone(schema, mergeDefs(schema._zod.def, { shape: newShape }));\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\n// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined). Used to respect `abort: true` in .refine() even for checks that have a `when` function.\nexport function explicitlyAborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue === false) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\n/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */\n/** The leading size checks of `defChecks` that set an upper bound, each paired with it. */\nexport function sizeCaps(defChecks) {\n const caps = [];\n for (const ch of defChecks ?? []) {\n const d = ch._zod.def;\n // a later check may rewrite the value\n if (!/_(length|size)$|_equals$/.test(d.check))\n break;\n const max = d.maximum ?? d.length ?? d.size;\n if (max >= 0)\n caps.push([max, ch]);\n }\n return caps;\n}\nexport function attachSchema(issues, start, inst) {\n var _a;\n for (let i = start; i < issues.length; i++) {\n (_a = issues[i]).schema ?? (_a.schema = inst);\n }\n}\nexport function finalizeIssue(iss, ctx, config) {\n var _a;\n // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead.\n const traits = iss.inst?._zod?.traits;\n if (traits?.has(\"$ZodType\")) {\n if (traits.has(\"$ZodCheck\"))\n (_a = iss).schema ?? (_a.schema = iss.inst);\n else\n iss.schema = iss.inst;\n }\n // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's.\n const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined;\n const message = iss.message\n ? iss.message\n : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(schemaError?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\");\n // an explicit own-key copy beats object rest with excluded keys, which v8 routes through a generic runtime call; Object.keys rather than for-in so an issue pushed with a prototype does not leak inherited keys, and an own __proto__ key is dropped rather than assigned through the setter\n const full = {};\n for (const k of Object.keys(iss)) {\n if (k === \"inst\" || k === \"schema\" || k === \"continue\" || k === \"input\" || k === \"__proto__\")\n continue;\n full[k] = iss[k];\n }\n full.path ?? (full.path = []);\n full.message = message;\n if (ctx?.reportInput) {\n full.input = iss.input;\n }\n return full;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nconst highSurrogate = /[\\uD800-\\uDBFF]/;\n// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters.\nexport function codePointLength(str) {\n const units = str.length;\n if (!highSurrogate.test(str))\n return units;\n let count = units;\n for (let i = 0; i < units - 1; i++) {\n if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {\n count--;\n i++;\n }\n }\n return count;\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n////////// PROTOTYPE INSTALLERS //////////\n//\n// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see \"The three axes\" in AGENTS.md.\n/**\n * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working.\n *\n * Call this from a `proto` initializer, which runs once per prototype — never per instance.\n */\nexport function members(proto, table) {\n for (const key in table) {\n const desc = Object.getOwnPropertyDescriptor(table, key);\n // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was\n if (desc.get)\n Object.defineProperty(proto, key, { ...desc, enumerable: false });\n // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()`\n else\n defineBound(proto, key, desc.value);\n }\n}\n/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */\nexport function own(inst, key, value, enumerable = true) {\n Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value });\n return value;\n}\n/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */\nexport function hide(inst, key, value) {\n return own(inst, key, value, false);\n}\n/** Adds members a table derives from the instance: each builds on first read and shadows as own data, and assignment shadows the same way, as when these were own properties. */\nexport /*@__NO_SIDE_EFFECTS__*/ function derived(computes, table) {\n for (const key in computes) {\n const compute = computes[key];\n // an object literal's accessor is configurable and enumerable, and `members` copies the descriptor as written\n Object.defineProperty(table, key, {\n configurable: true,\n enumerable: true,\n get() {\n return own(this, key, compute(this));\n },\n set(value) {\n own(this, key, value);\n },\n });\n }\n return table;\n}\nfunction defineBound(proto, key, fn) {\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method\n return this == null ? fn : own(this, key, fn.bind(this));\n },\n set(value) {\n own(this, key, value);\n },\n });\n}\n/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */\nfunction claim(inst, sentinel) {\n const proto = Object.getPrototypeOf(inst);\n // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines.\n return sentinel in proto ? undefined : proto;\n}\n// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped.\nlet installing;\n// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation.\nlet broke = false;\nconst breaker = {\n configurable: true,\n get() {\n broke = true;\n return undefined;\n },\n};\n/**\n * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s\n * constructor, computed from the internals object itself and cached there on\n * first read. One accessor per constructor rather than one per instance.\n */\nexport function defineLazyInternal(inst, key, compute) {\n const proto = Object.getPrototypeOf(inst._zod);\n if (key in proto && installing !== inst._zod) {\n // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type.\n installing = undefined;\n return;\n }\n installing = inst._zod;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again.\n Object.defineProperty(this, key, breaker);\n const outer = broke;\n broke = false;\n try {\n const value = compute(this);\n // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included.\n if (broke)\n delete this[key];\n else\n Object.defineProperty(this, key, { configurable: true, writable: true, value });\n broke = broke || outer;\n return value;\n }\n catch (err) {\n // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read.\n delete this[key];\n broke = broke || outer;\n throw err;\n }\n },\n set(value) {\n Object.defineProperty(this, key, { configurable: true, writable: true, value });\n },\n });\n}\n/**\n * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own\n * data property. One accessor per constructor rather than one per instance, because an own accessor\n * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel.\n */\nexport function installLazyProp(inst, key, make, enumerable) {\n const proto = claim(inst, key);\n if (!proto)\n return;\n Object.defineProperty(proto, key, {\n configurable: true,\n get() {\n // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid.\n const desc = { configurable: true, writable: true, enumerable, value: undefined };\n Object.defineProperty(this, key, desc);\n // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches\n desc.value = make(this);\n Object.defineProperty(this, key, desc);\n return desc.value;\n },\n set(value) {\n Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value });\n },\n });\n}\n/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */\nexport const CONSTANT_CATCH = \"~constantCatch\";\n/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */\nexport function constantCatch(value) {\n const fn = () => value;\n fn[CONSTANT_CATCH] = true;\n return fn;\n}\n","var _a;\nimport { members as installMembers } from \"./util.js\";\n/** A special constant with type `never` */\nexport const NEVER = /*@__PURE__*/ Object.freeze({\n status: \"aborted\",\n});\n/* Shared descriptor for installing `_zod`; defineProperty reads it\n * synchronously, so reusing one object avoids a per-instance allocation. */\nconst _zodDesc = { value: undefined, enumerable: false };\n// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error\nlet _E = \"captureStackTrace\" in Error ? Error : null;\n// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot\nfunction newError(Definition) {\n const E = _E;\n if (E) {\n const saved = E.stackTraceLimit;\n if (typeof saved === \"number\") {\n try {\n E.stackTraceLimit = 0;\n }\n catch {\n _E = null;\n return new Definition();\n }\n try {\n return new Definition();\n }\n finally {\n E.stackTraceLimit = saved;\n }\n }\n }\n return new Definition();\n}\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, \n/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */\nproto, params) {\n // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance.\n const zodProto = {};\n // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy.\n function Internals(def) {\n this.def = def;\n this.constr = _;\n this.traits = new Set();\n }\n Internals.prototype = zodProto;\n const protoMembers = proto;\n // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait.\n const initialized = protoMembers && new WeakSet();\n function init(inst, def) {\n if (!inst._zod) {\n _zodDesc.value = new Internals(def);\n try {\n Object.defineProperty(inst, \"_zod\", _zodDesc);\n }\n finally {\n // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next.\n _zodDesc.value = undefined;\n }\n }\n else if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n if (initialized) {\n // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before.\n const own = Object.getPrototypeOf(inst);\n const ctorProto = inst._zod.constr.prototype;\n let up = own;\n while (up && up !== ctorProto)\n up = Object.getPrototypeOf(up);\n const target = up ?? own;\n if (!initialized.has(target)) {\n initialized.add(target);\n installMembers(target, protoMembers);\n }\n }\n // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype\n const proto = _.prototype;\n for (const k in proto) {\n if (!Object.prototype.hasOwnProperty.call(proto, k))\n continue;\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n const inst = params?.Parent ? newError(Definition) : this;\n init(inst, def);\n const deferred = inst._zod.deferred;\n if (deferred) {\n for (const fn of deferred) {\n fn();\n }\n // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime.\n inst._zod.deferred = undefined;\n }\n // Global post-processor hook. Internal: installed by `import \"zod/compile\"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation.\n const pp = globalThis.__zod_globalConfig?.postProcessor;\n if (pp)\n pp(inst);\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = /*@__PURE__*/ Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\n(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});\nexport const globalConfig = globalThis.__zod_globalConfig;\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","import * as util from \"./util.js\";\nexport class $ZodCyclicError extends Error {\n constructor() {\n super(`Cannot parse a reference cycle that closes through a transform`);\n this.name = \"ZodCyclicError\";\n }\n}\n/** Keyed off the context object every schema in one parse call already shares. */\nconst STATE = \"~memo\";\nconst NO_ISSUES = [];\n// a value a cycle can close through\nfunction isRef(value) {\n return value !== null && typeof value === \"object\";\n}\n// Receivers prefix paths in place, so the cache and every hand-out need their own copies.\nfunction cloneIssues(issues) {\n return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss }));\n}\nconst recursive = /*@__PURE__*/ new WeakMap();\n/** What the walk established, in order of certainty: ordered so the strongest answer among children wins. */\nconst NONE = 0;\nconst ASSUMED = 1;\nconst PROVEN = 2;\n/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */\nfunction isRecursive(inst, stack, resolve) {\n const cached = recursive.get(inst);\n if (cached !== undefined)\n return cached ? PROVEN : NONE;\n // Relative to the walk in progress, so not cached.\n if (stack.has(inst))\n return PROVEN;\n stack.add(inst);\n let result = NONE;\n const check = (child) => {\n if (result !== PROVEN && child?._zod) {\n const answer = isRecursive(child, stack, resolve);\n if (answer > result)\n result = answer;\n }\n };\n // `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen\n const shape = (sh, spread) => {\n let answer = NONE;\n for (const key of Reflect.ownKeys(sh)) {\n const desc = Object.getOwnPropertyDescriptor(sh, key);\n // an object resolves its shape by spread, so a key it does not enumerate is never parsed; `z.properties` reads every own key and so keeps them all\n if (spread && !desc.enumerable)\n continue;\n // resolving runs user code, and a factory mints a fresh subtree per read, so an edge the walk can't follow counts as a cycle\n const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve) : NONE;\n if (child > answer)\n answer = child;\n }\n return answer;\n };\n const merge = (answer) => {\n if (answer > result)\n result = answer;\n };\n const def = inst._zod.def;\n const kind = def.type;\n switch (kind) {\n case \"object\": {\n const raw = util.rawShape(def);\n // a def with no raw shape answers `shape` from an accessor of its own, and running that can mint a whole fresh subtree\n merge(raw ? shape(raw, true) : ASSUMED);\n check(def.catchall);\n break;\n }\n case \"array\":\n check(def.element);\n break;\n case \"tuple\":\n for (const el of def.items)\n check(el);\n check(def.rest);\n break;\n case \"record\":\n case \"map\":\n check(def.keyType);\n check(def.valueType);\n break;\n case \"set\":\n check(def.valueType);\n break;\n case \"union\":\n for (const el of def.options)\n check(el);\n break;\n case \"intersection\":\n check(def.left);\n check(def.right);\n break;\n case \"optional\":\n case \"nullable\":\n case \"default\":\n case \"prefault\":\n case \"catch\":\n case \"readonly\":\n case \"nonoptional\":\n case \"promise\":\n case \"success\":\n check(def.innerType);\n break;\n case \"pipe\":\n check(def.in);\n check(def.out);\n break;\n case \"function\":\n check(def.input);\n check(def.output);\n break;\n // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly\n case \"lazy\": {\n const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : undefined);\n // walked with resolution off: one hop sees past the deferral, and a lazy that yields only another unresolved lazy is generative, so it stops there\n merge(inner ? isRecursive(inner, stack, false) : ASSUMED);\n break;\n }\n // a leaf by choice: `parts` are regex fragments, not data positions\n case \"template_literal\":\n // leaves\n case \"string\":\n case \"number\":\n case \"int\":\n case \"boolean\":\n case \"bigint\":\n case \"symbol\":\n case \"undefined\":\n case \"null\":\n case \"void\":\n case \"never\":\n case \"any\":\n case \"unknown\":\n case \"date\":\n case \"nan\":\n case \"enum\":\n case \"literal\":\n case \"file\":\n case \"transform\":\n case \"custom\":\n break;\n default: {\n // a new built-in kind becomes a compile error here\n kind;\n // a user-defined kind can still hold children, and only its author knows where, so fall back to scanning the def — skipping accessors, since reading one can run user code\n for (const key in def) {\n const desc = Object.getOwnPropertyDescriptor(def, key);\n if (!desc || desc.get)\n continue;\n const value = desc.value;\n if (!value || typeof value !== \"object\")\n continue;\n if (value._zod)\n check(value);\n else if (Array.isArray(value))\n for (const el of value)\n check(el);\n }\n }\n }\n stack.delete(inst);\n return settle(inst, result);\n}\n/** An assumed answer must not outlive the resolution that settles it, so only a certain one is cached. */\nfunction settle(inst, answer) {\n if (answer !== ASSUMED)\n recursive.set(inst, answer === PROVEN);\n return answer;\n}\n/**\n * Whether one parse can re-enter this schema, i.e. its subtree contains a cycle.\n * Exported for `z.compile`, which refuses to compile such a schema: cycle\n * breaking is driven from here off state keyed on the parse context, and a\n * generated fast path has no context to key on.\n */\nexport function isRecursiveSchema(inst) {\n // z.compile never parses, so nothing would ever resolve a lazy for it; it runs once and already treats a throw here as recursive\n return isRecursive(inst, new Set(), true) !== NONE;\n}\nfunction bucketFor(state, inst) {\n let bucket = state.buckets.get(inst);\n if (!bucket) {\n bucket = new WeakMap();\n state.buckets.set(inst, bucket);\n }\n return bucket;\n}\n// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving.\nlet handoff;\n// Allocated but unfinished entries. `alloc` and the matching pop both happen in the synchronous part of a parse, so they nest even when children are async, and one stack serves every schema.\nconst open = [];\nconst memo = {\n alloc(_inst, payload, empty) {\n const bucket = handoff;\n if (!bucket)\n return empty;\n handoff = undefined;\n const entry = { value: empty, issues: null };\n bucket.set(payload.value, entry);\n open.push(entry);\n return empty;\n },\n guard(inst) {\n var _a;\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred.push(() => {\n const base = inst._zod.parse;\n const wrapped = (payload, ctx) => {\n // The value is a placeholder a back-edge is still waiting on, so the cycle closes through this transform. Its output can't exist in time to bind.\n if (ctx.direction !== \"backward\" && isBackEdge(ctx, payload.value))\n throw new $ZodCyclicError();\n return base(payload, ctx);\n };\n inst._zod.parse = wrapped;\n if (inst._zod.run === base)\n inst._zod.run = wrapped;\n });\n },\n attach(inst) {\n var _a;\n let isRecursiveInst;\n let rechecked = false;\n // a recursive schema is re-entered many times per parse and its bucket never changes\n let lastCtx;\n let lastBucket;\n // Wraps `parse` in a deferred so it sees the container's final parse. Core's own deferred copies `parse` into `run` when there are no checks, and it ran first, so `run` is patched to match; with checks, `run` reads `parse` dynamically.\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred.push(() => {\n const base = inst._zod.parse;\n const wrapped = (payload, ctx) => {\n if (isRecursiveInst === undefined) {\n const walked = isRecursive(inst, new Set(), false);\n if (walked === NONE) {\n // Nothing here can ever fire, so take it back out.\n inst._zod.parse = base;\n if (inst._zod.run === wrapped)\n inst._zod.run = base;\n return base(payload, ctx);\n }\n // this parse resolves the deferred edges on its own path, so ask once more before latching\n if (walked === PROVEN || rechecked)\n isRecursiveInst = true;\n else\n rechecked = true;\n }\n const input = payload.value;\n if (!isRef(input))\n return base(payload, ctx);\n let state = ctx[STATE];\n if (!state) {\n state = { buckets: new WeakMap(), backEdges: undefined };\n ctx[STATE] = state;\n }\n let bucket;\n if (lastCtx === ctx) {\n bucket = lastBucket;\n }\n else {\n bucket = bucketFor(state, inst);\n lastCtx = ctx;\n lastBucket = bucket;\n }\n const hit = bucket.get(input);\n if (hit) {\n payload.value = hit.value;\n if (hit.issues) {\n if (hit.issues.length)\n payload.issues.push(...cloneIssues(hit.issues));\n }\n else {\n // Still being parsed: its own checks cover it, so skip them here.\n payload.memo = true;\n state.backEdges ?? (state.backEdges = new WeakSet());\n state.backEdges.add(hit.value);\n }\n return payload;\n }\n handoff = bucket;\n const depth = open.length;\n const result = base(payload, ctx);\n handoff = undefined;\n // A container that rejected its input outright allocated nothing.\n const entry = open.length > depth ? open.pop() : undefined;\n // Both paths written out so the sync one allocates no closure. It runs once per node, and capturing here cost more than everything else combined.\n if (result instanceof Promise) {\n return result.then((r) => {\n if (entry)\n entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES;\n return r;\n });\n }\n if (entry)\n entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES;\n return result;\n };\n inst._zod.parse = wrapped;\n if (inst._zod.run === base)\n inst._zod.run = wrapped;\n });\n },\n};\n/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */\nexport function memoizer() {\n return memo;\n}\n/** Whether this value is a node a back-edge resolved to before it finished. */\nexport function isBackEdge(ctx, value) {\n const backEdges = ctx[STATE]?.backEdges;\n return backEdges !== undefined && isRef(value) && backEdges.has(value);\n}\n","var _a;\nexport const $output = /*@__PURE__*/ Symbol(\"ZodOutput\");\nexport const $input = /*@__PURE__*/ Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n constructor() {\n this._map = new WeakMap();\n this._idmap = new Map();\n }\n add(schema, ..._meta) {\n const meta = _meta[0];\n this._map.set(schema, meta);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.set(meta.id, schema);\n }\n return this;\n }\n clear() {\n this._map = new WeakMap();\n this._idmap = new Map();\n return this;\n }\n remove(schema) {\n const meta = this._map.get(schema);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.delete(meta.id);\n }\n this._map.delete(schema);\n return this;\n }\n get(schema) {\n // return this._map.get(schema) as any;\n // inherit metadata\n const p = schema._zod.parent;\n if (p) {\n const pm = { ...(this.get(p) ?? {}) };\n delete pm.id; // do not inherit id\n const f = { ...pm, ...this._map.get(schema) };\n return Object.keys(f).length ? f : undefined;\n }\n return this._map.get(schema);\n }\n has(schema) {\n return this._map.has(schema);\n }\n}\n// registries\nexport function registry() {\n return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n","import * as util from \"./util.js\";\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const cuid = /^[cC][0-9a-z]{6,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\nexport function nanoidOfLength(length) {\n return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`);\n}\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n if (!version)\n return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;\n return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport const rfc5322Email = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = unicodeEmail;\nexport const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\n// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match. The leading lookahead then demands one anchor — a pictograph, a regional indicator, or the enclosing keycap — because `\\p{Emoji_Component}` on its own covers ASCII digits, `#`, `*`, ZWJ, variation selectors and skin tone modifiers, none of which is an emoji without a base.\nconst _emoji = `^(?=[\\\\s\\\\S]*[\\\\p{Extended_Pictographic}\\\\p{Regional_Indicator}\\\\u20E3])[\\\\p{Extended_Pictographic}\\\\p{Emoji_Component}]+$`;\nexport function emoji() {\n return new RegExp(_emoji, \"u\");\n}\nexport const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nexport const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;\nexport const mac = (delimiter) => {\n const escapedDelim = util.escapeRegex(delimiter ?? \":\");\n return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);\n};\nexport const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/;\nexport const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const hostname = /^(?=.{1,253}\\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\\.?$/;\nexport const domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,63}$/;\nexport const httpProtocol = /^https?$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro).\nexport const creditCard = /^\\d(?:[ -]?\\d){11,18}$/;\n// ISO 4217 alpha codes from the SIX list, regenerated by scripts/update-iso-4217.ts\nexport const currencyCode = /^(?:AED|AFN|ALL|AMD|AOA|ARS|AUD|AWG|AZN|BAM|BBD|BDT|BHD|BIF|BMD|BND|BOB|BOV|BRL|BSD|BTN|BWP|BYN|BZD|CAD|CDF|CHE|CHF|CHW|CLF|CLP|CNY|COP|COU|CRC|CUP|CVE|CZK|DJF|DKK|DOP|DZD|EGP|ERN|ETB|EUR|FJD|FKP|GBP|GEL|GHS|GIP|GMD|GNF|GTQ|GYD|HKD|HNL|HTG|HUF|IDR|ILS|INR|IQD|IRR|ISK|JMD|JOD|JPY|KES|KGS|KHR|KMF|KPW|KRW|KWD|KYD|KZT|LAK|LBP|LKR|LRD|LSL|LYD|MAD|MDL|MGA|MKD|MMK|MNT|MOP|MRU|MUR|MVR|MWK|MXN|MXV|MYR|MZN|NAD|NGN|NIO|NOK|NPR|NZD|OMR|PAB|PEN|PGK|PHP|PKR|PLN|PYG|QAR|RON|RSD|RUB|RWF|SAR|SBD|SCR|SDG|SEK|SGD|SHP|SLE|SOS|SRD|SSP|STN|SVC|SYP|SZL|THB|TJS|TMT|TND|TOP|TRY|TTD|TWD|TZS|UAH|UGX|USD|USN|UYI|UYU|UYW|UZS|VED|VES|VND|VUV|WST|XAD|XAF|XAG|XAU|XBA|XBB|XBC|XBD|XCD|XCG|XDR|XOF|XPD|XPF|XPT|XSU|XTS|XUA|XXX|YER|ZAR|ZMW|ZWG)$/;\n// iban electronic format: 2-letter country, check digits 02-98 (the only values `98 - remainder` can produce), 11-30 bban characters\nexport const iban = /^[A-Z]{2}(?!00|01|99)\\d{2}[A-Z0-9]{11,30}$/;\nconst dateSource = `(?:(?:\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\\\d|30)|(?:02)-(?:0[1-9]|1\\\\d|2[0-8])))`;\n/** Anchors a pattern source. The interpolation lives here rather than at the call site because\n * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it\n * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */\nfunction anchor(source) {\n return new RegExp(`^${source}$`);\n}\nexport const date = /*@__PURE__*/ anchor(dateSource);\nfunction timeSource(args) {\n const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n const regex = typeof args.precision === \"number\"\n ? args.precision === -1\n ? `${hhmm}`\n : args.precision === 0\n ? `${hhmm}:[0-5]\\\\d`\n : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n : args.seconds\n ? `${hhmm}:[0-5]\\\\d(?:\\\\.\\\\d+)?`\n : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n return regex;\n}\nexport function time(args) {\n return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n const opts = [\"Z\"];\n // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n if (args.offset)\n opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them\n const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join(\"|\")})`;\n const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\n// the unbounded form of `string()` as a literal, so every plain string shares one instance instead of building its own\nexport const anyString = /^[\\s\\S]{0,}$/;\nexport const string = (params) => {\n const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^-?\\d+n?$/;\nexport const integer = /^-?\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?$/;\nexport const boolean = /^(?:true|false)$/i;\nconst _null = /^null$/i;\nexport { _null as null };\nconst _undefined = /^undefined$/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n","// import { $ZodType } from \"./schemas.js\";\nimport * as core from \"./core.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nexport const $ZodCheck = /*@__PURE__*/ core.$constructor(\"$ZodCheck\", (inst, def) => {\n var _a;\n inst._zod ?? (inst._zod = {});\n inst._zod.def = def;\n (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\n/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */\nconst _whenHasSize = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n};\n/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */\nconst _whenHasLength = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n};\nconst numericOriginMap = {\n number: \"number\",\n bigint: \"bigint\",\n object: \"date\",\n};\nexport const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckLessThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n return;\n }\n payload.issues.push({\n origin: numericOriginMap[typeof payload.value] ?? origin,\n code: \"too_big\",\n maximum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckGreaterThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n return;\n }\n payload.issues.push({\n origin: numericOriginMap[typeof payload.value] ?? origin,\n code: \"too_small\",\n minimum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMultipleOf = \n/*@__PURE__*/ core.$constructor(\"$ZodCheckMultipleOf\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n if (typeof payload.value !== typeof def.value)\n throw new Error(\"Cannot mix number and bigint in multiple_of check.\");\n const isMultiple = typeof payload.value === \"bigint\"\n ? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN\n def.value !== BigInt(0) && payload.value % def.value === BigInt(0)\n : util.floatSafeRemainder(payload.value, def.value) === 0;\n if (isMultiple)\n return;\n payload.issues.push({\n origin: typeof payload.value,\n code: \"not_multiple_of\",\n divisor: def.value,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckNumberFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n def.format = def.format || \"float64\";\n const isInt = def.format?.includes(\"int\");\n const origin = isInt ? \"int\" : \"number\";\n const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (isInt) {\n if (!Number.isInteger(input)) {\n // invalid_format issue\n // payload.issues.push({\n // expected: def.format,\n // format: def.format,\n // code: \"invalid_format\",\n // input,\n // inst,\n // });\n // invalid_type issue\n payload.issues.push({\n expected: origin,\n format: def.format,\n code: \"invalid_type\",\n continue: false,\n input,\n inst,\n });\n return;\n // not_multiple_of issue\n // payload.issues.push({\n // code: \"not_multiple_of\",\n // origin: \"number\",\n // input,\n // inst,\n // divisor: 1,\n // });\n }\n if (!Number.isSafeInteger(input)) {\n if (input > 0) {\n // too_big\n payload.issues.push({\n input,\n code: \"too_big\",\n maximum: Number.MAX_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n else {\n // too_small\n payload.issues.push({\n input,\n code: \"too_small\",\n minimum: Number.MIN_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n return;\n }\n }\n if (input < minimum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_small\",\n minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckBigIntFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (input < minimum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_small\",\n minimum: minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size <= def.maximum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size >= def.minimum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckSizeEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasSize);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size === def.size)\n return;\n const tooBig = size > def.size;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n ...(tooBig ? { code: \"too_big\", maximum: def.size } : { code: \"too_small\", minimum: def.size }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // Strings are measured in Unicode code points, not UTF-16 units. A code point is at most two units, so a string that already fits in units fits in code points; only an overflow has to be counted.\n const length = typeof input === \"string\" && units > def.maximum ? util.codePointLength(input) : units;\n if (length <= def.maximum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // A code point is one or two UTF-16 units, so fewer units than the floor can never reach it and twice the floor always clears it. Only in between is the exact count in doubt.\n const length = typeof input === \"string\" && units >= def.minimum && units < def.minimum * 2\n ? util.codePointLength(input)\n : units;\n if (length >= def.minimum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckLengthEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = _whenHasLength);\n inst._zod.check = (payload) => {\n const input = payload.value;\n const units = input.length;\n // A code point is one or two UTF-16 units, so outside `[length, length * 2]` units the target is missed either way — and missed in the same direction in both measures.\n const length = typeof input === \"string\" && units >= def.length && units <= def.length * 2\n ? util.codePointLength(input)\n : units;\n if (length === def.length)\n return;\n const origin = util.getLengthableOrigin(input);\n const tooBig = length > def.length;\n payload.issues.push({\n origin,\n ...(tooBig ? { code: \"too_big\", maximum: def.length } : { code: \"too_small\", minimum: def.length }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckStringFormat\", (inst, def) => {\n var _a, _b;\n $ZodCheck.init(inst, def);\n if (def.pattern)\n (_a = inst._zod).check ?? (_a.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n ...(def.pattern ? { pattern: def.pattern.toString() } : {}),\n inst,\n continue: !def.abort,\n });\n });\n else\n (_b = inst._zod).check ?? (_b.check = () => { });\n});\nexport const $ZodCheckRegex = /*@__PURE__*/ core.$constructor(\"$ZodCheckRegex\", (inst, def) => {\n $ZodCheckStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"regex\",\n input: payload.value,\n pattern: def.pattern.toString(),\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckLowerCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.lowercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckUpperCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.uppercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor(\"$ZodCheckIncludes\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const escapedRegex = util.escapeRegex(def.includes);\n // `String.prototype.includes(sub, position)` matches `sub` at `position`\n // OR LATER, so the pattern must allow at least `position` leading chars\n // (`{N,}`), not exactly `position` chars (`{N}`).\n const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position},}${escapedRegex}` : escapedRegex);\n def.pattern = pattern;\n inst._zod.check = (payload) => {\n if (payload.value.includes(def.includes, def.position))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"includes\",\n includes: def.includes,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckStartsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.check = (payload) => {\n if (payload.value.startsWith(def.prefix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"starts_with\",\n prefix: def.prefix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckEndsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.check = (payload) => {\n if (payload.value.endsWith(def.suffix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"ends_with\",\n suffix: def.suffix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n///////////////////////////////////\n///// $ZodCheckProperty /////\n///////////////////////////////////\nfunction handleCheckPropertyResult(result, payload, property) {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(property, result.issues));\n }\n}\nexport const $ZodCheckProperty = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperty\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n const result = def.schema._zod.run({\n value: payload.value[def.property],\n issues: [],\n }, {});\n if (result instanceof Promise) {\n return result.then((result) => handleCheckPropertyResult(result, payload, def.property));\n }\n handleCheckPropertyResult(result, payload, def.property);\n return;\n };\n});\nexport const $ZodCheckProperties = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperties\", (inst, def) => {\n $ZodCheck.init(inst, def);\n util.hide(inst, Symbol.iterator, function* () {\n yield inst;\n });\n // key and schema snapshotted together: reading one live and the other cached lets a later mutation of the caller's shape object pair a stale key with a missing schema\n let entries;\n inst._zod.check = (payload) => {\n // the base schema already typed the value, so only a nullish one is rejected here: the properties read on a primitive too, matching z.property() on a string's length\n if (payload.value == null) {\n payload.issues.push({ expected: \"object\", code: \"invalid_type\", input: payload.value, inst });\n return undefined;\n }\n entries ?? (entries = Reflect.ownKeys(def.shape).map((key) => [key, def.shape[key]]));\n const input = payload.value;\n let proms;\n for (const [key, schema] of entries) {\n const result = schema._zod.run({ value: input[key], issues: [] }, {});\n if (result instanceof Promise) {\n proms ?? (proms = []);\n proms.push(result.then((result) => handleCheckPropertyResult(result, payload, key)));\n }\n else {\n handleCheckPropertyResult(result, payload, key);\n }\n }\n if (proms)\n return Promise.all(proms).then(() => undefined);\n return undefined;\n };\n});\nexport const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const mimeSet = new Set(def.mime);\n inst._zod.check = (payload) => {\n if (mimeSet.has(payload.value.type))\n return;\n payload.issues.push({\n code: \"invalid_value\",\n values: def.mime,\n input: payload.value.type,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor(\"$ZodCheckOverwrite\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n payload.value = def.tx(payload.value);\n };\n});\n","export class Doc {\n constructor(args = [], closed = {}) {\n this.content = [];\n this.indent = 0;\n this.args = args;\n this.closed = closed;\n }\n // the compiler catches a child's throw and keeps writing into this doc, so the indent has to unwind with it\n indented(fn) {\n this.indent += 1;\n try {\n fn(this);\n }\n finally {\n this.indent -= 1;\n }\n }\n write(arg) {\n if (typeof arg === \"function\") {\n arg(this, { execution: \"sync\" });\n arg(this, { execution: \"async\" });\n return;\n }\n const content = arg;\n const lines = content.split(\"\\n\").filter((x) => x);\n const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));\n const dedented = lines.map((x) => x.slice(minIndent)).map((x) => \" \".repeat(this.indent * 2) + x);\n for (const line of dedented) {\n this.content.push(line);\n }\n }\n compile() {\n const F = Function;\n const content = this?.content ?? [``];\n const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(\", \")}) {\\n${content.join(\"\\n\")}\\n};`);\n return factory(...Object.values(this.closed));\n }\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\n/* Computing the message eagerly is expensive (pretty-printed JSON of all\n * issues), so defer it until first read. The accessor functions and\n * descriptors are shared across instances to keep error construction\n * cheap; the computed message is cached on the internals object. The\n * setter preserves plain assignment semantics for consumers that\n * overwrite `message`. */\nfunction _getMessage() {\n const internals = this._zod;\n internals.message ?? (internals.message = JSON.stringify(internals.def, util.jsonStringifyReplacer, 2));\n return internals.message;\n}\nfunction _setMessage(value) {\n this._zod.message = value;\n}\nconst _messageDesc = {\n get: _getMessage,\n set: _setMessage,\n enumerable: true,\n configurable: true,\n};\nconst _issuesDesc = { value: undefined, enumerable: false };\n/* Prototypes that already carry the lazy `toString`. Seeded with the\n * intrinsics so that `init` on a foreign object — it accepts any object —\n * can never install an accessor onto a prototype we do not own. */\nconst _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n // `_zod` is already non-enumerable: $constructor's init defined it with this same descriptor\n _issuesDesc.value = def;\n Object.defineProperty(inst, \"issues\", _issuesDesc);\n // Clear the shared slot; a retained `value` pins the last error's issues.\n _issuesDesc.value = undefined;\n Object.defineProperty(inst, \"message\", _messageDesc);\n /* `toString` lives as a non-enumerable lazy getter on the shared\n * prototype; on first access it caches a per-instance closure so\n * detached usage still works. */\n const proto = Object.getPrototypeOf(inst);\n if (!_installedToString.has(proto)) {\n _installedToString.add(proto);\n Object.defineProperty(proto, \"toString\", {\n configurable: true,\n enumerable: false,\n get() {\n const value = () => this.message;\n Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n return value;\n },\n set(value) {\n Object.defineProperty(this, \"toString\", { value, configurable: true, writable: true });\n },\n });\n }\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, undefined, {\n Parent: Error,\n});\n/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member\n * (\"toString\", \"constructor\") would otherwise read through to the prototype, and assigning\n * \"__proto__\" would hit the setter instead of creating a key. */\nfunction node(obj, key, make) {\n if (!Object.prototype.hasOwnProperty.call(obj, key)) {\n if (key === \"__proto__\") {\n Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true });\n }\n else {\n obj[key] = make();\n }\n }\n return obj[key];\n}\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n node(fieldErrors, sub.path[0], () => []).push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error, path = []) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n // `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child.\n if (el === \"_errors\") {\n if (terminal)\n curr._errors.push(mapper(issue));\n i++;\n continue;\n }\n // A path element may collide with an inherited property name such as\n // \"__proto__\" or \"constructor\". Truthiness checks read the prototype\n // (so no node is created, then ._errors.push throws), and bracket\n // assignment of \"__proto__\" hits the setter instead of creating an\n // own key. Guard the read with hasOwnProperty and create the node\n // with defineProperty so any path element becomes a real own key.\n if (!Object.prototype.hasOwnProperty.call(curr, el)) {\n Object.defineProperty(curr, el, {\n value: { _errors: [] },\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n const node = curr[el];\n if (terminal) {\n node._errors.push(mapper(issue));\n }\n curr = node;\n i++;\n }\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n // el may collide with an inherited property name (\"__proto__\",\n // \"constructor\", ...); ??= reads the prototype so the node is never\n // created and curr.errors.push throws. Guard with hasOwnProperty and\n // create the node with defineProperty so \"__proto__\" becomes a real\n // own key rather than invoking the prototype setter.\n if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) {\n Object.defineProperty(curr.properties, el, {\n value: { errors: [] },\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_a = curr.items)[el] ?? (_a[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\n// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two.\nfunction finalizeParams(callee, params) {\n return { callee: params?.callee ?? callee, Err: params?.Err };\n}\nexport const _parse = (_Err) => {\n const fn = (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, _params?.callee ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => {\n const fn = async (schema, value, _ctx, params) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, params?.callee ?? fn);\n throw e;\n }\n return result.value;\n };\n return fn;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\n// the error is built on the first read of `error`: finalizing the issues and constructing the instance is most of a failing parse, and a caller that only branches on `success` never pays it. a getter in the literal keeps this small; the alternative, one shared accessor descriptor plus a hidden state slot, reads ~15% faster but costs ~75 B gzipped in every bundle\nfunction failure(Err, issues, ctx) {\n let error;\n return {\n success: false,\n get error() {\n if (!error) {\n error = new Err(issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n // finalizeIssue drops `input`, so the built error holds nothing; keeping the raw issues past this point pins the parsed value for the life of the result\n issues = undefined;\n ctx = undefined;\n }\n return error;\n },\n set error(e) {\n error = e;\n // a replacement makes the getter's branch unreachable, so the captures have to go here too\n issues = undefined;\n ctx = undefined;\n },\n };\n}\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\n// registry mirrors of the compiler's sentinels, so this module never imports the compiler\nconst COMPILE_INVALID = /* @__PURE__ */ Symbol.for(\"zod.compile.invalid\");\nconst COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for(\"zod.compile.fallback\");\n// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema.\nexport const validate = ((schema, value, _ctx) => {\n const validator = schema._zod.bag.validator;\n if (validator !== undefined) {\n if (validator(value) !== COMPILE_INVALID)\n return true;\n // a definite sentinel means the runtime would reject, so skip the re-parse; a ctx can still change the answer\n if (validator.definite === true && _ctx === undefined)\n return false;\n }\n return validateFallback(schema, value, _ctx);\n});\nfunction validateFallback(schema, value, _ctx) {\n const ctx = _ctx\n ? { ..._ctx, async: false, abortEarly: true }\n : { async: false, abortEarly: true };\n const fallbackRun = schema._zod.bag.fallbackRun;\n let result;\n if (fallbackRun) {\n // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound\n ctx[COMPILE_FALLBACK] = true;\n result = fallbackRun({ value, issues: [] }, ctx);\n }\n else {\n result = schema._zod.run({ value, issues: [] }, ctx);\n }\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length === 0;\n}\n// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw\nexport const validateAsync = async (schema, value, _ctx) => {\n const ctx = _ctx\n ? { ..._ctx, async: true, abortEarly: true }\n : { async: true, abortEarly: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length === 0;\n};\nexport const _encode = (_Err) => {\n const parse = _parse(_Err);\n const fn = (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return parse(schema, value, ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => {\n const parse = _parse(_Err);\n const fn = (schema, value, _ctx, _params) => {\n return parse(schema, value, _ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => {\n const parseAsync = _parseAsync(_Err);\n const fn = async (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params)));\n };\n return fn;\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => {\n const parseAsync = _parseAsync(_Err);\n const fn = async (schema, value, _ctx, _params) => {\n return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params));\n };\n return fn;\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n","export const version = {\n major: 4,\n minor: 6,\n patch: 7,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def; // set _def property\n inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n inst._zod.version = version;\n const defChecks = inst._zod.def.checks;\n // if inst is itself a checks.$ZodCheck, run it as a check\n const checks = inst._zod.traits.has(\"$ZodCheck\")\n ? [inst, ...(defChecks ?? [])]\n : defChecks?.length\n ? [...defChecks]\n : [];\n for (const ch of checks) {\n for (const fn of ch._zod.onattach) {\n fn(inst);\n }\n }\n if (checks.length === 0) {\n // deferred initializer inst._zod.parse is not yet defined\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n }\n else {\n const runChecks = (payload, checks, ctx) => {\n if (payload.memo)\n return payload;\n let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n if (util.explicitlyAborted(payload))\n continue;\n const shouldRun = ch._zod.def.when(payload);\n if (!shouldRun)\n continue;\n }\n else if (isAborted) {\n continue;\n }\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) {\n throw new core.$ZodAsyncError();\n }\n if (asyncResult || _ instanceof Promise) {\n asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n return;\n util.attachSchema(payload.issues, currLen, inst);\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n });\n }\n else {\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n continue;\n util.attachSchema(payload.issues, currLen, inst);\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n }\n }\n if (asyncResult) {\n return asyncResult.then(() => {\n return payload;\n });\n }\n return payload;\n };\n const handleCanaryResult = (canary, payload, ctx) => {\n // abort if the canary is aborted\n if (util.aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n // run checks first, then\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) {\n return inst._zod.parse(payload, ctx);\n }\n if (ctx.direction === \"backward\") {\n // run canary initial pass (no checks)\n const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n if (canary instanceof Promise) {\n return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n }\n return handleCanaryResult(canary, payload, ctx);\n }\n // forward\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n}, {\n // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness.\n get \"~standard\"() {\n return util.hide(this, \"~standard\", standardProps(this));\n },\n set \"~standard\"(value) {\n util.own(this, \"~standard\", value);\n },\n});\n/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */\n// a Standard Schema result only reports issues, so a failure finalizes them straight off the raw payload: no ZodError, and no lazy result to read through\nconst toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())) } : { value: r.value };\nasync function validateAsync(inst, value) {\n const ctx = { async: true };\n return toStandardResult((await inst._zod.run({ value, issues: [] }, ctx)), ctx);\n}\nexport function standardProps(inst) {\n return {\n validate: (value) => {\n const ctx = { async: false };\n try {\n const r = inst._zod.run({ value, issues: [] }, ctx);\n if (!(r instanceof Promise))\n return toStandardResult(r, ctx);\n }\n catch (_) { }\n // async function so a synchronously throwing check rejects instead of escaping validate\n return validateAsync(inst, value);\n },\n vendor: \"zod\",\n version: 1,\n };\n}\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n // a format's own pattern, else unbounded; a template literal derives the check-aware form itself\n inst._zod.pattern = def.pattern ?? regexes.anyString;\n inst._zod.parse = (payload, _) => {\n if (def.coerce)\n try {\n payload.value = String(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"string\")\n return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n // check initialization must come first\n checks.$ZodCheckStringFormat.init(inst, def);\n $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.guid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n if (def.version) {\n const versionMap = {\n v1: 1,\n v2: 2,\n v3: 3,\n v4: 4,\n v5: 5,\n v6: 6,\n v7: 7,\n v8: 8,\n };\n const v = versionMap[def.version];\n if (v === undefined)\n throw new Error(`Invalid UUID version: \"${def.version}\"`);\n def.pattern ?? (def.pattern = regexes.uuid(v));\n }\n else\n def.pattern ?? (def.pattern = regexes.uuid());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.email);\n $ZodStringFormat.init(inst, def);\n});\n/** The `://` guard rejected the input before the URL constructor saw it. */\nexport const URL_BAD_FORMAT = 1;\n/** The URL parser rejected the input. */\nexport const URL_UNPARSEABLE = 2;\nexport function canParseURL(input) {\n try {\n if (typeof URL !== \"undefined\" && typeof URL.canParse === \"function\")\n return URL.canParse(input);\n new URL(input);\n return true;\n }\n catch {\n return false;\n }\n}\nexport function validateURL(trimmed, def) {\n if (!(\"normalize\" in def) && !(\"hostname\" in def) && !(\"protocol\" in def)) {\n return canParseURL(trimmed) || URL_UNPARSEABLE;\n }\n return parseURLObject(trimmed, def);\n}\n/** Parses a URL while preserving the non-normalizing HTTP guard. */\nexport function parseURLObject(trimmed, def) {\n // When normalize is off, require :// for http/https URLs. This prevents strings like \"http:example.com\" or \"https:/path\" from being silently accepted\n if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source && !/^https?:\\/\\//i.test(trimmed)) {\n return URL_BAD_FORMAT;\n }\n try {\n if (typeof URL !== \"undefined\") {\n const URLStatic = URL;\n if (typeof URLStatic.parse === \"function\")\n return URLStatic.parse(trimmed) ?? URL_UNPARSEABLE;\n }\n // @ts-ignore\n return new URL(trimmed);\n }\n catch {\n return URL_UNPARSEABLE;\n }\n}\nconst asciiTabOrNewline = /[\\t\\n\\r]/g;\n/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL(\"https://exa\\nmple.com\")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */\nexport function stripTabAndNewline(value) {\n return value.replace(asciiTabOrNewline, \"\");\n}\nexport function urlHostnameOk(url, hostname) {\n hostname.lastIndex = 0;\n return hostname.test(url.hostname);\n}\nexport function urlProtocolOk(url, protocol) {\n protocol.lastIndex = 0;\n return protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol);\n}\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n try {\n // Trim whitespace from input\n const trimmed = payload.value.trim();\n const url = validateURL(trimmed, def);\n if (url === URL_BAD_FORMAT) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid URL format\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n if (url === URL_UNPARSEABLE) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n if (url === true) {\n payload.value = stripTabAndNewline(trimmed);\n return;\n }\n if (def.hostname && !urlHostnameOk(url, def.hostname)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid hostname\",\n pattern: def.hostname.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n if (def.protocol && !urlProtocolOk(url, def.protocol)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid protocol\",\n pattern: def.protocol.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n // Set the output value based on normalize flag\n payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed);\n return;\n }\n catch (_) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.emoji());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1))\n throw new Error(`Invalid nanoid length: ${def.length}`);\n def.pattern ?? (def.pattern = def.length === undefined ? regexes.nanoid : regexes.nanoidOfLength(def.length));\n $ZodStringFormat.init(inst, def);\n});\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid2);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ulid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.xid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ksuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.datetime(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.date);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.time(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.duration);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv4);\n $ZodStringFormat.init(inst, def);\n});\n/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL(\"http://[...]\")` parses an authority, not an address, so `@` and `\\` re-delimit it and `\"::@1\\\\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `\"::1\\n\"` validated as `::1`. */\nconst ipv6Alphabet = /^[0-9a-fA-F:.]+$/;\nexport function isValidIPv6(value) {\n if (!ipv6Alphabet.test(value))\n return false;\n return canParseURL(`http://[${value}]`);\n}\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv6);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (!isValidIPv6(payload.value)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"ipv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport function isValidCIDRv6(value) {\n const parts = value.split(\"/\");\n if (parts.length !== 2)\n return false;\n const [address, prefix] = parts;\n if (!prefix)\n return false;\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n return false;\n if (prefixNum < 0 || prefixNum > 128)\n return false;\n return isValidIPv6(address);\n}\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (!isValidCIDRv6(payload.value)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"cidrv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64(data) {\n if (data === \"\")\n return true;\n // atob ignores whitespace, so reject it up front.\n if (/\\s/.test(data))\n return false;\n if (data.length % 4 !== 0)\n return false;\n try {\n // @ts-ignore\n atob(data);\n return true;\n }\n catch {\n return false;\n }\n}\n// lax on purpose: the quantified regexes.base64 overflows the regex stack on multi-MB input and its leading ^$| alternation leaks through template-literal composition; isValidBase64 enforces length and padding\nexport const base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/;\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = base64Charset);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidBase64(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodBase64URL //////////////////////////////\n// lax on purpose: the quantified regexes.base64url overflows the regex stack on multi-MB input; isValidBase64 enforces length on the padded string\nexport const base64urlCharset = /^[A-Za-z0-9_-]*$/;\nexport function isValidBase64URL(data) {\n if (!base64urlCharset.test(data))\n return false;\n const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n def.pattern ?? (def.pattern = base64urlCharset);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidBase64URL(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.e164);\n $ZodStringFormat.init(inst, def);\n});\n////////////////////////////// ZodCreditCard //////////////////////////////\nconst CC_SANITIZE = /[- ]/g;\n/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */\nfunction isLuhnAlgo(digits) {\n let length = digits.length;\n let bit = 1;\n let sum = 0;\n while (length) {\n const value = digits.charCodeAt(--length) - 48;\n bit ^= 1;\n sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value;\n }\n return sum % 10 === 0;\n}\nexport function isValidCreditCard(input) {\n if (!regexes.creditCard.test(input))\n return false;\n return isLuhnAlgo(input.replace(CC_SANITIZE, \"\"));\n}\nexport const $ZodCreditCard = /*@__PURE__*/ core.$constructor(\"$ZodCreditCard\", (inst, def) => {\n // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone.\n def.pattern ?? (def.pattern = regexes.creditCard);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidCreditCard(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"credit_card\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodIBAN //////////////////////////////\n// iso 7064 mod 97-10 checksum without BigInt\nfunction isIso7064Mod97(iban) {\n let remainder = 0;\n const len = iban.length;\n for (let i = 4; i < len; i++) {\n const code = iban.charCodeAt(i);\n remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;\n }\n for (let i = 0; i < 4; i++) {\n const code = iban.charCodeAt(i);\n remainder = (code >= 65 ? remainder * 100 + (code - 55) : remainder * 10 + (code - 48)) % 97;\n }\n return remainder === 1;\n}\nexport function isValidIBAN(input) {\n if (!regexes.iban.test(input))\n return false;\n return isIso7064Mod97(input);\n}\nexport const $ZodIBAN = /*@__PURE__*/ core.$constructor(\"$ZodIBAN\", (inst, def) => {\n // shape only — checksum is not expressible as a pattern\n def.pattern ?? (def.pattern = regexes.iban);\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidIBAN(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"iban\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodJWT //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n try {\n const tokensParts = token.split(\".\");\n if (tokensParts.length !== 3)\n return false;\n const [header] = tokensParts;\n if (!header)\n return false;\n // @ts-ignore\n const parsedHeader = JSON.parse(atob(header));\n if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n return false;\n if (!parsedHeader.alg)\n return false;\n if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidJWT(payload.value, def.alg))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"jwt\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (def.fn(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.number;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Number(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n return payload;\n }\n const received = typeof input === \"number\"\n ? Number.isNaN(input)\n ? \"NaN\"\n : !Number.isFinite(input)\n ? String(input)\n : undefined\n : undefined;\n payload.issues.push({\n expected: \"number\",\n code: \"invalid_type\",\n input,\n inst,\n ...(received ? { received } : {}),\n });\n return payload;\n };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n checks.$ZodCheckNumberFormat.init(inst, def);\n $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.boolean;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Boolean(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"boolean\")\n return payload;\n payload.issues.push({\n expected: \"boolean\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.bigint;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = BigInt(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"bigint\")\n return payload;\n payload.issues.push({\n expected: \"bigint\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n checks.$ZodCheckBigIntFormat.init(inst, def);\n $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"symbol\")\n return payload;\n payload.issues.push({\n expected: \"symbol\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.undefined;\n inst._zod.values = new Set([undefined]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"undefined\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.null;\n inst._zod.values = new Set([null]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input === null)\n return payload;\n payload.issues.push({\n expected: \"null\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.issues.push({\n expected: \"never\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"void\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce) {\n try {\n payload.value = new Date(payload.value);\n }\n catch (_err) { }\n }\n const input = payload.value;\n const isDate = input instanceof Date;\n const isValidDate = isDate && !Number.isNaN(input.getTime());\n if (isValidDate)\n return payload;\n payload.issues.push({\n expected: \"date\",\n code: \"invalid_type\",\n input,\n ...(isDate ? { received: \"Invalid Date\" } : {}),\n inst,\n });\n return payload;\n };\n});\n// an oversized container fails its leading size checks before any element is parsed\nfunction capSize(inst, size) {\n const caps = util.sizeCaps(inst._zod.def.checks);\n if (!caps.length)\n return;\n const cap = Math.min(...caps.map((c) => c[0]));\n const parse = inst._zod.parse;\n inst._zod.parse = (payload, ctx) => {\n const n = size(payload.value);\n if (n > cap && !ctx?.skipChecks && ctx?.direction !== \"backward\") {\n for (const [max, ch] of util.sizeCaps(inst._zod.def.checks)) {\n if (n > max && ch._zod.def.when(payload)) {\n const start = payload.issues.length;\n ch._zod.check(payload);\n // the value is still the raw input, so no later check may read it\n payload.issues[start].continue = false;\n util.attachSchema(payload.issues, start, inst);\n return payload;\n }\n }\n }\n return parse(payload, ctx);\n };\n}\nconst arraySize = (input) => (Array.isArray(input) ? input.length : -1);\nconst mapSize = (input) => (input instanceof Map ? input.size : -1);\nconst setSize = (input) => (input instanceof Set ? input.size : -1);\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length);\n const proms = [];\n const abortEarly = ctx?.abortEarly;\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n }\n else {\n handleArrayResult(result, payload, i);\n // the element's payload is authoritative here, since handleArrayResult forwards every issue; an object's is not, because it drops a failed absent optional\n if (abortEarly && result.issues.length !== 0 && util.aborted(result))\n break;\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n capSize(inst, arraySize);\n});\nfunction handlePropertyResult(result, final, key, input, optin, optout) {\n const isPresent = key in input;\n const isOptionalOut = optout === \"optional\";\n // The middle rung means \"absence permitted, nothing supplied in its place\", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key.\n if (!isPresent && isOptionalOut && optin === \"optional\") {\n return;\n }\n if (result.issues.length) {\n // For optional-in/out schemas, ignore errors on absent keys.\n if (optin !== undefined && isOptionalOut && !isPresent) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (!isPresent && optin === undefined) {\n if (!result.issues.length) {\n final.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [key],\n });\n }\n return;\n }\n if (result.value === undefined) {\n if (isPresent || (optin === \"defaulted\" && !isOptionalOut)) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\n// one shared instance; a fresh [] per schema cost 56 bytes retained\nconst NO_SYMBOL_KEYS = [];\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n const ownSymbols = Object.getOwnPropertySymbols(def.shape);\n const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS;\n // aliases `keys` when there are no symbols, so a string-only shape keeps one array\n const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys;\n for (const k of allKeys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${String(k)}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n allKeys,\n symbolKeys,\n // string-only: handleCatchall matches it against `for...in`, which never yields a symbol\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst, abortEarly) {\n const unrecognized = [];\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const optin = _catchall.optin;\n const optout = _catchall.optout;\n // starts at 0, not the current length: the shape phase already ran and may have aborted\n let seen = 0;\n for (const key in input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output.\n if (keySet.has(key))\n continue;\n // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping.\n if (key === \"__proto__\") {\n if (t === \"never\")\n unrecognized.push(key);\n continue;\n }\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n }\n else {\n handlePropertyResult(r, payload, key, input, optin, optout);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand.\n continue: true,\n });\n }\n if (!proms.length)\n return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodType.init(inst, def);\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n // a cloned def carries its source's accessor, which knows the shape it answers from; adopting that keeps the clone's keys readable without running it\n const sh = desc?.get ? desc.get.raw : (def.shape ?? {});\n if (sh) {\n // Freezes the shape on first read, so its getters resolve once and every later read sees the same schemas.\n const get = () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", { value: newSh });\n get.raw = newSh;\n return newSh;\n };\n get.raw = sh;\n Object.defineProperty(def, \"shape\", { get });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazyInternal(inst, \"propValues\", (zod) => {\n const shape = zod.def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n if (!Object.prototype.hasOwnProperty.call(propValues, key)) {\n util.assignProp(propValues, key, new Set());\n }\n for (const v of field.values)\n propValues[key].add(v);\n // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it.\n if (field.optin !== undefined)\n propValues[key].add(undefined);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const proms = [];\n const shape = value.shape;\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const key of value.allKeys) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n if (key === \"__proto__\")\n continue;\n const el = shape[key];\n const optin = el._zod.optin;\n const optout = el._zod.optout;\n const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));\n }\n else {\n handlePropertyResult(r, payload, key, input, optin, optout);\n }\n }\n if (!catchall) {\n return proms.length ? Promise.all(proms).then(() => payload) : payload;\n }\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst, abortEarly === true);\n };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodObject.init(inst, def);\n const superParse = inst._zod.parse;\n const _normalized = util.cached(() => normalizeDef(def));\n const memo = core.globalConfig.memoizer;\n const generateFastpass = (shape) => {\n const normalized = _normalized.value;\n const syms = normalized.symbolKeys;\n // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope\n const doc = new Doc([\"payload\", \"ctx\"], { shape, inst, memo, syms });\n const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n // prefixes in place, like util.prefixIssues. newResult must land before the early return: a catchall runs after this and would otherwise write onto the caller's input\n const prefixStr = (id, k) => `\n let ${id}_ab = false;\n for (let i = 0; i < ${id}.issues.length; i++) {\n const iss = ${id}.issues[i];\n iss.path = iss.path ? [${k}, ...iss.path] : [${k}];\n payload.issues.push(iss);\n if (iss.continue !== true) ${id}_ab = true;\n }\n if (${id}_ab && ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }`;\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.allKeys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`);\n for (const key of normalized.allKeys) {\n if (key === \"__proto__\")\n continue;\n const id = ids[key];\n const k = typeof key === \"symbol\" ? `syms[${syms.indexOf(key)}]` : util.esc(key);\n const isPresent = `${k} in input`;\n const schema = shape[key];\n const optin = schema?._zod?.optin;\n const isOptionalIn = optin !== undefined;\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(k)};`);\n if (isOptionalIn && isOptionalOut) {\n // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all.\n const assign = optin === \"optional\" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`;\n doc.write(`\n const ${id}_present = ${isPresent};\n if (!${id}.issues.length || ${id}_present) {\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n\n if (${assign}) {\n newResult[${k}] = ${id}.value;\n }\n }\n\n `);\n }\n else if (!isOptionalIn) {\n doc.write(`\n const ${id}_present = ${isPresent};\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n if (!${id}_present && !${id}.issues.length) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [${k}]\n });\n if (ctx && ctx.abortEarly) {\n payload.value = newResult;\n return payload;\n }\n }\n\n if (${id}_present) {\n newResult[${k}] = ${id}.value;\n }\n\n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {${prefixStr(id, k)}\n }\n `);\n if (optin === \"defaulted\") {\n doc.write(`newResult[${k}] = ${id}.value;`);\n }\n else {\n doc.write(`\n if (${id}.value !== undefined || ${isPresent}) {\n newResult[${k}] = ${id}.value;\n }\n `);\n }\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone\n return doc.compile();\n };\n let fastpass;\n const isObject = util.isObject;\n const jit = !core.globalConfig.jitless;\n const allowsEval = util.allowsEval;\n const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n // always synchronous\n if (!fastpass)\n fastpass = generateFastpass(def.shape);\n payload = fastpass(payload, ctx);\n if (!catchall)\n return payload;\n return handleCatchall([], input, payload, ctx, value, inst, ctx?.abortEarly === true);\n }\n return superParse(payload, ctx);\n };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n for (const result of results) {\n if (result.issues.length === 0) {\n final.value = result.value;\n return final;\n }\n }\n const nonaborted = results.filter((r) => !util.aborted(r));\n if (nonaborted.length === 1) {\n final.value = nonaborted[0].value;\n return nonaborted[0];\n }\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.options.some((o) => o._zod.optin === \"defaulted\")\n ? \"defaulted\"\n : zod.def.options.some((o) => o._zod.optin !== undefined)\n ? \"optional\"\n : undefined);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazyInternal(inst, \"values\", (zod) => {\n if (zod.def.options.every((o) => o._zod.values)) {\n return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n if (zod.def.options.every((o) => o._zod.pattern)) {\n const patterns = zod.def.options.map((o) => o._zod.pattern);\n return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n }\n return undefined;\n });\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n if (result.issues.length === 0)\n return result;\n results.push(result);\n }\n }\n if (!async)\n return handleUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleUnionResults(results, payload, inst, ctx);\n });\n };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n const matches = [];\n for (let i = 0; i < results.length; i++) {\n if (results[i].issues.length === 0)\n matches.push(i);\n }\n if (matches.length === 1) {\n final.value = results[matches[0]].value;\n return final;\n }\n if (matches.length === 0) {\n // No matches - same as regular union\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n }\n else {\n // Multiple matches - exclusive union failure\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: [],\n inclusive: false,\n matches,\n });\n }\n return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n $ZodUnion.init(inst, def);\n def.inclusive = false;\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n results.push(result);\n }\n }\n if (!async)\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n });\n };\n});\n/** Returns the option whose discriminator claims `value`, or throws if ambiguous. */\nexport function getDiscriminatedOption(union, value) {\n const internals = union._zod;\n let map = internals.bag.optionsMap;\n if (!map) {\n map = discriminatorMap(internals.def);\n internals.bag.optionsMap = map;\n }\n const option = map.get(value);\n if (option === null)\n throw new Error(`Ambiguous discriminator value \"${String(value)}\"`);\n return option;\n}\nfunction discriminatorMap(def) {\n const map = new Map();\n for (const option of def.options) {\n const values = option._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const value of values) {\n if (map.has(value)) {\n if (value !== undefined)\n throw new Error(`Duplicate discriminator value \"${String(value)}\"`);\n // keep the collision marked so a later member cannot reclaim it\n map.set(value, null);\n }\n else {\n map.set(value, option);\n }\n }\n }\n return map;\n}\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n def.inclusive = false;\n $ZodUnion.init(inst, def);\n const _super = inst._zod.parse;\n util.defineLazyInternal(inst, \"propValues\", (zod) => {\n const propValues = {};\n let undefinedCount = 0;\n for (const option of zod.def.options) {\n const pv = option._zod.propValues;\n if (!pv || Object.keys(pv).length === 0)\n throw new Error(`Invalid discriminated union option at index \"${zod.def.options.indexOf(option)}\"`);\n if (pv[zod.def.discriminator]?.has(undefined))\n undefinedCount++;\n for (const [k, v] of Object.entries(pv)) {\n if (!Object.prototype.hasOwnProperty.call(propValues, k)) {\n util.assignProp(propValues, k, new Set());\n }\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n if (!zod.def.unionFallback && undefinedCount > 1)\n propValues[zod.def.discriminator]?.delete(undefined);\n return propValues;\n });\n // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes and lazies — are left to the map.\n def.options.forEach((option, i) => {\n const propShape = util.rawShape(option._zod.def);\n if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) {\n throw new Error(`Invalid discriminated union option at index \"${i}\"`);\n }\n });\n const disc = util.cached(() => discriminatorMap(def));\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isObject(input)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"object\",\n input,\n inst,\n });\n return payload;\n }\n const value = input?.[def.discriminator];\n const opt = disc.value.get(value);\n // forward metadata cannot choose an encoder for an absent tag\n if (opt && (value !== undefined || ctx.direction !== \"backward\")) {\n return opt._zod.run(payload, ctx);\n }\n // Fall back to union matching when the fast discriminator path fails:\n // - explicitly enabled via unionFallback, or\n // - during backward direction (encode), since codec-based discriminators have different values in forward vs backward directions\n if (def.unionFallback || ctx.direction === \"backward\") {\n return _super(payload, ctx);\n }\n // no matching discriminator\n payload.issues.push({\n code: \"invalid_union\",\n errors: [],\n note: \"No matching discriminator\",\n discriminator: def.discriminator,\n options: Array.from(disc.value.keys()).filter((value) => disc.value.get(value) !== null),\n input,\n path: [def.discriminator],\n inst,\n });\n return payload;\n };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n const async = left instanceof Promise || right instanceof Promise;\n if (async) {\n return Promise.all([left, right]).then(([left, right]) => {\n return handleIntersectionResults(payload, left, right);\n });\n }\n return handleIntersectionResults(payload, left, right);\n };\n});\nexport function mergeValues(a, b) {\n // const aType = parse.t(a);\n // const bType = parse.t(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n if (a instanceof Date && b instanceof Date && +a === +b) {\n return { valid: true, data: a };\n }\n if (util.isPlainObject(a) && util.isPlainObject(b)) {\n const bKeys = Object.keys(b);\n const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n if (Object.prototype.hasOwnProperty.call(newObj, \"__proto__\"))\n delete newObj.__proto__;\n for (const key of sharedKeys) {\n if (key === \"__proto__\")\n continue;\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return { valid: false, mergeErrorPath: [] };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n // Track which side(s) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key.\n const unrecKeys = new Map();\n let unrecIssue;\n const keyIssues = new Map();\n const collect = (iss, side) => {\n let keys;\n if (iss.code === \"unrecognized_keys\" && !iss.path?.length) {\n unrecIssue ?? (unrecIssue = iss);\n keys = iss.keys;\n }\n else if (iss.code === \"invalid_key\" && iss.origin === \"record\" && iss.path?.length === 1) {\n const k = String(iss.path[0]);\n if (!keyIssues.has(k))\n keyIssues.set(k, iss);\n keys = [k];\n }\n else {\n return false;\n }\n for (const k of keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k)[side] = true;\n }\n return true;\n };\n for (const iss of left.issues) {\n if (!collect(iss, \"l\"))\n result.issues.push(iss);\n }\n for (const iss of right.issues) {\n if (!collect(iss, \"r\"))\n result.issues.push(iss);\n }\n // Report only keys rejected by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length) {\n const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : [];\n if (aggregated.length)\n result.issues.push({ ...unrecIssue, keys: aggregated });\n for (const k of bothKeys) {\n if (!aggregated.includes(k) && keyIssues.has(k))\n result.issues.push(keyIssues.get(k));\n }\n }\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n if (util.aborted(result))\n return result;\n throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n }\n result.value = merged.data;\n return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n $ZodType.init(inst, def);\n const items = def.items;\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n input,\n inst,\n expected: \"tuple\",\n code: \"invalid_type\",\n });\n return payload;\n }\n payload.value = memo ? memo.alloc(inst, payload, [], ctx) : [];\n const proms = [];\n const optinStart = getTupleOptStart(items, \"optin\");\n const optoutStart = getTupleOptStart(items, \"optout\");\n if (!def.rest) {\n if (input.length < optinStart) {\n payload.issues.push({\n code: \"too_small\",\n minimum: optinStart,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n if (input.length > items.length) {\n payload.issues.push({\n code: \"too_big\",\n maximum: items.length,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n }\n }\n // Run every item in parallel, collecting results into an indexed array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output.\n const itemResults = new Array(items.length);\n // only tracked when there is a rest loop to skip\n const abortEarly = def.rest ? ctx?.abortEarly : undefined;\n let itemAborted = false;\n for (let i = 0; i < items.length; i++) {\n const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((rr) => {\n itemResults[i] = rr;\n }));\n }\n else {\n itemResults[i] = r;\n if (abortEarly && !itemAborted && r.issues.length)\n itemAborted = util.aborted(r);\n }\n }\n // sound because rest is non-empty exactly when every fixed index is present, the one case handleTupleResults cannot discard an item's issues\n if (def.rest && !itemAborted) {\n let i = items.length - 1;\n const rest = input.slice(items.length);\n let seen = payload.issues.length;\n for (const el of rest) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n i++;\n const result = def.rest._zod.run({ value: el, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((r) => handleTupleResult(r, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));\n }\n return handleTupleResults(itemResults, payload, items, input, optoutStart);\n };\n});\nfunction getTupleOptStart(items, key) {\n for (let i = items.length - 1; i >= 0; i--) {\n // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued.\n const omittable = key === \"optin\" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === \"optional\";\n if (!omittable)\n return i + 1;\n }\n return 0;\n}\nfunction handleTupleResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nfunction handleTupleResults(itemResults, final, items, input, optoutStart) {\n // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional rule, but only after `optoutStart`: the first index where the output tuple tail can be absent.\n for (let i = 0; i < items.length; i++) {\n const r = itemResults[i];\n const isPresent = i < input.length;\n // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`.\n if (!isPresent && i >= optoutStart && items[i]._zod.optin === \"optional\") {\n final.value.length = i;\n break;\n }\n if (r.issues.length) {\n if (!isPresent && i >= optoutStart) {\n final.value.length = i;\n break;\n }\n final.issues.push(...util.prefixIssues(i, r.issues));\n }\n final.value[i] = r.value;\n }\n // Drop trailing slots that produced `undefined` for absent input\n // (the array analog of an absent optional key on an object). The\n // `i >= input.length` floor is critical: an explicit `undefined`\n // *inside* the input must be preserved even when the schema is\n // optional-out (e.g. `z.string().or(z.undefined())` accepting an\n // explicit undefined value).\n for (let i = final.value.length - 1; i >= input.length; i--) {\n if (items[i]._zod.optout === \"optional\" && final.value[i] === undefined) {\n final.value.length = i;\n }\n else {\n break;\n }\n }\n return final;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n // no guard in either loop below: a record's invalid_key aborts but an enclosing intersection can reconcile it, so a stopped loop hides keys the sibling does not own and the intersection then rejects nothing\n const proms = [];\n const values = def.keyType._zod.values;\n if (values && !def.partial) {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n const recordKeys = new Set();\n for (const key of values) {\n if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n // A declared __proto__ is stripped but is not an unrecognized key.\n if (key === \"__proto__\")\n continue;\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (keyResult.issues.length) {\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n continue;\n }\n const outKey = keyResult.value;\n if (outKey === \"__proto__\")\n continue;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!recordKeys.has(key)) {\n if (def.mode === \"loose\") {\n // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into\n if (key === \"__proto__\")\n continue;\n payload.value[key] = input[key];\n }\n else {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true,\n });\n }\n }\n else {\n payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};\n // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection.\n let unrecognized;\n // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\n continue;\n if (!Object.prototype.propertyIsEnumerable.call(input, key))\n continue;\n let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n // Numeric string fallback: if key is a numeric string and failed, retry with Number(key). This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals\n const checkNumericKey = typeof key === \"string\" && regexes.number.test(key) && keyResult.issues.length;\n if (checkNumericKey) {\n const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n if (retryResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (retryResult.issues.length === 0) {\n keyResult = retryResult;\n }\n }\n if (keyResult.issues.length) {\n if (def.mode === \"loose\") {\n // Pass through unchanged\n payload.value[key] = input[key];\n }\n else if (values) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n else {\n // Default \"strict\" behavior: error on invalid key\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n }\n continue;\n }\n // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under\n const outKey = keyResult.value;\n if (outKey === \"__proto__\")\n continue;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n continue: true,\n });\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload;\n };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Map)) {\n payload.issues.push({\n expected: \"map\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n payload.value = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map();\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const [key, value] of input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n if (keyResult instanceof Promise || valueResult instanceof Promise) {\n proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }));\n }\n else {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n capSize(inst, mapSize);\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n if (keyResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, keyResult.issues));\n }\n else {\n final.issues.push({\n code: \"invalid_key\",\n origin: \"map\",\n input,\n inst,\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n if (valueResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, valueResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_element\",\n input,\n inst,\n key: key,\n issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n $ZodType.init(inst, def);\n const memo = core.globalConfig.memoizer;\n memo?.attach(inst);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Set)) {\n payload.issues.push({\n input,\n inst,\n expected: \"set\",\n code: \"invalid_type\",\n });\n return payload;\n }\n const proms = [];\n payload.value = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set();\n const abortEarly = ctx?.abortEarly;\n let seen = payload.issues.length;\n for (const item of input) {\n if (abortEarly && payload.issues.length !== seen) {\n if (util.aborted(payload, seen))\n break;\n seen = payload.issues.length;\n }\n const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleSetResult(result, payload)));\n }\n else\n handleSetResult(result, payload);\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n capSize(inst, setSize);\n});\nfunction handleSetResult(result, final) {\n if (result.issues.length) {\n final.issues.push(...result.issues);\n }\n final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = util.getEnumValues(def.entries);\n const valuesSet = new Set(values);\n inst._zod.values = valuesSet;\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const patternValues = util.getEnumValues(zod.def.entries).filter((k) => util.propertyKeyTypes.has(typeof k));\n // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n return new RegExp(patternValues.length ? `^(${patternValues.map((o) => util.escapeRegex(o.toString())).join(\"|\")})$` : \"^[^\\\\s\\\\S]$\");\n });\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (valuesSet.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = new Set(def.values);\n inst._zod.values = values;\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const vals = zod.def.values;\n // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches \"\"\n return new RegExp(vals.length\n ? `^(${vals\n .map((o) => typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o))\n .join(\"|\")})$`\n : \"^[^\\\\s\\\\S]$\");\n });\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values: def.values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n // @ts-ignore\n if (input instanceof File)\n return payload;\n payload.issues.push({\n expected: \"file\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n core.globalConfig.memoizer?.guard(inst);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n const _out = def.transform(payload.value, payload);\n if (ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n return payload;\n };\n});\nfunction handleOptionalResult(payload, result) {\n // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it.\n payload.value = result.issues.length ? undefined : result.value;\n return payload;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung.\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n inst._zod.optout = \"optional\";\n util.defineLazyInternal(inst, \"values\", (zod) => {\n const values = zod.def.innerType._zod.values;\n return values ? new Set([...values, undefined]) : undefined;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (payload.value === undefined) {\n // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means.\n if (def.innerType._zod.optin !== \"defaulted\")\n return payload;\n // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it.\n const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n if (result instanceof Promise)\n return result.then((result) => handleOptionalResult(payload, result));\n return handleOptionalResult(payload, result);\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n // Call parent init - inherits optin/optout = \"optional\"\n $ZodOptional.init(inst, def);\n // Override values/pattern to NOT add undefined\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n util.defineLazyInternal(inst, \"pattern\", (zod) => zod.def.innerType._zod.pattern);\n // Override parse to just delegate (no undefined handling)\n inst._zod.parse = (payload, ctx) => {\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n util.defineLazyInternal(inst, \"pattern\", (zod) => {\n const pattern = zod.def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazyInternal(inst, \"values\", (zod) => {\n return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n // Forward direction (decode): allow null to pass through\n if (payload.value === null)\n return payload;\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n // inst._zod.qin = \"true\";\n inst._zod.optin = \"defaulted\";\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply defaults for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n /**\n * $ZodDefault returns the default value immediately in forward direction.\n * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe. */\n return payload;\n }\n // Forward direction: continue with default handling\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleDefaultResult(result, def));\n }\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"defaulted\";\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply prefault for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => {\n const v = zod.def.innerType._zod.values;\n return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleNonOptionalResult(result, inst));\n }\n return handleNonOptionalResult(result, inst);\n };\n});\nfunction handleNonOptionalResult(payload, inst) {\n if (!payload.issues.length && payload.value === undefined) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: payload.value,\n inst,\n });\n }\n return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(\"ZodSuccess\");\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.issues.length === 0;\n return payload;\n });\n }\n payload.value = result.issues.length === 0;\n return payload;\n };\n});\nfunction handleCatchResult(payload, result, def, ctx) {\n if (!result.issues.length) {\n payload.value = result.value;\n // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property.\n if (result.memo)\n payload.memo = true;\n return payload;\n }\n // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call.\n payload.value = def.catchValue({\n ...result,\n value: payload.value,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n return payload;\n}\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType._zod.optin === \"defaulted\" ? \"defaulted\" : \"optional\");\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType._zod.optout);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply catch logic\n const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleCatchResult(payload, result, def, ctx));\n }\n return handleCatchResult(payload, result, def, ctx);\n };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"nan\",\n code: \"invalid_type\",\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handlePipeResult(right, def.in, ctx));\n }\n return handlePipeResult(right, def.in, ctx);\n }\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handlePipeResult(left, def.out, ctx));\n }\n return handlePipeResult(left, def.out, ctx);\n };\n});\nfunction handlePipeResult(left, next, ctx) {\n // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it.\n if (left.issues.some((iss) => iss.code !== \"unrecognized_keys\")) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.in._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.in._zod.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.out._zod.optout);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handleCodecAResult(left, def, ctx));\n }\n return handleCodecAResult(left, def, ctx);\n }\n else {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handleCodecAResult(right, def, ctx));\n }\n return handleCodecAResult(right, def, ctx);\n }\n };\n});\nfunction handleCodecAResult(result, def, ctx) {\n if (result.issues.length) {\n // prevent further checks\n result.aborted = true;\n return result;\n }\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const transformed = def.transform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n }\n return handleCodecTxResult(result, transformed, def.out, ctx);\n }\n else {\n const transformed = def.reverseTransform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n }\n return handleCodecTxResult(result, transformed, def.in, ctx);\n }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n // Check if transform added any issues\n if (left.issues.length) {\n left.aborted = true;\n return left;\n }\n return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodPreprocess = /*@__PURE__*/ core.$constructor(\"$ZodPreprocess\", (inst, def) => {\n $ZodPipe.init(inst, def);\n});\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.def.innerType._zod.propValues);\n util.defineLazyInternal(inst, \"values\", (zod) => zod.def.innerType._zod.values);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.def.innerType?._zod?.optin);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.def.innerType?._zod?.optout);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then(handleReadonlyResult);\n }\n return handleReadonlyResult(result);\n };\n});\nfunction handleReadonlyResult(payload) {\n // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign.\n if (!payload.memo)\n payload.value = Object.freeze(payload.value);\n return payload;\n}\n// a leaf's pattern source with its own checks folded in: the last pattern-carrying check wins, else length bounds narrow the catch-all, else an integer format narrows the number form. the fold lives here instead of on `_zod.pattern` so a bundle without template literals never pays for it\nfunction leafPattern(schema) {\n const def = schema._zod.def;\n let pattern = def.pattern;\n let isInt = !!def.format?.includes(\"int\");\n let minimum;\n let maximum;\n for (const ch of def.checks ?? []) {\n const d = ch._zod.def;\n if (d.pattern)\n pattern = d.pattern;\n isInt || (isInt = !!d.format?.includes(\"int\"));\n const lo = d.minimum ?? d.length;\n const hi = d.maximum ?? d.length;\n if (lo !== undefined && (minimum === undefined || lo > minimum))\n minimum = lo;\n if (hi !== undefined && (maximum === undefined || hi < maximum))\n maximum = hi;\n }\n if (pattern)\n return pattern.source;\n // an empty range matches nothing at runtime, and `{8,5}` is not a legal quantifier\n if (minimum !== undefined && maximum !== undefined && minimum > maximum)\n return \"(?!)\";\n if (minimum !== undefined || maximum !== undefined)\n return regexes.string({ minimum, maximum }).source;\n const own = schema._zod.pattern;\n return (isInt && own === regexes.number ? regexes.integer : own)?.source;\n}\n// a part's pattern source. a wrapper's pattern embeds its inner pattern's source verbatim, so the folded form is substituted in place without knowing the wrapper's own composition; a union's options are joined the way the union builds its own pattern\nfunction partPattern(schema) {\n const def = schema._zod.def;\n const own = schema._zod.pattern?.source;\n // lazy resolves its inner on the internals, not the def\n const inner = def.innerType ?? schema._zod.innerType;\n if (inner) {\n const before = inner._zod.pattern?.source;\n const after = partPattern(inner);\n if (own && before && after && after !== before) {\n return own.replace(util.cleanRegex(before), () => util.cleanRegex(after));\n }\n return own;\n }\n if (def.options) {\n const sources = def.options.map(partPattern);\n if (sources.every(Boolean))\n return `^(${sources.map((s) => util.cleanRegex(s)).join(\"|\")})$`;\n }\n return leafPattern(schema);\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const regexParts = [];\n for (const part of def.parts) {\n if (typeof part === \"object\" && part !== null) {\n // is Zod schema\n const source = partPattern(part);\n if (!source) {\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n regexParts.push(util.cleanRegex(source));\n }\n else if (part === null || util.primitiveTypes.has(typeof part)) {\n regexParts.push(util.escapeRegex(`${part}`));\n }\n else {\n throw new Error(`Invalid template literal part: ${part}`);\n }\n }\n inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"string\") {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"string\",\n code: \"invalid_type\",\n });\n return payload;\n }\n inst._zod.pattern.lastIndex = 0;\n if (!inst._zod.pattern.test(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n code: \"invalid_format\",\n format: def.format ?? \"template_literal\",\n pattern: inst._zod.pattern.source,\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n $ZodType.init(inst, def);\n // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter.\n Object.defineProperty(inst, \"_def\", { value: def });\n inst._zod.def = def;\n inst.implement = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implement() must be called with a function\");\n }\n // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function.\n return Object.defineProperty(function (...args) {\n const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n const result = Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return parse(inst._def.output, result);\n }\n return result;\n }, \"_zod\", { value: inst._zod, enumerable: false });\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return Object.defineProperty(async function (...args) {\n const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n const result = await Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return await parseAsync(inst._def.output, result);\n }\n return result;\n }, \"_zod\", { value: inst._zod, enumerable: false });\n };\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"function\") {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"function\",\n input: payload.value,\n inst,\n });\n return payload;\n }\n // Check if output is a promise type to determine if we should use async implementation\n const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n if (hasPromiseOutput) {\n payload.value = inst.implementAsync(payload.value);\n }\n else {\n payload.value = inst.implement(payload.value);\n }\n return payload;\n };\n inst.input = (...args) => {\n const F = inst.constructor;\n if (Array.isArray(args[0])) {\n return new F({\n type: \"function\",\n input: new $ZodTuple({\n type: \"tuple\",\n items: args[0],\n rest: args[1],\n }),\n output: inst._def.output,\n });\n }\n return new F({\n type: \"function\",\n input: args[0],\n output: inst._def.output,\n });\n };\n inst.output = (output) => {\n const F = inst.constructor;\n return new F({\n type: \"function\",\n input: inst._def.input,\n output,\n });\n };\n return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n $ZodType.init(inst, def);\n // Cache the resolved inner type on the shared `def` so all clones of this lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, preserving identity for cycle detection on recursive schemas.\n util.defineLazy(inst._zod, \"innerType\", () => {\n const d = def;\n if (!d._cachedInner)\n d._cachedInner = def.getter();\n return d._cachedInner;\n });\n util.defineLazyInternal(inst, \"pattern\", (zod) => zod.innerType?._zod?.pattern);\n util.defineLazyInternal(inst, \"propValues\", (zod) => zod.innerType?._zod?.propValues);\n util.defineLazyInternal(inst, \"optin\", (zod) => zod.innerType?._zod?.optin ?? undefined);\n util.defineLazyInternal(inst, \"optout\", (zod) => zod.innerType?._zod?.optout ?? undefined);\n inst._zod.parse = (payload, ctx) => {\n const inner = inst._zod.innerType;\n return inner._zod.run(payload, ctx);\n };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n checks.$ZodCheck.init(inst, def);\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _) => {\n return payload;\n };\n inst._zod.check = (payload) => {\n const input = payload.value;\n const r = def.fn(input);\n if (r instanceof Promise) {\n return r.then((r) => handleRefineResult(r, payload, input, inst));\n }\n handleRefineResult(r, payload, input, inst);\n return;\n };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n if (!result) {\n const _iss = {\n code: \"custom\",\n input,\n inst, // incorporates params.error into issue reporting\n path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n continue: !inst._zod.def.abort,\n // params: inst._zod.def.params,\n };\n if (inst._zod.def.params)\n _iss.params = inst._zod.def.params;\n payload.issues.push(util.issue(_iss));\n }\n}\n","import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\nfunction snapshotChecks(def) {\n if (def.checks)\n def.checks = [...def.checks];\n return def;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class(snapshotChecks({ type: \"string\", ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class(snapshotChecks({ type: \"string\", coerce: true, ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n return new Class({\n type: \"string\",\n format: \"email\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"guid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v4\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v6\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v7\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n return new Class({\n type: \"string\",\n format: \"emoji\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"nanoid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link _cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid2\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ulid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"xid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ksuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n return new Class({\n type: \"string\",\n format: \"mac\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n return new Class({\n type: \"string\",\n format: \"e164\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _creditCard(Class, params) {\n return new Class({\n type: \"string\",\n format: \"credit_card\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _iban(Class, params) {\n return new Class({\n type: \"string\",\n format: \"iban\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n return new Class({\n type: \"string\",\n format: \"jwt\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport const TimePrecision = {\n Any: null,\n Minute: -1,\n Second: 0,\n Millisecond: 3,\n Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"datetime\",\n check: \"string_format\",\n offset: false,\n local: false,\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n return new Class({\n type: \"string\",\n format: \"date\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"time\",\n check: \"string_format\",\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n return new Class({\n type: \"string\",\n format: \"duration\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n return new Class(snapshotChecks({ type: \"number\", checks: [], ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class(snapshotChecks({ type: \"number\", coerce: true, checks: [], ...util.normalizeParams(params) }));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"safeint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"int32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"uint32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n return new Class({\n type: \"boolean\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n return new Class({\n type: \"boolean\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n return new Class({\n type: \"bigint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n return new Class({\n type: \"bigint\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"int64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"uint64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n return new Class({\n type: \"symbol\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n return new Class({\n type: \"undefined\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n return new Class({\n type: \"null\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n return new Class({\n type: \"any\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n return new Class({\n type: \"unknown\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n return new Class({\n type: \"never\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n return new Class({\n type: \"void\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n return new Class({\n type: \"date\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n return new Class({\n type: \"date\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n return new Class({\n type: \"nan\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n return new checks.$ZodCheckMultipleOf({\n check: \"multiple_of\",\n ...util.normalizeParams(params),\n value,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n return new checks.$ZodCheckMaxSize({\n check: \"max_size\",\n ...util.normalizeParams(params),\n maximum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n return new checks.$ZodCheckMinSize({\n check: \"min_size\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n return new checks.$ZodCheckSizeEquals({\n check: \"size_equals\",\n ...util.normalizeParams(params),\n size,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n const ch = new checks.$ZodCheckMaxLength({\n check: \"max_length\",\n ...util.normalizeParams(params),\n maximum,\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n return new checks.$ZodCheckMinLength({\n check: \"min_length\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n return new checks.$ZodCheckLengthEquals({\n check: \"length_equals\",\n ...util.normalizeParams(params),\n length,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n return new checks.$ZodCheckRegex({\n check: \"string_format\",\n format: \"regex\",\n ...util.normalizeParams(params),\n pattern,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n return new checks.$ZodCheckLowerCase({\n check: \"string_format\",\n format: \"lowercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n return new checks.$ZodCheckUpperCase({\n check: \"string_format\",\n format: \"uppercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n return new checks.$ZodCheckIncludes({\n check: \"string_format\",\n format: \"includes\",\n ...util.normalizeParams(params),\n includes,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n return new checks.$ZodCheckStartsWith({\n check: \"string_format\",\n format: \"starts_with\",\n ...util.normalizeParams(params),\n prefix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n return new checks.$ZodCheckEndsWith({\n check: \"string_format\",\n format: \"ends_with\",\n ...util.normalizeParams(params),\n suffix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n return new checks.$ZodCheckProperty({\n check: \"property\",\n property,\n schema,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _properties(shape, params) {\n return new checks.$ZodCheckProperties({\n check: \"properties\",\n shape,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n return new checks.$ZodCheckMimeType({\n check: \"mime_type\",\n mime: types,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n return new checks.$ZodCheckOverwrite({\n check: \"overwrite\",\n tx,\n });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n return new Class({\n type: \"array\",\n element,\n // get element() {\n // return element;\n // },\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n ...util.normalizeParams(params),\n });\n}\nexport function _xor(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n return new Class({\n type: \"union\",\n options: options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n return new Class({\n type: \"intersection\",\n left,\n right,\n });\n}\n// export function _tuple(\n// Class: util.SchemaClass<schemas.$ZodTuple>,\n// items: [],\n// params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new Class({\n type: \"tuple\",\n items,\n rest,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n return new Class({\n type: \"record\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n return new Class({\n type: \"map\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n return new Class({\n type: \"set\",\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n // if (Array.isArray(values)) {\n // for (const value of values) {\n // entries[value] = value;\n // }\n // } else {\n // Object.assign(entries, values);\n // }\n // const entries: util.EnumLike = {};\n // for (const val of values) {\n // entries[val] = val;\n // }\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n return new Class({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n return new Class({\n type: \"file\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n return new Class({\n type: \"transform\",\n transform: fn,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n return new Class({\n type: \"optional\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n return new Class({\n type: \"nullable\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n return new Class({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n return new Class({\n type: \"nonoptional\",\n innerType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n return new Class({\n type: \"success\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n return new Class({\n type: \"catch\",\n innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : util.constantCatch(catchValue)),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n return new Class({\n type: \"pipe\",\n in: in_,\n out,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n return new Class({\n type: \"readonly\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n return new Class({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n return new Class({\n type: \"lazy\",\n getter,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n return new Class({\n type: \"promise\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n const norm = util.normalizeParams(_params);\n norm.abort ?? (norm.abort = true); // default to abort:false\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...norm,\n });\n return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...util.normalizeParams(_params),\n });\n return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn, params) {\n const ch = _check((payload) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n if (!(\"input\" in _issue))\n _issue.input = payload.value;\n _issue.inst ?? (_issue.inst = ch);\n _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n payload.issues.push(util.issue(_issue));\n }\n };\n return fn(payload.value, payload);\n }, params);\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n const ch = new checks.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n const ch = new checks.$ZodCheck({ check: \"describe\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, description });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n const ch = new checks.$ZodCheck({ check: \"meta\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, ...metadata });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n const params = util.normalizeParams(_params);\n let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n if (params.case !== \"sensitive\") {\n truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n }\n const truthySet = new Set(truthyArray);\n const falsySet = new Set(falsyArray);\n const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n const _String = Classes.String ?? schemas.$ZodString;\n const stringSchema = new _String({ type: \"string\", error: params.error });\n const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n const codec = new _Codec({\n type: \"pipe\",\n in: stringSchema,\n out: booleanSchema,\n transform: ((input, payload) => {\n let data = input;\n if (params.case !== \"sensitive\")\n data = data.toLowerCase();\n if (truthySet.has(data)) {\n return true;\n }\n else if (falsySet.has(data)) {\n return false;\n }\n else {\n payload.issues.push({\n code: \"invalid_value\",\n expected: \"stringbool\",\n values: [...truthySet, ...falsySet],\n input: payload.value,\n inst: codec,\n continue: false,\n });\n return {};\n }\n }),\n reverseTransform: ((input, _payload) => {\n if (input === true) {\n return truthyArray[0] || \"true\";\n }\n else {\n return falsyArray[0] || \"false\";\n }\n }),\n error: params.error,\n });\n codec._zod.bag.truthy = truthyArray;\n codec._zod.bag.falsy = falsyArray;\n codec._zod.bag.case = params.case ?? \"insensitive\";\n return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n check: \"string_format\",\n type: \"string\",\n format,\n fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n ...params,\n };\n if (fnOrRegex instanceof RegExp) {\n def.pattern = fnOrRegex;\n }\n const inst = new Class(def);\n return inst;\n}\n","import { globalRegistry } from \"./registries.js\";\nimport { assignProp } from \"./util.js\";\nfunction assignProps(target, ...sources) {\n for (const source of sources) {\n for (const key of Reflect.ownKeys(source)) {\n if (Object.prototype.propertyIsEnumerable.call(source, key)) {\n assignProp(target, key, source[key]);\n }\n }\n }\n return target;\n}\n// function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {\n// return {\n// processor: inputs.processor,\n// metadataRegistry: inputs.metadata ?? globalRegistry,\n// target: inputs.target ?? \"draft-2020-12\",\n// unrepresentable: inputs.unrepresentable ?? \"throw\",\n// };\n// }\nexport function initializeContext(params) {\n // Normalize target: convert old non-hyphenated versions to hyphenated versions\n let target = params?.target ?? \"draft-2020-12\";\n if (target === \"draft-4\")\n target = \"draft-04\";\n if (target === \"draft-7\")\n target = \"draft-07\";\n return {\n processors: params.processors ?? {},\n metadataRegistry: params?.metadata ?? globalRegistry,\n target,\n unrepresentable: params?.unrepresentable ?? \"throw\",\n override: params?.override ?? (() => { }),\n io: params?.io ?? \"output\",\n counter: 0,\n seen: new Map(),\n sharedDefsExtractedFor: undefined,\n sharedEmitDoneFor: undefined,\n cycles: params?.cycles ?? \"ref\",\n reused: params?.reused ?? \"inline\",\n intersections: [],\n deferred: [],\n external: params?.external ?? undefined,\n };\n}\n/**\n * Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws\n * `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a\n * custom JSON Schema was written into `json`, in which case the caller must not write its own.\n */\nexport function handleUnrepresentable(schema, ctx, json, params, message) {\n const result = typeof ctx.unrepresentable === \"function\"\n ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message })\n : ctx.unrepresentable;\n if (result === \"any\")\n return false;\n if (result === undefined || result === \"throw\")\n throw new Error(message);\n Object.assign(json, result);\n return true;\n}\n// never rename this back to `process`: bundler polyfills inject a top-level `const process` that a lexical declaration of the same name collides with (#6397)\nexport function processSchema(schema, ctx, _params = { path: [], schemaPath: [] }) {\n var _a;\n const def = schema._zod.def;\n // check for schema in seens\n const seen = ctx.seen.get(schema);\n if (seen) {\n seen.count++;\n // check if cycle\n const isCycle = _params.schemaPath.includes(schema);\n if (isCycle) {\n seen.cycle = _params.path;\n }\n return seen.schema;\n }\n // initialize\n const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };\n ctx.seen.set(schema, result);\n ctx.sharedDefsExtractedFor = undefined;\n ctx.sharedEmitDoneFor = undefined;\n // custom method overrides default behavior\n const overrideSchema = schema._zod.toJSONSchema?.();\n if (overrideSchema) {\n result.schema = overrideSchema;\n }\n else {\n const params = {\n ..._params,\n schemaPath: [..._params.schemaPath, schema],\n path: _params.path,\n };\n if (schema._zod.processJSONSchema) {\n schema._zod.processJSONSchema(ctx, result.schema, params);\n }\n else {\n const _json = result.schema;\n const processor = ctx.processors[def.type];\n if (!processor) {\n throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);\n }\n processor(schema, ctx, _json, params);\n }\n const parent = schema._zod.parent;\n if (parent) {\n // Also set ref if processor didn't (for inheritance)\n if (!result.ref)\n result.ref = parent;\n processSchema(parent, ctx, params);\n ctx.seen.get(parent).isParent = true;\n }\n }\n // metadata\n const meta = ctx.metadataRegistry.get(schema);\n if (meta)\n assignProps(result.schema, meta);\n if (ctx.io === \"input\" && isTransforming(schema)) {\n // examples/defaults only apply to output type of pipe\n delete result.schema.examples;\n delete result.schema.default;\n }\n // set prefault as default\n if (ctx.io === \"input\" && \"_prefault\" in result.schema)\n (_a = result.schema).default ?? (_a.default = result.schema._prefault);\n delete result.schema._prefault;\n // pulling fresh from ctx.seen in case it was overwritten\n const _result = ctx.seen.get(schema);\n return _result.schema;\n}\n/** @deprecated Renamed to `processSchema`. An export alias declares no binding, so it is safe to keep. */\nexport { processSchema as process };\n// Escape a reference token for use in a JSON Pointer fragment (RFC 6901): `~` becomes `~0` and `/` becomes `~1`. The `~` replacement must run first.\nfunction encodeJSONPointerSegment(segment) {\n return segment.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n}\nexport function extractDefs(ctx, schema\n// params: EmitParams\n) {\n // iterate over seen map;\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // With `external` set, every registered schema resolves through the external branch of `makeURI`, so the root branch below produces the same ref the external branch would — this pass is identical whichever schema it is called with, and only needs to run once.\n if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external)\n return;\n // Track ids to detect duplicates across different schemas\n const idToSchema = new Map();\n for (const entry of ctx.seen.entries()) {\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n const existing = idToSchema.get(id);\n if (existing && existing !== entry[0]) {\n throw new Error(`Duplicate schema id \"${id}\" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);\n }\n idToSchema.set(id, entry[0]);\n }\n }\n // returns a ref to the schema defId will be empty if the ref points to an external schema (or #)\n const makeURI = (entry) => {\n // comparing the seen objects because sometimes multiple schemas map to the same seen object. e.g. lazy\n // external is configured\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n if (ctx.external) {\n const externalId = ctx.external.registry.get(entry[0])?.id; // ?? \"__shared\";// `__schema${ctx.counter++}`;\n // check if schema is in the external registry\n const uriGenerator = ctx.external.uri ?? ((id) => id);\n if (externalId) {\n return { ref: uriGenerator(externalId) };\n }\n // otherwise, add to __shared\n const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;\n entry[1].defId = id; // set defId so it will be reused if needed\n return { defId: id, ref: `${uriGenerator(\"__shared\")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` };\n }\n const uriPrefix = `#`;\n const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n // an id-less root has nowhere to be extracted to, so it stays inline and self-references as `#`\n if (entry[1] === root && !entry[1].schema.id) {\n return { ref: uriPrefix };\n }\n // self-contained schema\n const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) };\n };\n // stored cached version in `def` property remove all properties, set $ref\n const extractToDef = (entry) => {\n // if the schema is already a reference, do not extract it\n if (entry[1].schema.$ref) {\n return;\n }\n const seen = entry[1];\n const { ref, defId } = makeURI(entry);\n seen.def = { ...seen.schema };\n // defId won't be set if the schema is a reference to an external schema or if the schema is the root schema\n if (defId)\n seen.defId = defId;\n // wipe away all properties except $ref\n const schema = seen.schema;\n for (const key in schema) {\n delete schema[key];\n }\n schema.$ref = ref;\n };\n // throw on cycles\n // break cycles\n if (ctx.cycles === \"throw\") {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.cycle) {\n throw new Error(\"Cycle detected: \" +\n `#/${seen.cycle?.join(\"/\")}/<root>` +\n '\\n\\nSet the `cycles` parameter to `\"ref\"` to resolve cyclical schemas with defs.');\n }\n }\n }\n // extract schemas into $defs\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n // convert root schema to # $ref\n if (schema === entry[0]) {\n extractToDef(entry); // this has special handling for the root schema\n continue;\n }\n // extract schemas that are in the external registry\n if (ctx.external) {\n const ext = ctx.external.registry.get(entry[0])?.id;\n if (schema !== entry[0] && ext) {\n extractToDef(entry);\n continue;\n }\n }\n // extract schemas with `id` meta\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n extractToDef(entry);\n continue;\n }\n // break cycles\n if (seen.cycle) {\n // any\n extractToDef(entry);\n continue;\n }\n // extract reused schemas\n if (seen.count > 1) {\n if (ctx.reused === \"ref\") {\n extractToDef(entry);\n }\n }\n }\n if (ctx.external)\n ctx.sharedDefsExtractedFor = ctx.external;\n}\n/** Rewrites `anyOf: [{type: \"a\"}, {type: \"b\"}]` to `type: [\"a\", \"b\"]`, which every JSON Schema draft treats as equivalent and most consumers render far better for the nullable case. Only branches that are a bare type assertion qualify — anything carrying a constraint, `$ref`, `const` or metadata is left alone. Runs after `flattenRef`, so a branch an override decorated or `$defs` extraction turned into a `$ref` is no longer bare and correctly stays in `anyOf`. `oneOf` is excluded: `integer` and `number` overlap, so \"exactly one\" and \"at least one\" are not the same there. OpenAPI 3.0 is excluded: its `type` must be a single string. */\nfunction compactTypeUnion(schema) {\n const options = schema.anyOf;\n if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined)\n return;\n const types = [];\n for (const option of options) {\n if (!option || typeof option !== \"object\")\n return;\n // A branch that is itself a compactible union folds into this one — nested `anyOf` and a flat `type` array say the same thing. Compacting it first also makes the result independent of the order this pass walks the seen map in.\n compactTypeUnion(option);\n const keys = Object.keys(option);\n if (keys.length !== 1 || keys[0] !== \"type\")\n return;\n const type = option.type;\n for (const member of Array.isArray(type) ? type : [type]) {\n if (typeof member !== \"string\")\n return;\n if (!types.includes(member))\n types.push(member);\n }\n }\n delete schema.anyOf;\n // A `type` array must be non-empty and unique (metaschema); a single member is spelled as a bare string.\n schema.type = types.length === 1 ? types[0] : types;\n}\n/** Keywords `foldIntersection` knows how to combine. Anything else — `$ref`, `patternProperties`,\n * an annotation like `description` — makes a member unfoldable, so a constraint this does not\n * understand leaves the `allOf` alone instead of being silently dropped or misattributed. */\nconst FOLDABLE_KEYS = new Set([\"type\", \"properties\", \"required\", \"additionalProperties\"]);\nconst UNION_KEYS = [\"oneOf\", \"anyOf\"];\n/** A member's constraint on a key it does not declare itself. A `catchall` states one; `false`, an absent `additionalProperties`, and the empty schema a loose object emits state nothing. */\nfunction undeclaredConstraint(member) {\n const extra = member.additionalProperties;\n if (extra === undefined || extra === false || typeof extra !== \"object\" || extra === null)\n return null;\n return Object.keys(extra).length ? extra : null;\n}\n/** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */\nfunction foldObjects(members) {\n const objects = [];\n for (const member of members) {\n // A boolean subschema is legal JSON Schema and carries no keywords to fold.\n if (typeof member !== \"object\" || member.type !== \"object\")\n return null;\n for (const key in member) {\n if (!FOLDABLE_KEYS.has(key))\n return null;\n }\n objects.push(member);\n }\n const properties = {};\n const required = new Set();\n for (const object of objects) {\n for (const key in object.properties) {\n // `in` would report a `__proto__` key as already present via the prototype chain and skip it.\n if (Object.prototype.hasOwnProperty.call(properties, key))\n continue;\n // Every member constrains this key: the ones that declare it say how, and a `catchall` member constrains it too even though it does not name it. The key has to satisfy all of them, which is the same intersection one level down.\n const parts = [];\n for (const other of objects) {\n const part = other.properties?.[key] ?? undeclaredConstraint(other);\n if (part === null || part === undefined)\n continue;\n if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part)))\n parts.push(part);\n }\n const merged = parts.length === 1\n ? parts[0]\n : (foldObjects(parts) ?? { allOf: parts });\n assignProp(properties, key, merged);\n }\n for (const key of object.required ?? [])\n required.add(key);\n }\n const folded = { type: \"object\", properties };\n if (required.size)\n folded.required = [...required];\n // A key no member declares is rejected only when every member rejects it, so the fold is closed only when every member is. Otherwise it carries whatever the `catchall` members demand of such a key.\n if (objects.every((object) => object.additionalProperties === false)) {\n folded.additionalProperties = false;\n }\n else {\n const constraints = [];\n for (const object of objects) {\n const constraint = undeclaredConstraint(object);\n if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint)))\n constraints.push(constraint);\n }\n if (constraints.length === 1)\n folded.additionalProperties = constraints[0];\n else if (constraints.length > 1)\n folded.additionalProperties = { allOf: constraints };\n }\n return folded;\n}\n/** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two\n * closed object members reject each other's keys and the schema validates nothing. Zod's parser\n * pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when\n * *every* side rejects it — so the emitted schema has to pool them too, and folding the members\n * into one object is the encoding that says so on every target.\n *\n * This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref`\n * machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it\n * keeps its reference and its own closedness rather than being inlined as a stale copy. */\nfunction foldIntersection(json) {\n const allOf = json.allOf;\n if (!Array.isArray(allOf) || allOf.length < 2)\n return;\n // An `override` runs before this pass and may have written object keywords onto the intersection itself. Those are deliberate, so decline rather than overwrite them.\n for (const key of FOLDABLE_KEYS)\n if (key in json)\n return;\n // An intersection distributes over a union: `A & (X | Y)` is `(A & X) | (A & Y)`. Only the first union is distributed over; a second one stays among the members every branch folds against, where it fails the object check and declines the whole intersection rather than multiplying out.\n const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k])));\n let folded = null;\n if (!unions.length) {\n folded = foldObjects(allOf);\n }\n else {\n const union = unions[0];\n const keyword = UNION_KEYS.find((k) => Array.isArray(union[k]));\n if (Object.keys(union).length !== 1)\n return;\n const rest = allOf.filter((m) => m !== union);\n const branches = union[keyword].map((branch) => foldObjects([...rest, branch]));\n if (branches.some((b) => !b))\n return;\n folded = { [keyword]: branches };\n }\n if (!folded)\n return;\n delete json.allOf;\n assignProps(json, folded);\n}\nexport function finalize(ctx, schema) {\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // flatten refs - inherit properties from parent schemas\n const flattenRef = (zodSchema) => {\n const seen = ctx.seen.get(zodSchema);\n // already processed\n if (seen.ref === null)\n return;\n const schema = seen.def ?? seen.schema;\n const _cached = { ...schema };\n const ref = seen.ref;\n seen.ref = null; // prevent infinite recursion\n if (ref) {\n flattenRef(ref);\n const refSeen = ctx.seen.get(ref);\n const refSchema = refSeen.schema;\n // merge referenced schema into current\n if (refSchema.$ref && (ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\")) {\n // older drafts can't combine $ref with other properties\n schema.allOf = schema.allOf ?? [];\n schema.allOf.push(refSchema);\n }\n else {\n assignProps(schema, refSchema);\n }\n // restore child's own properties (child wins)\n assignProps(schema, _cached);\n const isParentRef = zodSchema._zod.parent === ref;\n // For parent chain, child is a refinement - remove parent-only properties\n if (isParentRef) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (!(key in _cached)) {\n delete schema[key];\n }\n }\n }\n // When ref was extracted to $defs, remove properties that match the definition\n if (refSchema.$ref && refSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n // If parent was extracted (has $ref), propagate $ref to this schema. This handles cases like: readonly().meta({id}).describe() where processor sets ref to innerType but parent should be referenced\n const parent = zodSchema._zod.parent;\n if (parent && parent !== ref) {\n // Ensure parent is processed first so its def has inherited properties\n flattenRef(parent);\n const parentSeen = ctx.seen.get(parent);\n if (parentSeen?.schema.$ref) {\n schema.$ref = parentSeen.schema.$ref;\n // De-duplicate with parent's definition\n if (parentSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n }\n // execute overrides\n ctx.override({\n zodSchema: zodSchema,\n jsonSchema: schema,\n path: seen.path ?? [],\n });\n };\n // Flattening walks the whole map and clears each `ref` as it goes, so a second call over the same map is a no-op scan. Skip it outright once it has run for a registry conversion.\n if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {\n for (const entry of [...ctx.seen.entries()].reverse()) {\n flattenRef(entry[0]);\n }\n if (ctx.target !== \"openapi-3.0\") {\n for (const entry of ctx.seen.entries()) {\n compactTypeUnion(entry[1].def ?? entry[1].schema);\n }\n }\n for (const rewrite of ctx.deferred)\n rewrite();\n // After flattening, every member that was extracted is a `$ref`, so the fold sees the final shape. A schema that inherits an intersection — through `z.lazy`, or any `ref` chain — holds the same `allOf` array, so fold by array identity to catch every copy.\n if (ctx.intersections.length) {\n const carriers = new Map();\n for (const seen of ctx.seen.values()) {\n for (const json of [seen.schema, seen.def]) {\n const allOf = json?.allOf;\n if (!Array.isArray(allOf))\n continue;\n const existing = carriers.get(allOf);\n if (existing)\n existing.push(json);\n else\n carriers.set(allOf, [json]);\n }\n }\n for (const allOf of ctx.intersections) {\n for (const json of carriers.get(allOf) ?? [])\n foldIntersection(json);\n }\n }\n }\n const result = {};\n if (ctx.target === \"draft-2020-12\") {\n result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n }\n else if (ctx.target === \"draft-07\") {\n result.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n else if (ctx.target === \"draft-04\") {\n result.$schema = \"http://json-schema.org/draft-04/schema#\";\n }\n else if (ctx.target === \"openapi-3.0\") {\n // OpenAPI 3.0 schema objects should not include a $schema property\n }\n else {\n // Arbitrary string values are allowed but won't have a $schema property set\n }\n if (ctx.external?.uri) {\n const id = ctx.external.registry.get(schema)?.id;\n if (!id)\n throw new Error(\"Schema is missing an `id` property\");\n result.$id = ctx.external.uri(id);\n }\n // when the root was extracted into $defs, `root.schema` is the `$ref` wrapper and `root.def` is the body that now lives under $defs\n assignProps(result, root.defId ? root.schema : (root.def ?? root.schema));\n // The `id` in `.meta()` is a Zod-specific registration tag used to extract schemas into $defs — it is not user-facing JSON Schema metadata. Strip it from the output body where it would otherwise leak. The id is preserved implicitly via the $defs key (and via $ref paths).\n const rootMetaId = ctx.metadataRegistry.get(schema)?.id;\n if (rootMetaId !== undefined && result.id === rootMetaId)\n delete result.id;\n // build defs object. With `external`, `defs` is the shared object every schema writes into, so the same entries are reassigned on every call. Without it, `defs` is fresh per call and must be rebuilt.\n const defs = ctx.external?.defs ?? {};\n if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.def && seen.defId) {\n if (seen.def.id === seen.defId)\n delete seen.def.id;\n assignProp(defs, seen.defId, seen.def);\n }\n }\n }\n if (ctx.external)\n ctx.sharedEmitDoneFor = ctx.external;\n // set definitions in result\n if (ctx.external) {\n }\n else {\n if (Object.keys(defs).length > 0) {\n if (ctx.target === \"draft-2020-12\") {\n result.$defs = defs;\n }\n else {\n result.definitions = defs;\n }\n }\n }\n try {\n // this \"finalizes\" this schema and ensures all cycles are removed each call to finalize() is functionally independent though the seen map is shared\n const finalized = JSON.parse(JSON.stringify(result));\n Object.defineProperty(finalized, \"~standard\", {\n value: {\n ...schema[\"~standard\"],\n jsonSchema: {\n input: createStandardJSONSchemaMethod(schema, \"input\", ctx.processors),\n output: createStandardJSONSchemaMethod(schema, \"output\", ctx.processors),\n },\n },\n enumerable: false,\n writable: false,\n });\n return finalized;\n }\n catch (_err) {\n throw new Error(\"Error converting schema to JSON.\");\n }\n}\nfunction isTransforming(_schema, _ctx) {\n const ctx = _ctx ?? { seen: new Set() };\n if (ctx.seen.has(_schema))\n return false;\n ctx.seen.add(_schema);\n const def = _schema._zod.def;\n if (def.type === \"transform\")\n return true;\n if (def.type === \"array\")\n return isTransforming(def.element, ctx);\n if (def.type === \"set\")\n return isTransforming(def.valueType, ctx);\n if (def.type === \"lazy\")\n return isTransforming(def.getter(), ctx);\n if (def.type === \"promise\" ||\n def.type === \"optional\" ||\n def.type === \"nonoptional\" ||\n def.type === \"nullable\" ||\n def.type === \"readonly\" ||\n def.type === \"default\" ||\n def.type === \"prefault\" ||\n def.type === \"catch\") {\n return isTransforming(def.innerType, ctx);\n }\n if (def.type === \"intersection\") {\n return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);\n }\n if (def.type === \"record\" || def.type === \"map\") {\n return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);\n }\n if (def.type === \"pipe\") {\n if (_schema._zod.traits.has(\"$ZodCodec\"))\n return true;\n return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);\n }\n if (def.type === \"object\") {\n for (const key in def.shape) {\n if (isTransforming(def.shape[key], ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"union\") {\n for (const option of def.options) {\n if (isTransforming(option, ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"tuple\") {\n for (const item of def.items) {\n if (isTransforming(item, ctx))\n return true;\n }\n if (def.rest && isTransforming(def.rest, ctx))\n return true;\n return false;\n }\n return false;\n}\n/**\n * Creates a toJSONSchema method for a schema instance.\n * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.\n */\nexport const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {\n const ctx = initializeContext({ ...params, processors });\n processSchema(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\nexport const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {\n const { libraryOptions, target } = params ?? {};\n const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });\n processSchema(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\n","import * as regexes from \"./regexes.js\";\nimport { base64Charset, base64urlCharset } from \"./schemas.js\";\nimport { extractDefs, finalize, handleUnrepresentable, initializeContext, processSchema, } from \"./to-json-schema.js\";\nimport { BIGINT_FORMAT_RANGES, NUMBER_FORMAT_RANGES, assignProp, getEnumValues } from \"./util.js\";\nconst narrowMin = (agg, key, value) => {\n if (agg[key] === undefined || value > agg[key])\n agg[key] = value;\n};\nconst narrowMax = (agg, key, value) => {\n if (agg[key] === undefined || value < agg[key])\n agg[key] = value;\n};\nconst narrowBoth = (agg, value) => {\n narrowMin(agg, \"minimum\", value);\n narrowMax(agg, \"maximum\", value);\n};\nconst addDivisor = (agg, value) => {\n agg.multipleOf ?? (agg.multipleOf = []);\n if (!agg.multipleOf.includes(value))\n agg.multipleOf.push(value);\n};\nconst addPattern = (agg, pattern) => {\n agg.patterns ?? (agg.patterns = new Set());\n agg.patterns.add(pattern);\n};\nconst intersectMime = (agg, mime) => {\n agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime];\n};\n// last-wins, matching the bag's historical write order; the flag keeps an integer format from being lost to a later float one\nconst setFormat = (agg, format) => {\n agg.format = format;\n if (format.includes(\"int\"))\n agg.isInt = true;\n};\nconst minContributor = (agg, def) => narrowMin(agg, \"minimum\", def.minimum);\nconst maxContributor = (agg, def) => narrowMax(agg, \"maximum\", def.maximum);\nconst formatContributor = (ranges) => (agg, def) => {\n setFormat(agg, def.format);\n const [minimum, maximum] = ranges[def.format];\n narrowMin(agg, \"minimum\", minimum);\n narrowMax(agg, \"maximum\", maximum);\n};\nconst contributors = {\n greater_than: (agg, def) => narrowMin(agg, def.inclusive ? \"minimum\" : \"exclusiveMinimum\", def.value),\n less_than: (agg, def) => narrowMax(agg, def.inclusive ? \"maximum\" : \"exclusiveMaximum\", def.value),\n multiple_of: (agg, def) => addDivisor(agg, def.value),\n number_format: formatContributor(NUMBER_FORMAT_RANGES),\n bigint_format: formatContributor(BIGINT_FORMAT_RANGES),\n min_length: minContributor,\n max_length: maxContributor,\n length_equals: (agg, def) => narrowBoth(agg, def.length),\n min_size: minContributor,\n max_size: maxContributor,\n size_equals: (agg, def) => narrowBoth(agg, def.size),\n string_format: (agg, def) => {\n setFormat(agg, def.format);\n if (def.pattern)\n addPattern(agg, def.pattern);\n if (def.format === \"base64\" || def.format === \"base64url\")\n agg.contentEncoding = def.format;\n if (def.local || def.precision === -1)\n agg.laxFormat = true;\n },\n mime_type: (agg, def) => intersectMime(agg, def.mime),\n};\nexport function aggregateChecks(schema) {\n const agg = {};\n const def = schema._zod.def;\n // a format schema is its own first check, same rule as $ZodType init\n const list = schema._zod.traits.has(\"$ZodCheck\")\n ? [schema, ...(def.checks ?? [])]\n : (def.checks ?? []);\n for (const ch of list)\n contributors[ch._zod.def.check]?.(agg, ch._zod.def);\n // reconcile with the bag so third-party onattach contributions still land; first-party residue is never tighter than the fold, so merging it back is idempotent for one and additive for the other\n const bag = schema._zod.bag;\n if (bag.minimum !== undefined)\n narrowMin(agg, \"minimum\", bag.minimum);\n if (bag.exclusiveMinimum !== undefined)\n narrowMin(agg, \"exclusiveMinimum\", bag.exclusiveMinimum);\n if (bag.maximum !== undefined)\n narrowMax(agg, \"maximum\", bag.maximum);\n if (bag.exclusiveMaximum !== undefined)\n narrowMax(agg, \"exclusiveMaximum\", bag.exclusiveMaximum);\n if (bag.multipleOf !== undefined)\n addDivisor(agg, bag.multipleOf);\n if (bag.format !== undefined) {\n agg.format ?? (agg.format = bag.format);\n if (bag.format.includes(\"int\"))\n agg.isInt = true;\n }\n if (bag.mime)\n intersectMime(agg, bag.mime);\n for (const pattern of bag.patterns ?? [])\n addPattern(agg, pattern);\n return agg;\n}\nconst formatMap = {\n guid: \"uuid\",\n url: \"uri\",\n datetime: \"date-time\",\n json_string: \"json-string\",\n regex: \"\", // do not set\n};\n// ==================== SIMPLE TYPE PROCESSORS ====================\n// the runtime patterns are lax so parse paths never overflow the regex stack; the emitted schema swaps in the exact block forms, which zod itself never executes\nconst exactPatterns = new Map([\n [base64Charset, regexes.base64],\n [base64urlCharset, regexes.base64url],\n]);\nconst exactPattern = (p) => exactPatterns.get(p) ?? p;\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n json.type = \"string\";\n const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema);\n if (typeof minimum === \"number\")\n json.minLength = minimum;\n if (typeof maximum === \"number\")\n json.maxLength = maximum;\n // custom pattern overrides format\n if (format) {\n json.format = formatMap[format] ?? format;\n if (json.format === \"\")\n delete json.format; // empty format is not valid\n // `z.iso.time()` is never full-time, and `laxFormat` carries the datetime shapes that also accept what their keyword forbids\n if (format === \"time\" || laxFormat) {\n delete json.format;\n }\n }\n if (contentEncoding)\n json.contentEncoding = contentEncoding;\n if (patterns && patterns.size > 0) {\n const patternList = [...patterns].map(exactPattern);\n if (patternList.length === 1)\n json.pattern = patternList[0].source;\n else if (patternList.length > 1) {\n json.allOf = [\n ...patternList.map((regex) => ({\n ...(ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\"\n ? { type: \"string\" }\n : {}),\n pattern: regex.source,\n })),\n ];\n }\n }\n};\nexport const numberProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema);\n json.type = isInt ? \"integer\" : \"number\";\n // when both minimum and exclusiveMinimum exist, pick the more restrictive one\n const exMin = typeof exclusiveMinimum === \"number\" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);\n const exMax = typeof exclusiveMaximum === \"number\" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);\n const legacy = ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\";\n if (exMin) {\n if (legacy) {\n json.minimum = exclusiveMinimum;\n json.exclusiveMinimum = true;\n }\n else {\n json.exclusiveMinimum = exclusiveMinimum;\n }\n }\n else if (typeof minimum === \"number\") {\n json.minimum = minimum;\n }\n if (exMax) {\n if (legacy) {\n json.maximum = exclusiveMaximum;\n json.exclusiveMaximum = true;\n }\n else {\n json.exclusiveMaximum = exclusiveMaximum;\n }\n }\n else if (typeof maximum === \"number\") {\n json.maximum = maximum;\n }\n if (multipleOf) {\n // JSON Schema requires a divisor strictly greater than zero, and a non-finite one does not survive JSON at all. A negative divisor accepts exactly what its absolute value accepts, so it still maps; zero, NaN and Infinity have no keyword form.\n const divisors = new Set();\n for (const divisor of multipleOf) {\n if (Number.isFinite(divisor) && divisor !== 0)\n divisors.add(Math.abs(divisor));\n else\n handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);\n }\n // chained divisors are a conjunction the keyword cannot carry alone, so extras ride an allOf, same as stacked patterns\n const [first, ...rest] = divisors;\n if (first !== undefined)\n json.multipleOf = first;\n if (rest.length)\n json.allOf = [...(json.allOf ?? []), ...rest.map((m) => ({ multipleOf: m }))];\n }\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const bigintProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"BigInt cannot be represented in JSON Schema\");\n};\nexport const symbolProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Symbols cannot be represented in JSON Schema\");\n};\nexport const nullProcessor = (_schema, ctx, json, _params) => {\n if (ctx.target === \"openapi-3.0\") {\n json.type = \"string\";\n json.nullable = true;\n json.enum = [null];\n }\n else {\n json.type = \"null\";\n }\n};\nexport const undefinedProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Undefined cannot be represented in JSON Schema\");\n};\nexport const voidProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Void cannot be represented in JSON Schema\");\n};\nexport const neverProcessor = (_schema, _ctx, json, _params) => {\n json.not = {};\n};\nexport const anyProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const unknownProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const dateProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Date cannot be represented in JSON Schema\");\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n const def = schema._zod.def;\n const values = getEnumValues(def.entries);\n // an empty enum accepts nothing, same as z.never()\n if (values.length === 0) {\n json.not = {};\n return;\n }\n // Number enums can have both string and number values\n if (values.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (values.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n json.enum = values;\n};\nexport const literalProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // a literal with no values accepts nothing, same as z.never()\n if (def.values.length === 0) {\n json.not = {};\n return;\n }\n const vals = [];\n for (const val of def.values) {\n if (val === undefined) {\n // a custom schema replaces the whole literal, so there is nothing left to accumulate\n if (handleUnrepresentable(schema, ctx, json, params, \"Literal `undefined` cannot be represented in JSON Schema\"))\n return;\n // otherwise do not add to vals\n }\n else if (typeof val === \"bigint\") {\n if (handleUnrepresentable(schema, ctx, json, params, \"BigInt literals cannot be represented in JSON Schema\"))\n return;\n vals.push(Number(val));\n }\n else {\n vals.push(val);\n }\n }\n if (vals.length === 0) {\n // do nothing (an undefined literal was stripped)\n }\n else if (vals.length === 1) {\n const val = vals[0];\n json.type = val === null ? \"null\" : typeof val;\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.enum = [val];\n }\n else {\n json.const = val;\n }\n }\n else {\n if (vals.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (vals.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n if (vals.every((v) => typeof v === \"boolean\"))\n json.type = \"boolean\";\n if (vals.every((v) => v === null))\n json.type = \"null\";\n json.enum = vals;\n }\n};\nexport const nanProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"NaN cannot be represented in JSON Schema\");\n};\nexport const templateLiteralProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const pattern = schema._zod.pattern;\n if (!pattern)\n throw new Error(\"Pattern not found in template literal\");\n _json.type = \"string\";\n _json.pattern = pattern.source;\n};\nexport const fileProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n _json.type = \"string\";\n _json.format = \"binary\";\n _json.contentEncoding = \"binary\";\n const { minimum, maximum, mime } = aggregateChecks(schema);\n if (minimum !== undefined)\n _json.minLength = minimum;\n if (maximum !== undefined)\n _json.maxLength = maximum;\n if (!mime)\n return;\n // an empty intersection means the mime checks share no value, so nothing passes at runtime; `anyOf` must be non-empty, so the false schema is `not: {}`\n if (mime.length === 0)\n _json.not = {};\n else if (mime.length === 1)\n _json.contentMediaType = mime[0];\n // only contentMediaType differs, so the shared props stay at the root\n else\n _json.anyOf = mime.map((m) => ({ contentMediaType: m }));\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const customProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Custom types cannot be represented in JSON Schema\");\n};\nexport const functionProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Function types cannot be represented in JSON Schema\");\n};\nexport const transformProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Transforms cannot be represented in JSON Schema\");\n};\nexport const mapProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Map cannot be represented in JSON Schema\");\n};\nexport const setProcessor = (schema, ctx, json, params) => {\n handleUnrepresentable(schema, ctx, json, params, \"Set cannot be represented in JSON Schema\");\n};\n// ==================== COMPOSITE TYPE PROCESSORS ====================\nexport const arrayProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const { minimum, maximum } = aggregateChecks(schema);\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n json.type = \"array\";\n json.items = processSchema(def.element, ctx, {\n ...params,\n path: [...params.path, \"items\"],\n });\n};\n// Transform and catch set `optin = \"optional\"` at runtime so the parser lets them observe an\n// absent key, but their declared input type stays required. An input JSON Schema describes the\n// declared type, so resolve past them to the schema that actually carries the optionality.\n// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see\n// wiki/optionality.md, \"The JSON Schema emitter reads the *static* value\".\nfunction inputOptin(schema) {\n const def = schema._zod.def;\n if (def.type === \"pipe\" && def.in._zod.traits.has(\"$ZodTransform\")) {\n return inputOptin(def.out);\n }\n if (def.type === \"catch\") {\n return inputOptin(def.innerType);\n }\n return schema._zod.optin;\n}\nexport const objectProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const shape = def.shape;\n // dropping it while still emitting `additionalProperties: false` would emit a schema that rejects data this one requires\n const symbolKeys = Object.getOwnPropertySymbols(shape);\n if (symbolKeys.length &&\n handleUnrepresentable(schema, ctx, json, params, \"Symbol keys cannot be represented in JSON Schema\")) {\n return;\n }\n json.type = \"object\";\n json.properties = {};\n for (const key in shape) {\n // assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter on the plain {} we build into\n assignProp(json.properties, key, processSchema(shape[key], ctx, {\n ...params,\n path: [...params.path, \"properties\", key],\n }));\n }\n // required keys\n const requiredKeys = [];\n for (const key of Object.keys(shape)) {\n const field = def.shape[key];\n if (ctx.io === \"input\" ? inputOptin(field) === undefined : field._zod.optout === undefined) {\n requiredKeys.push(key);\n }\n }\n if (requiredKeys.length > 0) {\n json.required = requiredKeys;\n }\n // catchall\n if (def.catchall?._zod.def.type === \"never\") {\n // strict\n json.additionalProperties = false;\n }\n else if (!def.catchall) {\n // regular\n if (ctx.io === \"output\")\n json.additionalProperties = false;\n }\n else if (def.catchall) {\n json.additionalProperties = processSchema(def.catchall, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n};\nexport const unionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches). This includes both z.xor() and discriminated unions\n const isExclusive = def.inclusive === false;\n const options = def.options.map((x, i) => processSchema(x, ctx, {\n ...params,\n path: [...params.path, isExclusive ? \"oneOf\" : \"anyOf\", i],\n }));\n if (isExclusive) {\n json.oneOf = options;\n }\n else {\n json.anyOf = options;\n }\n};\nexport const intersectionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const a = processSchema(def.left, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 0],\n });\n const b = processSchema(def.right, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 1],\n });\n const isSimpleIntersection = (val) => \"allOf\" in val && Object.keys(val).length === 1;\n const allOf = [\n ...(isSimpleIntersection(a) ? a.allOf : [a]),\n ...(isSimpleIntersection(b) ? b.allOf : [b]),\n ];\n json.allOf = allOf;\n // Recorded innermost first, so a nested intersection has already folded by the time this one is considered. The array is the handle rather than the schema, because a wrapper that inherits this schema shares the same array; `finalize` folds every object holding it. See `foldIntersection`.\n ctx.intersections.push(allOf);\n};\nexport const tupleProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"array\";\n const prefixPath = ctx.target === \"draft-2020-12\" ? \"prefixItems\" : \"items\";\n const restPath = ctx.target === \"draft-2020-12\" ? \"items\" : ctx.target === \"openapi-3.0\" ? \"items\" : \"additionalItems\";\n const prefixItems = def.items.map((x, i) => processSchema(x, ctx, {\n ...params,\n path: [...params.path, prefixPath, i],\n }));\n const rest = def.rest\n ? processSchema(def.rest, ctx, {\n ...params,\n path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n })\n : null;\n let minItems = def.items.length;\n while (minItems > 0) {\n const item = def.items[minItems - 1];\n const optional = ctx.io === \"input\" ? inputOptin(item) !== undefined : item._zod.optout === \"optional\";\n if (!optional)\n break;\n minItems--;\n }\n const maxItems = def.items.length;\n const isClosed = !def.rest;\n if (ctx.target === \"draft-2020-12\") {\n json.prefixItems = prefixItems;\n if (isClosed) {\n json.items = false;\n }\n else if (rest) {\n json.items = rest;\n }\n if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\n }\n else if (ctx.target === \"openapi-3.0\") {\n json.items = {\n anyOf: prefixItems,\n };\n if (rest) {\n json.items.anyOf.push(rest);\n }\n if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\n }\n else {\n json.items = prefixItems;\n if (isClosed) {\n json.additionalItems = false;\n }\n else if (rest) {\n json.additionalItems = rest;\n }\n if (minItems > 0)\n json.minItems = minItems;\n if (isClosed)\n json.maxItems = maxItems;\n }\n // explicit user-defined length checks take precedence\n const { minimum, maximum } = aggregateChecks(schema);\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n};\n/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the\n * numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key\n * behind a wrapper only carries its own `type` before then, and a union key only has its branches.\n *\n * A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather\n * than carried over: keeping them beside `type: \"string\"` reproduces the match-nothing schema this\n * exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)`\n * accepts `\"3\"` — which is the deliberate trade, since throwing on it would reject an ordinary schema\n * outright. */\nfunction stringifyKeyNames(bySchema, json, visited) {\n // an extracted key that rewrites cannot go on sharing its definition — the string form a key position needs is not the number form every other reference wants — so it inlines. One that does not rewrite keeps the `$ref`.\n if (json.$ref) {\n // a recursive key holds its own reference inside its definition, so a node already on the path is left alone rather than resolved again\n if (visited.has(json))\n return json;\n visited.add(json);\n const def = bySchema.get(json)?.def;\n if (!def)\n return json;\n const inlined = stringifyKeyNames(bySchema, def, visited);\n return inlined === def ? json : inlined;\n }\n for (const keyword of [\"anyOf\", \"oneOf\"]) {\n const branches = json[keyword];\n if (!Array.isArray(branches))\n continue;\n const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited));\n // rebuilding regardless would detach a key that had nothing to re-express, dropping its `$ref` and leaking the internal `id`\n if (mapped.some((branch, i) => branch !== branches[i]))\n json = { ...json, [keyword]: mapped };\n }\n // a member that already admits a string leaves the key unconstrained, so the node's own type re-expresses only when every member is numeric\n const types = Array.isArray(json.type) ? json.type : [json.type];\n const numericType = !types.includes(\"string\") && types.some((t) => t === \"number\" || t === \"integer\");\n // a heterogeneous key carries no type at all, so its numeric members are caught here instead\n const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined);\n if (!numericType && !values?.some((v) => typeof v === \"number\"))\n return json;\n const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json;\n if (rest.enum)\n rest.enum = rest.enum.map((v) => (typeof v === \"number\" ? String(v) : v));\n else if (typeof rest.const === \"number\")\n rest.const = String(rest.const);\n // a heterogeneous key keeps its absent type: the stringified members already say what a key may be\n if (!numericType)\n return rest;\n rest.type = \"string\";\n if (!values)\n rest.pattern = (types.includes(\"number\") ? regexes.number : regexes.integer).source;\n return rest;\n}\n/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */\nconst pendingRecords = new WeakMap();\nfunction rewriteKeyNames(ctx) {\n // an extracted key is resolved by the object `extractToDef` left in its place, so the map is built once rather than searched per reference. `_zod.toJSONSchema` can hand the same object to two schemas, so the first entry carrying a body wins, as a search would have found it.\n const bySchema = new Map();\n for (const entry of ctx.seen.values()) {\n if (entry.def && !bySchema.has(entry.schema))\n bySchema.set(entry.schema, entry);\n }\n const rewrites = new Map();\n for (const record of pendingRecords.get(ctx) ?? []) {\n const seen = ctx.seen.get(record);\n const names = (seen?.def ?? seen?.schema)?.propertyNames;\n if (!names || names === true || rewrites.has(names))\n continue;\n const rewritten = stringifyKeyNames(bySchema, names, new Set());\n if (rewritten !== names)\n rewrites.set(names, rewritten);\n }\n if (!rewrites.size)\n return;\n // the flatten has already copied each record's own properties onto every wrapper by reference, and an extracted body is another such copy, so every carrier holding a rewritten key is updated together\n for (const entry of ctx.seen.values()) {\n for (const carrier of [entry.schema, entry.def]) {\n const rewritten = carrier && rewrites.get(carrier.propertyNames);\n if (rewritten)\n carrier.propertyNames = rewritten;\n }\n }\n}\nexport const recordProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n // For looseRecord with regex patterns, use patternProperties. This correctly represents \"only validate keys matching the pattern\" semantics and composes well with allOf (intersections)\n const keyType = def.keyType;\n const patterns = aggregateChecks(keyType).patterns;\n if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n // Use patternProperties for looseRecord with regex patterns\n const valueSchema = processSchema(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"patternProperties\", \"*\"],\n });\n json.patternProperties = {};\n for (const pattern of patterns) {\n assignProp(json.patternProperties, exactPattern(pattern).source, valueSchema);\n }\n }\n else {\n // Default behavior: use propertyNames + additionalProperties\n if (ctx.target === \"draft-07\" || ctx.target === \"draft-2020-12\") {\n json.propertyNames = processSchema(def.keyType, ctx, {\n ...params,\n path: [...params.path, \"propertyNames\"],\n });\n let pending = pendingRecords.get(ctx);\n if (!pending) {\n pending = [];\n pendingRecords.set(ctx, pending);\n ctx.deferred.push(() => rewriteKeyNames(ctx));\n }\n pending.push(schema);\n }\n json.additionalProperties = processSchema(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n // Add required for keys with discrete values (enum, literal, etc.)\n const keyValues = keyType._zod.values;\n // Every key shares one value schema, so an optional-in value makes the whole key set omittable on input. Output keeps them: the exhaustive branch assigns every key, even one whose value came back undefined.\n const omittableOnInput = ctx.io === \"input\" && inputOptin(def.valueType) !== undefined;\n if (keyValues && !def.partial && !omittableOnInput) {\n const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n if (validKeyValues.length > 0) {\n json.required = validKeyValues.map(String);\n }\n }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const inner = processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n if (ctx.target === \"openapi-3.0\") {\n seen.ref = def.innerType;\n json.nullable = true;\n }\n else {\n json.anyOf = [inner, { type: \"null\" }];\n }\n};\nexport const nonoptionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\n/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON.\n * A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other\n * unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */\nconst UNREPRESENTABLE_DEFAULT = Symbol();\nfunction serializeDefaultValue(value, schema, ctx, json, params) {\n let unrepresentable = false;\n const serialized = JSON.stringify(value, (_, val) => {\n if (typeof val !== \"bigint\")\n return val;\n unrepresentable = true;\n return null;\n });\n if (!unrepresentable)\n return JSON.parse(serialized);\n handleUnrepresentable(schema, ctx, json, params, \"BigInt defaults cannot be represented in JSON Schema\");\n return UNREPRESENTABLE_DEFAULT;\n}\nexport const defaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);\n if (value !== UNREPRESENTABLE_DEFAULT)\n json.default = value;\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n if (ctx.io !== \"input\")\n return;\n const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);\n if (value !== UNREPRESENTABLE_DEFAULT)\n json._prefault = value;\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n let catchValue;\n try {\n catchValue = def.catchValue(undefined);\n }\n catch {\n handleUnrepresentable(schema, ctx, json, params, \"Dynamic catch values are not supported in JSON Schema\");\n return;\n }\n json.default = catchValue;\n};\nexport const pipeProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n const inIsTransform = def.in._zod.traits.has(\"$ZodTransform\");\n const innerType = ctx.io === \"input\" ? (inIsTransform ? def.out : def.in) : def.out;\n processSchema(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\nexport const readonlyProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.readOnly = true;\n};\nexport const promiseProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const optionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n processSchema(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const lazyProcessor = (schema, ctx, _json, params) => {\n const innerType = schema._zod.innerType;\n processSchema(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\n// ==================== ALL PROCESSORS ====================\nexport const allProcessors = {\n string: stringProcessor,\n number: numberProcessor,\n boolean: booleanProcessor,\n bigint: bigintProcessor,\n symbol: symbolProcessor,\n null: nullProcessor,\n undefined: undefinedProcessor,\n void: voidProcessor,\n never: neverProcessor,\n any: anyProcessor,\n unknown: unknownProcessor,\n date: dateProcessor,\n enum: enumProcessor,\n literal: literalProcessor,\n nan: nanProcessor,\n template_literal: templateLiteralProcessor,\n file: fileProcessor,\n success: successProcessor,\n custom: customProcessor,\n function: functionProcessor,\n transform: transformProcessor,\n map: mapProcessor,\n set: setProcessor,\n array: arrayProcessor,\n object: objectProcessor,\n union: unionProcessor,\n intersection: intersectionProcessor,\n tuple: tupleProcessor,\n record: recordProcessor,\n nullable: nullableProcessor,\n nonoptional: nonoptionalProcessor,\n default: defaultProcessor,\n prefault: prefaultProcessor,\n catch: catchProcessor,\n pipe: pipeProcessor,\n readonly: readonlyProcessor,\n promise: promiseProcessor,\n optional: optionalProcessor,\n lazy: lazyProcessor,\n};\nexport function toJSONSchema(input, params) {\n if (\"_idmap\" in input) {\n // Registry case\n const registry = input;\n const ctx = initializeContext({ ...params, processors: allProcessors });\n const defs = {};\n // First pass: process all schemas to build the seen map\n for (const entry of registry._idmap.entries()) {\n const [_, schema] = entry;\n processSchema(schema, ctx);\n }\n const schemas = {};\n const external = {\n registry,\n uri: params?.uri,\n defs,\n };\n // Update the context with external configuration\n ctx.external = external;\n // Second pass: emit each schema\n for (const entry of registry._idmap.entries()) {\n const [key, schema] = entry;\n extractDefs(ctx, schema);\n assignProp(schemas, key, finalize(ctx, schema));\n }\n if (Object.keys(defs).length > 0) {\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n schemas.__shared = {\n [defsSegment]: defs,\n };\n }\n return { schemas };\n }\n // Single schema case\n const ctx = initializeContext({ ...params, processors: allProcessors });\n processSchema(input, ctx);\n extractDefs(ctx, input);\n return finalize(ctx, input);\n}\n","import * as util from \"../core/util.js\";\nconst error = () => {\n const Sizable = {\n string: { unit: \"characters\", verb: \"to have\" },\n file: { unit: \"bytes\", verb: \"to have\" },\n array: { unit: \"items\", verb: \"to have\" },\n set: { unit: \"items\", verb: \"to have\" },\n map: { unit: \"entries\", verb: \"to have\" },\n };\n function getSizing(origin) {\n return Sizable[origin] ?? null;\n }\n const FormatDictionary = {\n regex: \"input\",\n email: \"email address\",\n url: \"URL\",\n emoji: \"emoji\",\n uuid: \"UUID\",\n uuidv4: \"UUIDv4\",\n uuidv6: \"UUIDv6\",\n nanoid: \"nanoid\",\n guid: \"GUID\",\n cuid: \"cuid\",\n cuid2: \"cuid2\",\n ulid: \"ULID\",\n xid: \"XID\",\n ksuid: \"KSUID\",\n datetime: \"ISO datetime\",\n date: \"ISO date\",\n time: \"ISO time\",\n duration: \"ISO duration\",\n ipv4: \"IPv4 address\",\n ipv6: \"IPv6 address\",\n mac: \"MAC address\",\n cidrv4: \"IPv4 range\",\n cidrv6: \"IPv6 range\",\n base64: \"base64-encoded string\",\n base64url: \"base64url-encoded string\",\n json_string: \"JSON string\",\n e164: \"E.164 number\",\n currency_code: \"currency code\",\n credit_card: \"credit card number\",\n iban: \"IBAN\",\n jwt: \"JWT\",\n template_literal: \"input\",\n };\n // type names: missing keys = do not translate (use raw value via ?? fallback)\n const TypeDictionary = {\n // Compatibility: \"nan\" -> \"NaN\" for display\n nan: \"NaN\",\n // All other type names omitted - they fall back to raw values via ?? operator\n };\n function getTypeName(type, input) {\n if (type === \"number\" && typeof input === \"number\" && !Number.isFinite(input)) {\n return String(input);\n }\n return TypeDictionary[type] ?? type;\n }\n return (issue) => {\n switch (issue.code) {\n case \"invalid_type\": {\n const expected = getTypeName(issue.expected);\n const receivedType = util.parsedType(issue.input);\n const received = getTypeName(receivedType, issue.input);\n return `Invalid input: expected ${expected}, received ${received}`;\n }\n case \"invalid_value\":\n if (issue.values.length === 1)\n return `Invalid input: expected ${util.stringifyPrimitive(issue.values[0])}`;\n return `Invalid option: expected one of ${util.joinValues(issue.values, \"|\")}`;\n case \"too_big\": {\n const adj = issue.exact ? \"exactly \" : issue.inclusive ? \"<=\" : \"<\";\n const sizing = getSizing(issue.origin);\n if (sizing)\n return `Too big: expected ${issue.origin ?? \"value\"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? \"elements\"}`;\n return `Too big: expected ${issue.origin ?? \"value\"} to be ${adj}${issue.maximum.toString()}`;\n }\n case \"too_small\": {\n const adj = issue.exact ? \"exactly \" : issue.inclusive ? \">=\" : \">\";\n const sizing = getSizing(issue.origin);\n if (sizing) {\n return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;\n }\n return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`;\n }\n case \"invalid_format\": {\n const _issue = issue;\n if (_issue.format === \"starts_with\") {\n return `Invalid string: must start with \"${_issue.prefix}\"`;\n }\n if (_issue.format === \"ends_with\")\n return `Invalid string: must end with \"${_issue.suffix}\"`;\n if (_issue.format === \"includes\")\n return `Invalid string: must include \"${_issue.includes}\"`;\n if (_issue.format === \"regex\")\n return `Invalid string: must match pattern ${_issue.pattern}`;\n return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;\n }\n case \"not_multiple_of\":\n return `Invalid number: must be a multiple of ${issue.divisor}`;\n case \"unrecognized_keys\":\n return `Unrecognized key${issue.keys.length > 1 ? \"s\" : \"\"}: ${util.joinValues(issue.keys, \", \")}`;\n case \"invalid_key\":\n return `Invalid key in ${issue.origin}`;\n case \"invalid_union\":\n if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) {\n const opts = issue.options.map((o) => `'${o}'`).join(\" | \");\n return `Invalid discriminator value. Expected ${opts}`;\n }\n if (issue.inclusive === false) {\n return \"Invalid input: more than one option matched\";\n }\n return \"Invalid input\";\n case \"invalid_element\":\n return `Invalid value in ${issue.origin}`;\n default:\n return `Invalid input`;\n }\n };\n};\nexport default function () {\n return {\n localeError: error(),\n };\n}\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\n/* Prototypes that already carry the lazy helper methods. Seeded with the\n * intrinsics so that `init` on a foreign object — it accepts any object —\n * can never install an accessor onto a prototype we do not own. */\nconst _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);\n/* Helper methods live as non-enumerable lazy getters on the shared\n * prototype instead of own properties on every instance. On first\n * access the getter allocates the per-instance closure and caches it\n * as a non-enumerable own property, so detached usage still works and\n * the allocation only happens for methods actually touched. */\nfunction _lazyMethod(proto, key, make) {\n Object.defineProperty(proto, key, {\n configurable: true,\n enumerable: false,\n get() {\n const value = make(this);\n Object.defineProperty(this, key, { value, configurable: true, writable: true });\n return value;\n },\n set(value) {\n Object.defineProperty(this, key, { value, configurable: true, writable: true });\n },\n });\n}\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n const proto = Object.getPrototypeOf(inst);\n if (_installedErrorProtos.has(proto))\n return;\n _installedErrorProtos.add(proto);\n _lazyMethod(proto, \"format\", (self) => (mapper) => core.formatError(self, mapper));\n _lazyMethod(proto, \"flatten\", (self) => (mapper) => core.flattenError(self, mapper));\n _lazyMethod(proto, \"addIssue\", (self) => (issue) => {\n self.issues.push(issue);\n self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);\n });\n _lazyMethod(proto, \"addIssues\", (self) => (issues) => {\n self.issues.push(...issues);\n self.message = JSON.stringify(self.issues, util.jsonStringifyReplacer, 2);\n });\n Object.defineProperty(proto, \"isEmpty\", {\n configurable: true,\n enumerable: false,\n get() {\n return this.issues.length === 0;\n },\n });\n};\nexport const ZodError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer, undefined, {\n Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n","import * as core from \"../core/index.js\";\nimport { ZodRealError } from \"./errors.js\";\nexport const parse = /* @__PURE__ */ core._parse(ZodRealError);\nexport const parseAsync = /* @__PURE__ */ core._parseAsync(ZodRealError);\nexport const safeParse = /* @__PURE__ */ core._safeParse(ZodRealError);\nexport const safeParseAsync = /* @__PURE__ */ core._safeParseAsync(ZodRealError);\nexport { validate, validateAsync } from \"../core/index.js\";\n// Codec functions\nexport const encode = /* @__PURE__ */ core._encode(ZodRealError);\nexport const decode = /* @__PURE__ */ core._decode(ZodRealError);\nexport const encodeAsync = /* @__PURE__ */ core._encodeAsync(ZodRealError);\nexport const decodeAsync = /* @__PURE__ */ core._decodeAsync(ZodRealError);\nexport const safeEncode = /* @__PURE__ */ core._safeEncode(ZodRealError);\nexport const safeDecode = /* @__PURE__ */ core._safeDecode(ZodRealError);\nexport const safeEncodeAsync = /* @__PURE__ */ core._safeEncodeAsync(ZodRealError);\nexport const safeDecodeAsync = /* @__PURE__ */ core._safeDecodeAsync(ZodRealError);\n","import * as core from \"../core/index.js\";\nimport { util } from \"../core/index.js\";\nimport * as processors from \"../core/json-schema-processors.js\";\nimport * as regexes from \"../core/regexes.js\";\nimport { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport en from \"../locales/en.js\";\nimport * as checks from \"./checks.js\";\nimport * as parse from \"./parse.js\";\n// Register English as the default locale on first ZodType construction. Hooked into the `ZodType` `$constructor` (rather than a top-level `config(en())` in `external.ts`) so bundlers honoring `sideEffects: false` can't tree-shake it out — see #5953, #5725. An explicit `z.config(z.locales.xx())` call wins regardless of order, since this only sets the default when none is present.\nfunction _ensureDefaultLocale() {\n if (!core.globalConfig.localeError)\n core.config(en());\n}\n// the default memoizer is read by the core container init, which runs before `ZodType.init`, so each container calls this first\nfunction _ensureDefaultMemoizer() {\n if (!core.globalConfig.memoizer)\n core.config({ memoizer: core.memoizer() });\n}\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n _ensureDefaultLocale();\n core.$ZodType.init(inst, def);\n inst.def = def;\n inst.type = def.type;\n return inst;\n}, {\n check(...chks) {\n const def = this.def;\n return this.clone(util.mergeDefs(def, {\n checks: [\n ...(def.checks ?? []),\n ...chks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }), { parent: true });\n },\n with(...chks) {\n return this.check(...chks);\n },\n clone(def, params) {\n return core.clone(this, def, params);\n },\n brand() {\n return this;\n },\n register(reg, meta) {\n reg.add(this, meta);\n return this;\n },\n refine(check, params) {\n return this.check(refine(check, params));\n },\n superRefine(refinement, params) {\n return this.check(superRefine(refinement, params));\n },\n overwrite(fn) {\n return this.check(checks.overwrite(fn));\n },\n optional() {\n return optional(this);\n },\n exactOptional() {\n return exactOptional(this);\n },\n nullable() {\n return nullable(this);\n },\n nullish() {\n return optional(nullable(this));\n },\n nonoptional(params) {\n return nonoptional(this, params);\n },\n array() {\n return array(this);\n },\n or(arg) {\n return union([this, arg]);\n },\n and(arg) {\n return intersection(this, arg);\n },\n transform(tx) {\n return pipe(this, transform(tx));\n },\n default(d) {\n return _default(this, d);\n },\n prefault(d) {\n return prefault(this, d);\n },\n catch(params) {\n return _catch(this, params);\n },\n pipe(target) {\n return pipe(this, target);\n },\n readonly() {\n return readonly(this);\n },\n describe(description) {\n const cl = this.clone();\n core.globalRegistry.add(cl, { description });\n return cl;\n },\n meta(...args) {\n // overloaded: meta() returns the registered metadata, meta(data) returns a clone with `data` registered. The mapped type picks up the second overload, so we accept variadic any-args and return `any` to satisfy both at runtime.\n if (args.length === 0)\n return core.globalRegistry.get(this);\n const cl = this.clone();\n core.globalRegistry.add(cl, args[0]);\n return cl;\n },\n isOptional() {\n return this.safeParse(undefined).success;\n },\n isNullable() {\n return this.safeParse(null).success;\n },\n apply(fn, ...args) {\n return args.length === 0 ? fn(this) : fn(this, ...args);\n },\n // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode.\n get \"~standard\"() {\n return util.hide(this, \"~standard\", {\n ...core.standardProps(this),\n jsonSchema: {\n input: createStandardJSONSchemaMethod(this, \"input\"),\n output: createStandardJSONSchemaMethod(this, \"output\"),\n },\n });\n },\n set \"~standard\"(value) {\n util.own(this, \"~standard\", value);\n },\n parse: function _parse(data, params) {\n return parse.parse(this, data, params, { callee: _parse });\n },\n parseAsync: async function _parseAsync(data, params) {\n return await parse.parseAsync(this, data, params, { callee: _parseAsync });\n },\n safeParse(data, params) {\n return parse.safeParse(this, data, params);\n },\n async safeParseAsync(data, params) {\n return parse.safeParseAsync(this, data, params);\n },\n // `spa` is an alias: same function object as `safeParseAsync`, as before.\n get spa() {\n return this?.safeParseAsync;\n },\n set spa(value) {\n util.own(this, \"spa\", value);\n },\n validate(data, params) {\n return parse.validate(this, data, params);\n },\n validateAsync(data, params) {\n return parse.validateAsync(this, data, params);\n },\n encode: function _encode(data, params) {\n return parse.encode(this, data, params, { callee: _encode });\n },\n decode: function _decode(data, params) {\n return parse.decode(this, data, params, { callee: _decode });\n },\n encodeAsync: async function _encodeAsync(data, params) {\n return await parse.encodeAsync(this, data, params, { callee: _encodeAsync });\n },\n decodeAsync: async function _decodeAsync(data, params) {\n return await parse.decodeAsync(this, data, params, { callee: _decodeAsync });\n },\n safeEncode(data, params) {\n return parse.safeEncode(this, data, params);\n },\n safeDecode(data, params) {\n return parse.safeDecode(this, data, params);\n },\n async safeEncodeAsync(data, params) {\n return parse.safeEncodeAsync(this, data, params);\n },\n async safeDecodeAsync(data, params) {\n return parse.safeDecodeAsync(this, data, params);\n },\n toJSONSchema(params) {\n return createToJSONSchemaMethod(this, {})(params);\n },\n // Reads through to the registry on every access, so it must not cache.\n get description() {\n return core.globalRegistry.get(this)?.description;\n },\n // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property.\n get _def() {\n return this._zod.def;\n },\n});\n/** @internal */\nexport const _ZodString = /*@__PURE__*/ core.$constructor(\"_ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.stringProcessor(inst, ctx, json, params);\n}, \n/*@__PURE__*/ util.derived({\n format: (inst) => processors.aggregateChecks(inst).format ?? null,\n minLength: (inst) => processors.aggregateChecks(inst).minimum ?? null,\n maxLength: (inst) => processors.aggregateChecks(inst).maximum ?? null,\n}, {\n regex(...args) {\n return this.check(checks.regex(...args));\n },\n includes(...args) {\n return this.check(checks.includes(...args));\n },\n startsWith(...args) {\n return this.check(checks.startsWith(...args));\n },\n endsWith(...args) {\n return this.check(checks.endsWith(...args));\n },\n min(...args) {\n return this.check(checks.minLength(...args));\n },\n max(...args) {\n return this.check(checks.maxLength(...args));\n },\n length(...args) {\n return this.check(checks.length(...args));\n },\n nonempty(...args) {\n return this.check(checks.minLength(1, ...args));\n },\n lowercase(params) {\n return this.check(checks.lowercase(params));\n },\n uppercase(params) {\n return this.check(checks.uppercase(params));\n },\n trim() {\n return this.check(checks.trim());\n },\n normalize(...args) {\n return this.check(checks.normalize(...args));\n },\n toLowerCase() {\n return this.check(checks.toLowerCase());\n },\n toUpperCase() {\n return this.check(checks.toUpperCase());\n },\n slugify() {\n return this.check(checks.slugify());\n },\n}));\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n _ZodString.init(inst, def);\n}, {\n email(params) {\n return this.check(core._email(ZodEmail, params));\n },\n url(params) {\n return this.check(core._url(ZodURL, params));\n },\n jwt(params) {\n return this.check(core._jwt(ZodJWT, params));\n },\n emoji(params) {\n return this.check(core._emoji(ZodEmoji, params));\n },\n guid(params) {\n return this.check(core._guid(ZodGUID, params));\n },\n uuid(params) {\n return this.check(core._uuid(ZodUUID, params));\n },\n uuidv4(params) {\n return this.check(core._uuidv4(ZodUUID, params));\n },\n uuidv6(params) {\n return this.check(core._uuidv6(ZodUUID, params));\n },\n uuidv7(params) {\n return this.check(core._uuidv7(ZodUUID, params));\n },\n nanoid(params) {\n return this.check(core._nanoid(ZodNanoID, params));\n },\n cuid(params) {\n return this.check(core._cuid(ZodCUID, params));\n },\n cuid2(params) {\n return this.check(core._cuid2(ZodCUID2, params));\n },\n ulid(params) {\n return this.check(core._ulid(ZodULID, params));\n },\n base64(params) {\n return this.check(core._base64(ZodBase64, params));\n },\n base64url(params) {\n return this.check(core._base64url(ZodBase64URL, params));\n },\n xid(params) {\n return this.check(core._xid(ZodXID, params));\n },\n ksuid(params) {\n return this.check(core._ksuid(ZodKSUID, params));\n },\n ipv4(params) {\n return this.check(core._ipv4(ZodIPv4, params));\n },\n ipv6(params) {\n return this.check(core._ipv6(ZodIPv6, params));\n },\n cidrv4(params) {\n return this.check(core._cidrv4(ZodCIDRv4, params));\n },\n cidrv6(params) {\n return this.check(core._cidrv6(ZodCIDRv6, params));\n },\n e164(params) {\n return this.check(core._e164(ZodE164, params));\n },\n datetime(params) {\n return this.check(core._isoDateTime(ZodISODateTime, params));\n },\n date(params) {\n return this.check(core._isoDate(ZodISODate, params));\n },\n time(params) {\n return this.check(core._isoTime(ZodISOTime, params));\n },\n duration(params) {\n return this.check(core._isoDuration(ZodISODuration, params));\n },\n});\nexport function string(params) {\n return core._string(ZodString, params);\n}\nexport const ZodStringFormat = /*@__PURE__*/ core.$constructor(\"ZodStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n _ZodString.init(inst, def);\n});\nexport const ZodISODateTime = /*@__PURE__*/ core.$constructor(\"ZodISODateTime\", (inst, def) => {\n core.$ZodISODateTime.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISODate = /*@__PURE__*/ core.$constructor(\"ZodISODate\", (inst, def) => {\n core.$ZodISODate.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISOTime = /*@__PURE__*/ core.$constructor(\"ZodISOTime\", (inst, def) => {\n core.$ZodISOTime.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodISODuration = /*@__PURE__*/ core.$constructor(\"ZodISODuration\", (inst, def) => {\n core.$ZodISODuration.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport const ZodEmail = /*@__PURE__*/ core.$constructor(\"ZodEmail\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmail.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function email(params) {\n return core._email(ZodEmail, params);\n}\nexport const ZodGUID = /*@__PURE__*/ core.$constructor(\"ZodGUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodGUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function guid(params) {\n return core._guid(ZodGUID, params);\n}\nexport const ZodUUID = /*@__PURE__*/ core.$constructor(\"ZodUUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodUUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function uuid(params) {\n return core._uuid(ZodUUID, params);\n}\nexport function uuidv4(params) {\n return core._uuidv4(ZodUUID, params);\n}\n// ZodUUIDv6\nexport function uuidv6(params) {\n return core._uuidv6(ZodUUID, params);\n}\n// ZodUUIDv7\nexport function uuidv7(params) {\n return core._uuidv7(ZodUUID, params);\n}\nexport const ZodURL = /*@__PURE__*/ core.$constructor(\"ZodURL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodURL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function url(params) {\n return core._url(ZodURL, params);\n}\nexport function httpUrl(params) {\n return core._url(ZodURL, {\n protocol: regexes.httpProtocol,\n hostname: regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEmoji = /*@__PURE__*/ core.$constructor(\"ZodEmoji\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmoji.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function emoji(params) {\n return core._emoji(ZodEmoji, params);\n}\nexport const ZodNanoID = /*@__PURE__*/ core.$constructor(\"ZodNanoID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodNanoID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function nanoid(params) {\n return core._nanoid(ZodNanoID, params);\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const ZodCUID = /*@__PURE__*/ core.$constructor(\"ZodCUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\n/**\n * Validates a CUID v1 string.\n *\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport function cuid(params) {\n return core._cuid(ZodCUID, params);\n}\nexport const ZodCUID2 = /*@__PURE__*/ core.$constructor(\"ZodCUID2\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID2.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid2(params) {\n return core._cuid2(ZodCUID2, params);\n}\nexport const ZodULID = /*@__PURE__*/ core.$constructor(\"ZodULID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodULID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ulid(params) {\n return core._ulid(ZodULID, params);\n}\nexport const ZodXID = /*@__PURE__*/ core.$constructor(\"ZodXID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodXID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function xid(params) {\n return core._xid(ZodXID, params);\n}\nexport const ZodKSUID = /*@__PURE__*/ core.$constructor(\"ZodKSUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodKSUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ksuid(params) {\n return core._ksuid(ZodKSUID, params);\n}\nexport const ZodIPv4 = /*@__PURE__*/ core.$constructor(\"ZodIPv4\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv4(params) {\n return core._ipv4(ZodIPv4, params);\n}\nexport const ZodMAC = /*@__PURE__*/ core.$constructor(\"ZodMAC\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodMAC.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function mac(params) {\n return core._mac(ZodMAC, params);\n}\nexport const ZodIPv6 = /*@__PURE__*/ core.$constructor(\"ZodIPv6\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv6(params) {\n return core._ipv6(ZodIPv6, params);\n}\nexport const ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv4(params) {\n return core._cidrv4(ZodCIDRv4, params);\n}\nexport const ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv6(params) {\n return core._cidrv6(ZodCIDRv6, params);\n}\nexport const ZodBase64 = /*@__PURE__*/ core.$constructor(\"ZodBase64\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64(params) {\n return core._base64(ZodBase64, params);\n}\nexport const ZodBase64URL = /*@__PURE__*/ core.$constructor(\"ZodBase64URL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64URL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64url(params) {\n return core._base64url(ZodBase64URL, params);\n}\nexport const ZodE164 = /*@__PURE__*/ core.$constructor(\"ZodE164\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodE164.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function e164(params) {\n return core._e164(ZodE164, params);\n}\nexport const ZodCreditCard = /*@__PURE__*/ core.$constructor(\"ZodCreditCard\", (inst, def) => {\n core.$ZodCreditCard.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function creditCard(params) {\n return core._creditCard(ZodCreditCard, params);\n}\nexport const ZodIBAN = /*@__PURE__*/ core.$constructor(\"ZodIBAN\", (inst, def) => {\n core.$ZodIBAN.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function iban(params) {\n return core._iban(ZodIBAN, params);\n}\nexport const ZodJWT = /*@__PURE__*/ core.$constructor(\"ZodJWT\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodJWT.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function jwt(params) {\n return core._jwt(ZodJWT, params);\n}\nexport const ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodCustomStringFormat\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCustomStringFormat.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);\n}\nexport function hostname(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hostname\", regexes.hostname, _params);\n}\nexport function hex(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hex\", regexes.hex, _params);\n}\nexport function currencyCode(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"currency_code\", regexes.currencyCode, _params);\n}\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodCustomStringFormat, format, regex, params);\n}\nexport const ZodNumber = /*@__PURE__*/ core.$constructor(\"ZodNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.numberProcessor(inst, ctx, json, params);\n inst.isFinite = true;\n}, \n/*@__PURE__*/ util.derived({\n minValue: (inst) => {\n const { minimum, exclusiveMinimum } = processors.aggregateChecks(inst);\n return Math.max(minimum ?? Number.NEGATIVE_INFINITY, exclusiveMinimum ?? Number.NEGATIVE_INFINITY);\n },\n maxValue: (inst) => {\n const { maximum, exclusiveMaximum } = processors.aggregateChecks(inst);\n return Math.min(maximum ?? Number.POSITIVE_INFINITY, exclusiveMaximum ?? Number.POSITIVE_INFINITY);\n },\n isInt: (inst) => {\n const { isInt, multipleOf } = processors.aggregateChecks(inst);\n return !!isInt || !!multipleOf?.some(Number.isSafeInteger);\n },\n format: (inst) => processors.aggregateChecks(inst).format ?? null,\n}, {\n gt(value, params) {\n return this.check(checks.gt(value, params));\n },\n gte(value, params) {\n return this.check(checks.gte(value, params));\n },\n min(value, params) {\n return this.check(checks.gte(value, params));\n },\n lt(value, params) {\n return this.check(checks.lt(value, params));\n },\n lte(value, params) {\n return this.check(checks.lte(value, params));\n },\n max(value, params) {\n return this.check(checks.lte(value, params));\n },\n int(params) {\n return this.check(int(params));\n },\n safe(params) {\n return this.check(int(params));\n },\n positive(params) {\n return this.check(checks.gt(0, params));\n },\n nonnegative(params) {\n return this.check(checks.gte(0, params));\n },\n negative(params) {\n return this.check(checks.lt(0, params));\n },\n nonpositive(params) {\n return this.check(checks.lte(0, params));\n },\n multipleOf(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n step(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n finite() {\n return this;\n },\n}));\nexport function number(params) {\n return core._number(ZodNumber, params);\n}\nexport const ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodNumber.init(inst, def);\n});\nexport function int(params) {\n return core._int(ZodNumberFormat, params);\n}\nexport function float32(params) {\n return core._float32(ZodNumberFormat, params);\n}\nexport function float64(params) {\n return core._float64(ZodNumberFormat, params);\n}\nexport function int32(params) {\n return core._int32(ZodNumberFormat, params);\n}\nexport function uint32(params) {\n return core._uint32(ZodNumberFormat, params);\n}\nexport const ZodBoolean = /*@__PURE__*/ core.$constructor(\"ZodBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.booleanProcessor(inst, ctx, json, params);\n});\nexport function boolean(params) {\n return core._boolean(ZodBoolean, params);\n}\nexport const ZodBigInt = /*@__PURE__*/ core.$constructor(\"ZodBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params);\n}, \n/*@__PURE__*/ util.derived({\n minValue: (inst) => processors.aggregateChecks(inst).minimum ?? null,\n maxValue: (inst) => processors.aggregateChecks(inst).maximum ?? null,\n format: (inst) => processors.aggregateChecks(inst).format ?? null,\n}, {\n gte(value, params) {\n return this.check(checks.gte(value, params));\n },\n min(value, params) {\n return this.check(checks.gte(value, params));\n },\n gt(value, params) {\n return this.check(checks.gt(value, params));\n },\n lt(value, params) {\n return this.check(checks.lt(value, params));\n },\n lte(value, params) {\n return this.check(checks.lte(value, params));\n },\n max(value, params) {\n return this.check(checks.lte(value, params));\n },\n positive(params) {\n return this.check(checks.gt(BigInt(0), params));\n },\n negative(params) {\n return this.check(checks.lt(BigInt(0), params));\n },\n nonpositive(params) {\n return this.check(checks.lte(BigInt(0), params));\n },\n nonnegative(params) {\n return this.check(checks.gte(BigInt(0), params));\n },\n multipleOf(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n}));\nexport function bigint(params) {\n return core._bigint(ZodBigInt, params);\n}\nexport const ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodBigInt.init(inst, def);\n});\nexport function int64(params) {\n return core._int64(ZodBigIntFormat, params);\n}\nexport function uint64(params) {\n return core._uint64(ZodBigIntFormat, params);\n}\nexport const ZodSymbol = /*@__PURE__*/ core.$constructor(\"ZodSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params);\n});\nexport function symbol(params) {\n return core._symbol(ZodSymbol, params);\n}\nexport const ZodUndefined = /*@__PURE__*/ core.$constructor(\"ZodUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params);\n});\nfunction _undefined(params) {\n return core._undefined(ZodUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodNull = /*@__PURE__*/ core.$constructor(\"ZodNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullProcessor(inst, ctx, json, params);\n});\nfunction _null(params) {\n return core._null(ZodNull, params);\n}\nexport { _null as null };\nexport const ZodAny = /*@__PURE__*/ core.$constructor(\"ZodAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.anyProcessor(inst, ctx, json, params);\n});\nexport function any() {\n return core._any(ZodAny);\n}\nexport const ZodUnknown = /*@__PURE__*/ core.$constructor(\"ZodUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unknownProcessor(inst, ctx, json, params);\n});\nexport function unknown() {\n return core._unknown(ZodUnknown);\n}\nexport const ZodNever = /*@__PURE__*/ core.$constructor(\"ZodNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.neverProcessor(inst, ctx, json, params);\n});\nexport function never(params) {\n return core._never(ZodNever, params);\n}\nexport const ZodVoid = /*@__PURE__*/ core.$constructor(\"ZodVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params);\n});\nfunction _void(params) {\n return core._void(ZodVoid, params);\n}\nexport { _void as void };\nexport const ZodDate = /*@__PURE__*/ core.$constructor(\"ZodDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params);\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n}, \n/*@__PURE__*/ util.derived({\n minDate: (inst) => {\n const { minimum } = processors.aggregateChecks(inst);\n return minimum ? new Date(minimum) : null;\n },\n maxDate: (inst) => {\n const { maximum } = processors.aggregateChecks(inst);\n return maximum ? new Date(maximum) : null;\n },\n}, {}));\nexport function date(params) {\n return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodArray.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.arrayProcessor(inst, ctx, json, params);\n inst.element = def.element;\n}, {\n min(n, params) {\n return this.check(checks.minLength(n, params));\n },\n nonempty(params) {\n return this.check(checks.minLength(1, params));\n },\n max(n, params) {\n return this.check(checks.maxLength(n, params));\n },\n length(n, params) {\n return this.check(checks.length(n, params));\n },\n unwrap() {\n return this.element;\n },\n});\nexport function array(element, params) {\n return core._array(ZodArray, element, params);\n}\n// .keyof\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodObject = /*@__PURE__*/ core.$constructor(\"ZodObject\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodObjectJIT.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.objectProcessor(inst, ctx, json, params);\n util.installLazyProp(inst, \"shape\", (self) => self._zod.def.shape, false);\n}, {\n keyof() {\n return _enum(Object.keys(this._zod.def.shape));\n },\n catchall(catchall) {\n // `mergeDefs` rather than a spread: spreading reads `shape`, and resolving it can mint a whole fresh subtree\n return this.clone(util.mergeDefs(this._zod.def, { catchall: catchall }));\n },\n passthrough() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: unknown() }));\n },\n loose() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: unknown() }));\n },\n strict() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: never() }));\n },\n strip() {\n return this.clone(util.mergeDefs(this._zod.def, { catchall: undefined }));\n },\n extend(incoming) {\n return util.extend(this, incoming);\n },\n safeExtend(incoming) {\n return util.safeExtend(this, incoming);\n },\n merge(other) {\n return util.merge(this, other);\n },\n pick(mask) {\n return util.pick(this, mask);\n },\n omit(mask) {\n return util.omit(this, mask);\n },\n partial(...args) {\n return util.partial(ZodOptional, this, args[0]);\n },\n exactPartial(...args) {\n return util.partial(ZodExactOptional, this, args[0], \"exactPartial\");\n },\n required(...args) {\n return util.required(ZodNonOptional, this, args[0]);\n },\n});\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodObject(def);\n}\n// strictObject\nexport function strictObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\nexport function looseObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\nexport const ZodUnion = /*@__PURE__*/ core.$constructor(\"ZodUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\nexport function union(options, params) {\n return new ZodUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodXor = /*@__PURE__*/ core.$constructor(\"ZodXor\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\n/** Creates an exclusive union (XOR) where exactly one option must match.\n * Unlike regular unions that succeed when any option matches, xor fails if\n * zero or more than one option matches the input. */\nexport function xor(options, params) {\n return new ZodXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodDiscriminatedUnion\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodDiscriminatedUnion.init(inst, def);\n});\nexport function discriminatedUnion(discriminator, options, params) {\n // const [options, params] = args;\n return new ZodDiscriminatedUnion({\n type: \"union\",\n options: options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodIntersection = /*@__PURE__*/ core.$constructor(\"ZodIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.intersectionProcessor(inst, ctx, json, params);\n});\nexport function intersection(left, right) {\n return new ZodIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodTuple = /*@__PURE__*/ core.$constructor(\"ZodTuple\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodTuple.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params);\n}, {\n rest(rest) {\n return this.clone({\n ...this._zod.def,\n rest: rest,\n });\n },\n partial() {\n const def = this._zod.def;\n // a refinement was authored against the full arity; partialing would run it on a shorter array\n if (def.checks?.length)\n throw new Error(\".partial() cannot be used on tuple schemas containing refinements\");\n return this.clone({\n ...def,\n items: def.items.map((item) => new ZodOptional({ type: \"optional\", innerType: item })),\n });\n },\n});\nexport function tuple(items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof core.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new ZodTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodRecord = /*@__PURE__*/ core.$constructor(\"ZodRecord\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodRecord.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.recordProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n});\nexport function record(keyType, valueType, params) {\n // v3-compat: z.record(valueType, params?) — defaults keyType to z.string()\n if (!valueType || !valueType._zod) {\n return new ZodRecord({\n type: \"record\",\n keyType: string(),\n valueType: keyType,\n ...util.normalizeParams(valueType),\n });\n }\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// type alksjf = core.output<core.$ZodRecordKey>;\nexport function partialRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n partial: true,\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMap = /*@__PURE__*/ core.$constructor(\"ZodMap\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodMap.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function map(keyType, valueType, params) {\n return new ZodMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSet = /*@__PURE__*/ core.$constructor(\"ZodSet\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodSet.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params);\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function set(valueType, params) {\n return new ZodSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEnum = /*@__PURE__*/ core.$constructor(\"ZodEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.enumProcessor(inst, ctx, json, params);\n inst.enum = def.entries;\n // reuse the parsed value set so a numeric TS enum's reverse-mapping keys stay out\n inst.options = [...inst._zod.values];\n const keys = new Set(Object.keys(def.entries));\n inst.extract = (values, params) => {\n const newEntries = {};\n for (const value of values) {\n if (keys.has(value)) {\n newEntries[value] = def.entries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n inst.exclude = (values, params) => {\n const newEntries = { ...def.entries };\n for (const value of values) {\n if (keys.has(value)) {\n delete newEntries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n});\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLiteral = /*@__PURE__*/ core.$constructor(\"ZodLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.literalProcessor(inst, ctx, json, params);\n inst.values = new Set(def.values);\n Object.defineProperty(inst, \"value\", {\n get() {\n if (def.values.length > 1) {\n throw new Error(\"This schema contains multiple valid literal values. Use `.values` instead.\");\n }\n return def.values[0];\n },\n });\n});\nexport function literal(value, params) {\n return new ZodLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodFile = /*@__PURE__*/ core.$constructor(\"ZodFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params);\n inst.min = (size, params) => inst.check(core._minSize(size, params));\n inst.max = (size, params) => inst.check(core._maxSize(size, params));\n inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params));\n});\nexport function file(params) {\n return core._file(ZodFile, params);\n}\nexport const ZodTransform = /*@__PURE__*/ core.$constructor(\"ZodTransform\", (inst, def) => {\n _ensureDefaultMemoizer();\n core.$ZodTransform.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.transformProcessor(inst, ctx, json, params);\n inst._zod.parse = (payload, _ctx) => {\n if (_ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n if (!(\"input\" in _issue))\n _issue.input = payload.value;\n _issue.inst ?? (_issue.inst = inst);\n // _issue.continue ??= true;\n payload.issues.push(util.issue(_issue));\n }\n };\n const output = def.transform(payload.value, payload);\n if (output instanceof Promise) {\n return output.then((output) => {\n payload.value = output;\n return payload;\n });\n }\n payload.value = output;\n return payload;\n };\n});\nexport function transform(fn) {\n return new ZodTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodOptional = /*@__PURE__*/ core.$constructor(\"ZodOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function optional(innerType) {\n return new ZodOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodExactOptional = /*@__PURE__*/ core.$constructor(\"ZodExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function exactOptional(innerType) {\n return new ZodExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodNullable = /*@__PURE__*/ core.$constructor(\"ZodNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullableProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nullable(innerType) {\n return new ZodNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodDefault = /*@__PURE__*/ core.$constructor(\"ZodDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.defaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeDefault = inst.unwrap;\n});\nexport function _default(innerType, defaultValue) {\n return new ZodDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodPrefault = /*@__PURE__*/ core.$constructor(\"ZodPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.prefaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function prefault(innerType, defaultValue) {\n return new ZodPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodNonOptional = /*@__PURE__*/ core.$constructor(\"ZodNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nonoptionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nonoptional(innerType, params) {\n return new ZodNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSuccess = /*@__PURE__*/ core.$constructor(\"ZodSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function success(innerType) {\n return new ZodSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodCatch = /*@__PURE__*/ core.$constructor(\"ZodCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.catchProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeCatch = inst.unwrap;\n});\nfunction _catch(innerType, catchValue) {\n return new ZodCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : core.util.constantCatch(catchValue)),\n });\n}\nexport { _catch as catch };\nexport const ZodNaN = /*@__PURE__*/ core.$constructor(\"ZodNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params);\n});\nexport function nan(params) {\n return core._nan(ZodNaN, params);\n}\nexport const ZodPipe = /*@__PURE__*/ core.$constructor(\"ZodPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.pipeProcessor(inst, ctx, json, params);\n inst.in = def.in;\n inst.out = def.out;\n});\nexport function pipe(in_, out) {\n return new ZodPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n // ...util.normalizeParams(params),\n });\n}\nexport const ZodCodec = /*@__PURE__*/ core.$constructor(\"ZodCodec\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\nexport function codec(in_, out, params) {\n return new ZodCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\nexport function invertCodec(codec) {\n const def = codec._zod.def;\n return new ZodCodec({\n type: \"pipe\",\n in: def.out,\n out: def.in,\n transform: def.reverseTransform,\n reverseTransform: def.transform,\n });\n}\nexport const ZodPreprocess = /*@__PURE__*/ core.$constructor(\"ZodPreprocess\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodPreprocess.init(inst, def);\n});\nexport const ZodReadonly = /*@__PURE__*/ core.$constructor(\"ZodReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.readonlyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function readonly(innerType) {\n return new ZodReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params);\n});\nexport function templateLiteral(parts, params) {\n return new ZodTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLazy = /*@__PURE__*/ core.$constructor(\"ZodLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.lazyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.getter();\n});\nexport function lazy(getter) {\n return new ZodLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport const ZodPromise = /*@__PURE__*/ core.$constructor(\"ZodPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function promise(innerType) {\n return new ZodPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodFunction = /*@__PURE__*/ core.$constructor(\"ZodFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params);\n});\nexport function _function(params) {\n return new ZodFunction({\n type: \"function\",\n input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n output: params?.output ?? unknown(),\n });\n}\nexport { _function as function };\nexport const ZodCustom = /*@__PURE__*/ core.$constructor(\"ZodCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.customProcessor(inst, ctx, json, params);\n});\n// custom checks\nexport function check(fn) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n // ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\nexport function custom(fn, _params) {\n return core._custom(ZodCustom, fn ?? (() => true), _params);\n}\nexport function refine(fn, _params = {}) {\n return core._refine(ZodCustom, fn, _params);\n}\n// superRefine\nexport function superRefine(fn, params) {\n return core._superRefine(fn, params);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\nexport const ZodInstanceOf = /*@__PURE__*/ core.$constructor(\"ZodInstanceOf\", (inst, def) => {\n ZodCustom.init(inst, def);\n}, {\n properties(shape, params) {\n // asserts in place, so the narrowed output type is truthful without a wrapper\n return this.check(core._properties(shape, params));\n },\n});\nfunction _instanceof(cls, params = {}) {\n const inst = new ZodInstanceOf({\n type: \"custom\",\n check: \"custom\",\n fn: (data) => data instanceof cls,\n abort: true,\n ...util.normalizeParams(params),\n });\n inst._zod.bag.Class = cls;\n // Override check to emit invalid_type instead of custom\n inst._zod.check = (payload) => {\n if (!(payload.value instanceof cls)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: cls.name,\n input: payload.value,\n inst,\n path: [...(inst._zod.def.path ?? [])],\n });\n }\n };\n return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n Codec: ZodCodec,\n Boolean: ZodBoolean,\n String: ZodString,\n}, ...args);\nexport function json(params) {\n const jsonSchema = lazy(() => {\n return union([string(params), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\n// preprocess\nexport function preprocess(fn, schema) {\n return new ZodPreprocess({\n type: \"pipe\",\n in: transform(fn),\n out: schema,\n });\n}\n","import * as core from \"../core/index.js\";\nimport { ZodISODate, ZodISODateTime, ZodISODuration, ZodISOTime } from \"./schemas.js\";\nexport { ZodISODate, ZodISODateTime, ZodISODuration, ZodISOTime } from \"./schemas.js\";\nexport function datetime(params) {\n return core._isoDateTime(ZodISODateTime, params);\n}\nexport function date(params) {\n return core._isoDate(ZodISODate, params);\n}\nexport function time(params) {\n return core._isoTime(ZodISOTime, params);\n}\nexport function duration(params) {\n return core._isoDuration(ZodISODuration, params);\n}\n","unable to read source [project]/node_modules/@aeolus-fleet/common/src/fleet/index.ts","/**\n * The web app's server calling the gateway's API (header design part 5,\n * decision 0033): one tRPC client per page request, as the browser that\n * asked, by its shared sign-in forwarded, in the fleet its page names. Server\n * only: a browser never calls the API from a page.\n */\nimport { FLEET_HEADER } from '@aeolus-fleet/common';\nimport { createTRPCClient, httpLink, type TRPCClient } from '@trpc/client';\n\nimport type { GatewayRouter } from '../../../src/adapters/trpc/router.js';\n\n/** The gateway's API, as the web app's server calls it. */\nexport type GatewayApi = TRPCClient<GatewayRouter>;\n\n/** The shared account sign-in's cookie (header design H5): src/core/account-sign-in/ports.ts names the same. */\nconst SHARED_SIGN_IN_COOKIE = 'aeolus_account_session';\n\n/**\n * The browser's cookies the API is sent: the shared sign-in alone. The API\n * would take the gateway's old page session or argo's console session first,\n * as another account or fleet than the page shows.\n */\nexport function forwardedCookieOf(header: string | undefined): string | undefined {\n const prefix = `${SHARED_SIGN_IN_COOKIE}=`;\n const signIn = header\n ?.split(';')\n .map((part) => part.trim())\n .find((part) => part.startsWith(prefix) && part.length > prefix.length);\n return signIn;\n}\n\n/** The header the waiting page sends its browser's secret in, so it never travels in an address (src/adapters/trpc/router.ts names the same). */\nconst WAITING_SECRET_HEADER = 'aeolus-waiting-secret';\n\n/** What a call of the API is sent besides its input: the shared sign-in, the fleet the page names, and the waiting page's browser secret. */\nexport interface ApiSent {\n cookie: string | undefined;\n fleetId: string | undefined;\n waitingSecret?: string;\n}\n\nexport function apiHeadersOf(sent: ApiSent): Record<string, string> {\n const cookie = forwardedCookieOf(sent.cookie);\n return {\n ...(cookie === undefined ? {} : { cookie }),\n ...(sent.fleetId === undefined ? {} : { [FLEET_HEADER]: sent.fleetId }),\n ...(sent.waitingSecret === undefined ? {} : { [WAITING_SECRET_HEADER]: sent.waitingSecret }),\n };\n}\n\nexport function gatewayApi(sent: ApiSent & { url: string }): GatewayApi {\n return createTRPCClient<GatewayRouter>({ links: [httpLink({ url: `${sent.url}/trpc`, headers: apiHeadersOf(sent) })] });\n}\n","/**\n * What a page of the web app does with the API's account.inView (header\n * design H5, H9): show its fleet as the account signed in, or send the\n * browser where it may go: the same page in the fleet the account may open,\n * the app it may open there, or sign-in and back to the page. Where the\n * gateway is off for the account's fleet, the page says so instead.\n */\n\n/** The API's answer to account.inView. */\nexport type InView =\n | { kind: 'signedIn'; fleetId: string; accountId: string; scopes: string[] }\n | { kind: 'goTo'; fleetId: string }\n | { kind: 'off'; fleetName: string; accountUrl: string }\n | { kind: 'elsewhere'; url: string };\n\n/** The API's refusals of account.inView a page answers: signed in to no account, and no shared sign-in at this gateway. */\nexport type InViewRefusal = 'UNAUTHORIZED' | 'NOT_FOUND';\n\nexport type PageAccount =\n | { kind: 'signedIn'; fleetId: string; scopes: readonly string[] }\n | { kind: 'goTo'; location: string }\n | { kind: 'off'; fleetName: string; accountUrl: string }\n | { kind: 'noSignIn' };\n\nconst SIGN_IN_START = '/sign-in/start';\n\n/** The parameter a page names its fleet by. */\nexport const FLEET_PARAMETER = 'fleet';\n\n/** A page of the web app in a fleet: every link keeps the fleet in its address. */\nexport function inFleet(page: string, fleetId: string): string {\n const [path = '', query = ''] = page.split('?');\n const parameters = new URLSearchParams(query);\n parameters.set(FLEET_PARAMETER, fleetId);\n return `${path}?${parameters.toString()}`;\n}\n\n/** Reads the answer for the page asked for, its path and query as the browser sent them. */\nexport function pageAccountOf(read: { inView: InView } | { refusal: InViewRefusal }, page: string): PageAccount {\n if ('refusal' in read) {\n return read.refusal === 'UNAUTHORIZED' ? { kind: 'goTo', location: `${SIGN_IN_START}?${new URLSearchParams({ return_to: page }).toString()}` } : { kind: 'noSignIn' };\n }\n const { inView } = read;\n switch (inView.kind) {\n case 'signedIn':\n return { kind: 'signedIn', fleetId: inView.fleetId, scopes: inView.scopes };\n case 'goTo':\n return { kind: 'goTo', location: inFleet(page, inView.fleetId) };\n case 'off':\n return inView;\n case 'elsewhere':\n return { kind: 'goTo', location: inView.url };\n }\n}\n","/**\n * The gateway's API for a page of the web app and for its forms (server\n * actions): as the browser that asked, by its cookies, at the address the\n * gateway's server gave the web app, never one a request names.\n */\nimport { TRPCClientError } from '@trpc/client';\nimport { headers } from 'next/headers';\nimport { redirect } from 'next/navigation';\n\nimport type { GatewayRouter } from '../../../src/adapters/trpc/router.js';\nimport { gatewayApi, type GatewayApi } from './gateway-api';\nimport { FLEET_PARAMETER, inFleet, pageAccountOf, type InView, type InViewRefusal } from './page-account';\n\n/** Set by the gateway's server as it starts the web app (src/adapters/web/next-web-app.ts). */\nconst API_URL_VARIABLE = 'AEOLUS_GATEWAY_API_URL';\n\n/** A page's search parameters, as Next.js hands them over. */\nexport type SearchParams = Record<string, string | string[] | undefined>;\n\n/** A page shown as the account signed in: the API as it, its fleet and its scopes there. */\nexport interface SignedInPage {\n kind: 'signedIn';\n api: GatewayApi;\n fleetId: string;\n scopes: readonly string[];\n}\n\n/** The page that says the gateway is off for the account's fleet. */\nexport const GATEWAY_OFF_PATH = '/gateway-off';\n\n/** Where the page that says the gateway is off sends an account once it may open the gateway. */\nconst OVERVIEW_PATH = '/overview';\n\n/** The gateway's own address, where the API answers. */\nexport function apiUrl(): string {\n const url = process.env[API_URL_VARIABLE];\n if (url === undefined) {\n throw new Error(`${API_URL_VARIABLE} is not set: the gateway's server starts the web app`);\n }\n return url;\n}\n\n/** The API as the browser that asked, in the fleet named. */\nexport async function requestApi(fleetId: string | undefined): Promise<GatewayApi> {\n return gatewayApi({ url: apiUrl(), cookie: (await headers()).get('cookie') ?? undefined, fleetId });\n}\n\nfunction isApiRefusal(error: unknown): error is TRPCClientError<GatewayRouter> {\n return error instanceof TRPCClientError;\n}\n\n/** The code the API refused a call with, if it refused it. */\nexport function refusalCodeOf(error: unknown): string | undefined {\n return isApiRefusal(error) ? error.data?.code : undefined;\n}\n\n/** Why the API refused a call, as it says it; anything else is no refusal and is thrown on. */\nexport function refusalMessageOf(error: unknown): string {\n if (!isApiRefusal(error)) {\n throw error;\n }\n return error.message;\n}\n\nfunction isInViewRefusal(code: string | undefined): code is InViewRefusal {\n return code === 'UNAUTHORIZED' || code === 'NOT_FOUND';\n}\n\n/** The API's answer to account.inView for the API given, the refusals a page answers included. */\nasync function inViewOf(api: GatewayApi): Promise<{ inView: InView } | { refusal: InViewRefusal }> {\n try {\n return { inView: await api.account.inView.query() };\n } catch (error) {\n const code = refusalCodeOf(error);\n if (!isInViewRefusal(code)) {\n throw error;\n }\n return { refusal: code };\n }\n}\n\n/**\n * The page as the account signed in, in the fleet its address names; or\n * the browser is sent where it may go, the page that says the gateway is\n * off for the account's fleet included. A gateway that signs no one in to\n * its pages answers noSignIn.\n */\nexport async function signedInPage(page: { path: string; searchParams: SearchParams }): Promise<SignedInPage | { kind: 'noSignIn' }> {\n const query = new URLSearchParams();\n for (const [name, value] of Object.entries(page.searchParams)) {\n if (typeof value === 'string') {\n query.set(name, value);\n }\n }\n const fleet = query.get(FLEET_PARAMETER) ?? undefined;\n const asked = query.size === 0 ? page.path : `${page.path}?${query.toString()}`;\n const api = await requestApi(fleet);\n const account = pageAccountOf(await inViewOf(api), asked);\n switch (account.kind) {\n case 'goTo':\n return redirect(account.location);\n case 'off':\n return redirect(GATEWAY_OFF_PATH);\n case 'noSignIn':\n return account;\n case 'signedIn':\n return { kind: 'signedIn', api, fleetId: account.fleetId, scopes: account.scopes };\n }\n}\n\n/**\n * The page that says the gateway is off for the account's fleet: its name\n * and the way back to its account; once the account may open the gateway,\n * the browser goes to the Overview.\n */\nexport async function gatewayOffPage(): Promise<{ kind: 'off'; fleetName: string; accountUrl: string } | { kind: 'noSignIn' }> {\n const account = pageAccountOf(await inViewOf(await requestApi(undefined)), OVERVIEW_PATH);\n switch (account.kind) {\n case 'goTo':\n return redirect(account.location);\n case 'signedIn':\n return redirect(inFleet(OVERVIEW_PATH, account.fleetId));\n case 'off':\n case 'noSignIn':\n return account;\n }\n}\n\n/** What a page reads from the API, or why the API refused it, for the page to say in its place. */\nexport type Read<T> = { isOk: true; value: T } | { isOk: false; refusal: string };\n\nexport async function readOf<T>(call: Promise<T>): Promise<Read<T>> {\n try {\n return { isOk: true, value: await call };\n } catch (error) {\n return { isOk: false, refusal: refusalMessageOf(error) };\n }\n}\n"],"names":["isObservable","x","teardownRef","subscribe","isDone","_observer$complete","teardownImmediately","unsubscribe","observable","AbortController","onDone","ac","signal","addEventListener","data","complete","isObject","msg","forbidden","DIGEST","HTTP_ERROR_FALLBACK_ERROR_CODE","process","env","__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS","Error","error","digest","HTTPAccessErrorStatus","getAccessFallbackErrorTypeByStatus","getAccessFallbackHTTPStatus","isHTTPAccessFallbackError","NOT_FOUND","FORBIDDEN","UNAUTHORIZED","ALLOWED_CODES","Set","Object","values","prefix","httpStatus","split","has","Number","status","isNextRouterError","isRedirectError","ReadonlyURLSearchParams","RedirectType","notFound","permanentRedirect","redirect","unauthorized","unstable_isUnrecognizedActionError","unstable_rethrow","push","replace","ReadonlyURLSearchParamsError","constructor","URLSearchParams","append","delete","set","sort","REDIRECT_ERROR_CODE","errorCode","type","destination","slice","join","at","statusCode","isNaN","RedirectStatusCode","getRedirectError","getRedirectStatusCodeFromError","getRedirectTypeFromError","getURLFromRedirectError","url","TemporaryRedirect","actionAsyncStorage","getStore","isAction","PermanentRedirect","workAsyncStorage","workUnitAsyncStorage","isBailoutToCSRError","isDynamicServerError","isHangingPromiseRejectionError","isPrerenderInterruptedError","cause","BailoutToCSRError","BAILOUT_TO_CSR","reason","err","assertEqual","val","assertNotEqual","toZod","schema","assertIs","_arg","assertNever","_x","assert","_","getEnumValues","entries","numericValues","filter","v","k","indexOf","map","joinValues","array","separator","stringifyPrimitive","jsonStringifyReplacer","value","toString","Cached","getter","_getter","_value","undefined","cached","nullish","input","cleanRegex","source","start","startsWith","end","endsWith","length","floatSafeRemainder","step","ratio","roundedRatio","Math","round","tolerance","EPSILON","max","abs","EVALUATING","Symbol","defineLazy","object","key","defineProperty","get","configurable","objectClone","obj","create","getPrototypeOf","getOwnPropertyDescriptors","assignProp","target","prop","writable","enumerable","rawShape","def","desc","getOwnPropertyDescriptor","raw","sourceShape","_zod","shape","deferProp","putProp","mirrorShape","keys","wrap","mirrorProps","Reflect","ownKeys","mergeDefs","defs","mergedDescriptors","descriptors","assign","defineProperties","cloneDef","getElementAtPath","path","reduce","acc","promiseAllObject","promisesObj","promises","Promise","all","then","results","resolvedObj","i","randomString","chars","str","floor","random","esc","JSON","stringify","slugify","toLowerCase","trim","captureStackTrace","_args","Array","isArray","allowsEval","globalConfig","jitless","navigator","userAgent","includes","F","Function","isPlainObject","o","ctor","prot","prototype","hasOwnProperty","call","shallowClone","Map","numKeys","keyCount","getParsedType","t","catch","Date","File","propertyKeyTypes","primitiveTypes","escapeRegex","clone","inst","params","cl","constr","parent","normalizeParams","_params","message","createTransparentProxy","Proxy","receiver","deleteProperty","descriptor","optionalKeys","optin","optout","NUMBER_FORMAT_RANGES","safeint","MIN_SAFE_INTEGER","MAX_SAFE_INTEGER","int32","uint32","float32","float64","MAX_VALUE","BIGINT_FORMAT_RANGES","int64","BigInt","uint64","pick","mask","currDef","checks","hasChecks","newShape","maskedKeys","String","omit","omitted","extend","existingShape","extended","safeExtend","merge","a","b","catchall","partial","Class","name","selected","innerType","required","aborted","startIndex","issues","continue","explicitlyAborted","prefixIssues","iss","_a","unshift","unwrapMessage","sizeCaps","defChecks","caps","ch","d","test","check","maximum","size","attachSchema","finalizeIssue","ctx","config","traits","schemaError","customError","localeError","full","reportInput","getSizableOrigin","highSurrogate","codePointLength","units","count","charCodeAt","getLengthableOrigin","parsedType","issue","args","code","cleanEnum","parseInt","el","base64ToUint8Array","base64","binaryString","atob","bytes","Uint8Array","uint8ArrayToBase64","fromCharCode","btoa","base64urlToUint8Array","base64url","padding","repeat","uint8ArrayToBase64url","hexToUint8Array","hex","cleanHex","uint8ArrayToHex","from","padStart","members","proto","table","defineBound","own","hide","derived","computes","compute","fn","bind","claim","sentinel","installing","broke","breaker","defineLazyInternal","outer","installLazyProp","make","CONSTANT_CATCH","constantCatch","SIGN_IN_START","FLEET_PARAMETER","inFleet","page","fleetId","query","parameters","pageAccountOf","read","refusal","kind","location","return_to","inView","scopes","API_URL_VARIABLE","GATEWAY_OFF_PATH","OVERVIEW_PATH","apiUrl","requestApi","cookie","isApiRefusal","refusalCodeOf","refusalMessageOf","isInViewRefusal","inViewOf","api","account","signedInPage","searchParams","fleet","asked","gatewayOffPage","readOf","isOk"],"mappings":"6CASG,IAAA,EAAA,EAAA,CAAA,CAAA,OACH,EAAwB,CAAjB,CAAiB,CAAA,AAAf,CAAe,AAAd,EAAE,KAEL,CAFW,GAEL,EAFU,AAEI,CAFH,AAGtB,KAAK,CAAE,EADe,GACV,CACZ,IAAI,CAAE,KAAK,CACX,OAAO,CAAE,KAAK,CACd,QAAQ,CAAE,KAAK,CACf,KAAK,CAAE,KAAK,CACZ,KAAK,CAAE,KAAK,CACZ,UAAU,CAAE,KAAK,CACjB,QAAQ,CAAE,KAAK,CACf,cAAc,CAAE,KAAK,CACrB,KAAK,CAAE,KAAK,CACZ,UAAU,CAAE,KAAK,CACjB,YAAY,CAAE,KAAK,CAEnB,OAAO,CAAE,KAAK,CAEd,OAAO,CAAE,KAAK,CAEd,QAAQ,CAAE,KAAK,CACP,CAAC,AASE,EAA8B,MAAtB,AAA4B,CAAC,IAAI,CAAC,GAAa,MAAM,CAAC,AAL3E,CAKkE,CAAC,MAAgB,CAAC,AAL3E,AAAS,C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AClB,IAAK,OACH,MAAO,CAAA,EAAA,EAAA,QAAA,AAAQ,EAACiB,EAAQhB,QAAQ,CAClC,KAAK,WACH,MAAO,CAAA,EAAA,EAAA,QAAA,AAAQ,EAAC,CAAA,EAAA,EAAA,CAAA,AAAO,EAACM,EAAeU,EAAQvB,OAAO,EACxD,KAAK,MACL,IAAK,WACH,OAAOuB,CACX,CACF,CAKO,eAAeM,EAAUzL,CAAgB,EAC9C,GAAI,CACF,MAAO,CAAE0L,MAAM,EAAMxS,MAAO,MAAM8G,CAAK,CACzC,CAAE,MAAO3M,EAAO,CACd,MAAO,CAAEqY,MAAM,EAAOzB,QAASc,EAAiB1X,EAAO,CACzD,CACF","ignoreList":[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93]}