@harperfast/harper 5.2.13 → 5.2.14

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 (264) hide show
  1. package/components/Application.ts +7 -7
  2. package/components/componentLoader.ts +70 -33
  3. package/dist/components/Application.js +1 -7
  4. package/dist/components/Application.js.map +1 -1
  5. package/dist/components/componentLoader.d.ts +6 -0
  6. package/dist/components/componentLoader.js +60 -31
  7. package/dist/components/componentLoader.js.map +1 -1
  8. package/dist/resources/RocksTransactionLogStore.d.ts +4 -2
  9. package/dist/resources/RocksTransactionLogStore.js +12 -6
  10. package/dist/resources/RocksTransactionLogStore.js.map +1 -1
  11. package/dist/resources/Table.js +40 -4
  12. package/dist/resources/Table.js.map +1 -1
  13. package/dist/resources/replayLogs.js +25 -21
  14. package/dist/resources/replayLogs.js.map +1 -1
  15. package/dist/resources/transactionBroadcast.js +4 -6
  16. package/dist/resources/transactionBroadcast.js.map +1 -1
  17. package/dist/security/certificateVerification/index.js +40 -11
  18. package/dist/security/certificateVerification/index.js.map +1 -1
  19. package/dist/security/certificateVerification/trustedIssuers.d.ts +24 -0
  20. package/dist/security/certificateVerification/trustedIssuers.js +79 -0
  21. package/dist/security/certificateVerification/trustedIssuers.js.map +1 -0
  22. package/dist/security/certificateVerification/types.d.ts +1 -0
  23. package/dist/security/keys.js +4 -0
  24. package/dist/security/keys.js.map +1 -1
  25. package/dist/server/loadRootComponents.js +4 -2
  26. package/dist/server/loadRootComponents.js.map +1 -1
  27. package/dist/server/threads/manageThreads.d.ts +1 -0
  28. package/dist/server/threads/manageThreads.js +175 -24
  29. package/dist/server/threads/manageThreads.js.map +1 -1
  30. package/npm-shrinkwrap.json +2 -2
  31. package/package.json +1 -1
  32. package/resources/DESIGN.md +5 -0
  33. package/resources/RocksTransactionLogStore.ts +12 -6
  34. package/resources/Table.ts +39 -4
  35. package/resources/replayLogs.ts +25 -22
  36. package/resources/transactionBroadcast.ts +4 -4
  37. package/security/certificateVerification/index.ts +54 -13
  38. package/security/certificateVerification/trustedIssuers.ts +76 -0
  39. package/security/certificateVerification/types.ts +1 -0
  40. package/security/keys.ts +3 -0
  41. package/server/DESIGN.md +14 -13
  42. package/server/loadRootComponents.js +9 -2
  43. package/server/threads/manageThreads.js +176 -23
  44. package/studio/web/404.html +79 -0
  45. package/studio/web/assets/{Chat-4RrB5134.js → Chat-C97PMlIn.js} +274 -247
  46. package/studio/web/assets/FloatingChat-BUlsFGMV.js +23 -0
  47. package/studio/web/assets/_basePickBy-QJXUw_pr.js +1 -0
  48. package/studio/web/assets/_baseUniq-DR4vVjyC.js +1 -0
  49. package/studio/web/assets/{abnfDiagram-VCTEODGH-B0BebmD2.js → abnfDiagram-O67JEVCF-DpPZWMOf.js} +1 -1
  50. package/studio/web/assets/{alertDialog-CQyAJJhl.js → alertDialog-UrbiMgQt.js} +1 -1
  51. package/studio/web/assets/{apiToken-Bke3wvfZ.js → apiToken-CPhbc_zN.js} +1 -1
  52. package/studio/web/assets/applications-D3Z6BVDl.js +296 -0
  53. package/studio/web/assets/architecture-7GRP2DOG-11l4Ny1l.js +1 -0
  54. package/studio/web/assets/architectureDiagram-NJMV4G6O-OmgLraID.js +36 -0
  55. package/studio/web/assets/authStore-5jSS5pTW.js +3 -0
  56. package/studio/web/assets/{blockDiagram-I7D4REHJ-BqguiadH.js → blockDiagram-BEXU5L5S-Cv7CD3Ai.js} +15 -4
  57. package/studio/web/assets/{button-BIsUKRZq.js → button-MFP9n8Ck.js} +1 -1
  58. package/studio/web/assets/c4Diagram-YGBWAQC7-Ds1vKYnN.js +38 -0
  59. package/studio/web/assets/channel-BDtouPd6.js +1 -0
  60. package/studio/web/assets/chevron-up-CFe8x5Bp.js +1 -0
  61. package/studio/web/assets/chunk-3FUC2YCW-DpnBPH8B.js +2 -0
  62. package/studio/web/assets/{chunk-GVQU2GXP-sbwVIQ8i.js → chunk-5DYCD2WN-LLLCQSzg.js} +1 -1
  63. package/studio/web/assets/{chunk-PWAF6VOD-1z1THyS5.js → chunk-742MDFTN-BL8J_pIO.js} +1 -1
  64. package/studio/web/assets/chunk-7INBJB4K-C-hJHiiK.js +62 -0
  65. package/studio/web/assets/chunk-7M6MHVWA-C6ZqkFbA.js +213 -0
  66. package/studio/web/assets/chunk-7PRAP22T-CUXM8BG6.js +1 -0
  67. package/studio/web/assets/chunk-DUW6YSOI-Dgx8z5s3.js +1 -0
  68. package/studio/web/assets/{chunk-FOHPRMQF-DHwB1DNv.js → chunk-FOHPRMQF-DzxwRta7.js} +9 -9
  69. package/studio/web/assets/{chunk-SVP7TREG-jtdAHw0S.js → chunk-GTNCS2PH-DJ2BFvS1.js} +1 -1
  70. package/studio/web/assets/{chunk-F27PBJKO-BVA5EPhV.js → chunk-GWA4HPMP-C42bSqLL.js} +1 -1
  71. package/studio/web/assets/chunk-J5ZVWO5B-oDCd-gWO.js +1 -0
  72. package/studio/web/assets/chunk-MBY4JIJT-C-5jz6Lo.js +72 -0
  73. package/studio/web/assets/chunk-NETBCI7D-D-bzlN4r.js +1 -0
  74. package/studio/web/assets/chunk-O7XYJQB3-ep14zA23.js +128 -0
  75. package/studio/web/assets/chunk-UA2S7LBM-BMRWRHED.js +1 -0
  76. package/studio/web/assets/{chunk-POPQ4Y6H-ClWhhkwW.js → chunk-WEXAMYUT-DdLYVdX1.js} +1 -1
  77. package/studio/web/assets/{chunk-XXDRQBXY-BoGZu3HH.js → chunk-XXDRQBXY-CbPh2l8S.js} +1 -1
  78. package/studio/web/assets/{chunk-OSK3NFVY-ByciRftO.js → chunk-Z7XXMR3K-BmKEDjcP.js} +3 -3
  79. package/studio/web/assets/{chunk-75Z2AOVW-QGQD6th2.js → chunk-ZIGJFQKS-DLZgdNxA.js} +2 -2
  80. package/studio/web/assets/classDiagram-v2-NBCMYWYE-DOI5vgKT.js +217 -0
  81. package/studio/web/assets/cose-bilkent-JH36ORCC-BSOszL11.js +1 -0
  82. package/studio/web/assets/createLucideIcon-bziYxJli.js +1 -0
  83. package/studio/web/assets/{css.worker-BD9HbRGW.js → css.worker-l1psR_wG.js} +13 -10
  84. package/studio/web/assets/{cssMode-C1vRa7zh.js → cssMode-DyLZPMjo.js} +1 -1
  85. package/studio/web/assets/cynefin-OW5HDTMX-BSW-DB7S.js +1 -0
  86. package/studio/web/assets/cynefinDiagram-VND7K2PF-CbAHEwxt.js +62 -0
  87. package/studio/web/assets/cytoscape.esm-BZkf-uXn.js +321 -0
  88. package/studio/web/assets/dagre-6A5THRUB-Csxewgs4.js +4 -0
  89. package/studio/web/assets/diagram-22UHCM2B-a0rt8tY4.js +200 -0
  90. package/studio/web/assets/{diagram-VX7I27RA-DccVJet6.js → diagram-3UASUU5V-lEj2SVNh.js} +2 -2
  91. package/studio/web/assets/{diagram-VSXAHHWV-fhEdmkwM.js → diagram-ATOU4E4O-HcrAeB-q.js} +3 -3
  92. package/studio/web/assets/{diagram-S7CK7UJ4-aoCVTtcy.js → diagram-CDSNMT55-CYxiuyEx.js} +3 -3
  93. package/studio/web/assets/{diagram-Z3DM3KII-D-RyJJb7.js → diagram-MLGK6HIB-ChbCJTgJ.js} +1 -1
  94. package/studio/web/assets/diagram-MPIPVDR6-DaX9Y-N3.js +41 -0
  95. package/studio/web/assets/dialog-DTepachC.js +1 -0
  96. package/studio/web/assets/{dist-kYfyPZP9.js → dist-BRuBKNNy.js} +1 -1
  97. package/studio/web/assets/{dist-DP8UjMB_.js → dist-Cz2Y6-6G.js} +2 -2
  98. package/studio/web/assets/download-CtostjYn.js +1 -0
  99. package/studio/web/assets/{ebnfDiagram-PWID7BFC-DJGpIpz_.js → ebnfDiagram-ZINNZB2B-CwAsENB1.js} +1 -1
  100. package/studio/web/assets/{editor-3XRWEDWX.js → editor-CFQ5kbiT.js} +1 -1
  101. package/studio/web/assets/editor.worker-CkkvdXvO.js +33 -0
  102. package/studio/web/assets/elk-276RUBZZ-Hexg9E4D.js +27 -0
  103. package/studio/web/assets/{erDiagram-RLTQ6QDP-CIfNlgkC.js → erDiagram-OPXOYQCR-CeC-wwO1.js} +15 -15
  104. package/studio/web/assets/eventmodeling-NTZA5JFV-CFb03e0o.js +1 -0
  105. package/studio/web/assets/flowDiagram-KWPJA3E3-Cidi00_Y.js +1 -0
  106. package/studio/web/assets/{ganttDiagram-EL5Y4UJY-BxToTzzD.js → ganttDiagram-FUAMR5RP-C2_Hhl1-.js} +2 -2
  107. package/studio/web/assets/{getAnalytics-GHK8ORfM.js → getAnalytics-CjthMQqF.js} +1 -1
  108. package/studio/web/assets/gitGraph-4MIJSDKK-xIk5Vuew.js +1 -0
  109. package/studio/web/assets/{gitGraphDiagram-WWUBYQGX-Dwntd4-x.js → gitGraphDiagram-X574FWY7-CMxJ34up.js} +4 -4
  110. package/studio/web/assets/graphlib-C9Tl7QrK.js +1 -0
  111. package/studio/web/assets/{html-CTY5tdMr.js → html-DdMBJEGu.js} +1 -1
  112. package/studio/web/assets/{html.worker-DsMmVtuG.js → html.worker-DdwM4IrA.js} +12 -9
  113. package/studio/web/assets/{htmlMode-CG1vSD9t.js → htmlMode-DNtBx3OV.js} +1 -1
  114. package/studio/web/assets/index-CPoDzQTe.css +1 -0
  115. package/studio/web/assets/index-zZCxAIEb.js +824 -0
  116. package/studio/web/assets/index.lazy-CKbsHbSN.js +2 -0
  117. package/studio/web/assets/info-A6RAGUB7-o49TEbj-.js +1 -0
  118. package/studio/web/assets/infoDiagram-VRGFBTTK-Cjhh7yzZ.js +2 -0
  119. package/studio/web/assets/{ishikawaDiagram-5VMMS53U-D9Xh2r6X.js → ishikawaDiagram-OU5B5YK6-C63aXRmh.js} +2 -2
  120. package/studio/web/assets/{javascript-CJeJzGnI.js → javascript-Dy6KbeHT.js} +1 -1
  121. package/studio/web/assets/{journeyDiagram-3NMN7TZE-CokIi6ll.js → journeyDiagram-ZHPQQLJL-D_o0P5Mu.js} +3 -3
  122. package/studio/web/assets/json.worker-CSi2hF-a.js +65 -0
  123. package/studio/web/assets/{jsonMode-CYPBwM82.js → jsonMode-BiuDVrzl.js} +1 -1
  124. package/studio/web/assets/{kanban-definition-UXKFOSKX-CukSFJfX.js → kanban-definition-PNTS6WVX-CTI9SSxY.js} +7 -7
  125. package/studio/web/assets/{katex-CXMH3UgJ.js → katex-ZlcWpGUi.js} +2 -2
  126. package/studio/web/assets/languageServices-Dk8_6B25.js +1 -0
  127. package/studio/web/assets/linear-Ds1AeO4V.js +1 -0
  128. package/studio/web/assets/{lspLanguageFeatures-BC8_gxKG.js → lspLanguageFeatures-DwJKXzQa.js} +2 -2
  129. package/studio/web/assets/{mermaid-parser.core-BlEsOWNO.js → mermaid-parser.core-C2lcH_jP.js} +3 -3
  130. package/studio/web/assets/mermaid.core-BG5bjfIG.js +44 -0
  131. package/studio/web/assets/{mindmap-definition-YA3MSWOX-IprMc_0j.js → mindmap-definition-NLK3R4M7-BK7ho6JD.js} +24 -24
  132. package/studio/web/assets/{notifications-DFbArTfC.js → notifications-DJqAtWxD.js} +1 -1
  133. package/studio/web/assets/{notifications-BfKBpYcq.js → notifications-DsDtb41c.js} +1 -1
  134. package/studio/web/assets/packet-AYTQ26CC-BHPy6KBV.js +1 -0
  135. package/studio/web/assets/{pegDiagram-XKGWAZYB-BNuPDLZY.js → pegDiagram-GJSIUBJH-DzjwG3jO.js} +1 -1
  136. package/studio/web/assets/pie-WAS4IAKB-D0cP-DTU.js +1 -0
  137. package/studio/web/assets/{pieDiagram-E7YTZNPT-DqNb6Ht2.js → pieDiagram-5QR66LMP-C_hOP9Lv.js} +2 -2
  138. package/studio/web/assets/profile-zTGUN51x.js +1 -0
  139. package/studio/web/assets/{quadrantDiagram-AXDQQJYC-BGH9E2YR.js → quadrantDiagram-O4NWA36T-CZW8PbV1.js} +3 -3
  140. package/studio/web/assets/radar-RG4KPBEZ-C8fk0U81.js +1 -0
  141. package/studio/web/assets/railroad-74A4TZTK-B60FWm17.js +1 -0
  142. package/studio/web/assets/railroad-abnf-HS5TGJTU-CLMVZvH0.js +1 -0
  143. package/studio/web/assets/railroad-ebnf-LZEXJU2U--tlwFoVB.js +1 -0
  144. package/studio/web/assets/railroad-peg-WCYAUIDC-Dpuslblm.js +1 -0
  145. package/studio/web/assets/{railroadDiagram-O6MQD6OU-DGTPh2KZ.js → railroadDiagram-XR7U4H2S-DyyNmgbU.js} +1 -1
  146. package/studio/web/assets/regions-SOtABPB9.js +1 -0
  147. package/studio/web/assets/{register-1ZZuMsiA.js → register-7JezVakc.js} +39 -39
  148. package/studio/web/assets/{requirementDiagram-BXWQKSXE-BJnO6uLz.js → requirementDiagram-PLB6GJNP-C4H-mLKu.js} +11 -11
  149. package/studio/web/assets/{rolldown-runtime-hePW80VL.js → rolldown-runtime-Dd_uD5pT.js} +1 -1
  150. package/studio/web/assets/sankeyDiagram-IPEJSGJF-DHDyga4c.js +40 -0
  151. package/studio/web/assets/sequenceDiagram-PO4LG4MO-CdNcHXRI.js +169 -0
  152. package/studio/web/assets/setComponentFile-BavlhfY0.js +1 -0
  153. package/studio/web/assets/{setup-DWprJyJy.js → setup-04yVzr2I.js} +2 -2
  154. package/studio/web/assets/sizeCapture-INFHLROL-3uHXrFqA.js +1 -0
  155. package/studio/web/assets/{src-CMc7m_Ut.js → src-D0vMJQRr.js} +1 -1
  156. package/studio/web/assets/stateDiagram-v2-GCMORJYK-CpKuXq15.js +291 -0
  157. package/studio/web/assets/status-g_mNYE7j.js +61 -0
  158. package/studio/web/assets/swimlanes-2SLR337P-NRHa2D8I.js +1 -0
  159. package/studio/web/assets/swimlanesDiagram-TC7HE7FX-BBk4t4hO.js +8 -0
  160. package/studio/web/assets/{tabs-BrHu7gJi.js → tabs-CnQ_zenf.js} +1 -1
  161. package/studio/web/assets/{time-Cclkb7kQ.js → time-Ci1v4fvT.js} +1 -1
  162. package/studio/web/assets/timeline-definition-EJHVYXUP-D39Y-xpq.js +120 -0
  163. package/studio/web/assets/toggleHighContrast-i2FjCrzO.js +49 -0
  164. package/studio/web/assets/treeView-Q6P3EWNA-CRWR9OqD.js +1 -0
  165. package/studio/web/assets/treemap-WGGIJYW6-ZfXyJgLO.js +1 -0
  166. package/studio/web/assets/{ts.worker-DpaaFKhy.js → ts.worker-DDMUrpqh.js} +118 -115
  167. package/studio/web/assets/{tsMode-pjgytARx.js → tsMode-DGeWfx0W.js} +5 -5
  168. package/studio/web/assets/{typescript-Cdg0mqUh.js → typescript-62_1FUbs.js} +1 -1
  169. package/studio/web/assets/{useEntityRestURL-RZhaY8Rn.js → useEntityRestURL-DSVwev9J.js} +1 -1
  170. package/studio/web/assets/useLocalStorage-BYoZF60G.js +1 -0
  171. package/studio/web/assets/usecaseDiagram-POWQR4AR-jf-zIDZ_.js +328 -0
  172. package/studio/web/assets/vendor-core-BdkdbUek.js +63 -0
  173. package/studio/web/assets/vendor-datadog-fCQhBHGk.js +6 -0
  174. package/studio/web/assets/vendor-react-izWchTRL.js +9 -0
  175. package/studio/web/assets/vendor-tanstack-CQ1aRjVa.js +2 -0
  176. package/studio/web/assets/vendor-ui-aE1tHcW7.js +41 -0
  177. package/studio/web/assets/vennDiagram-UO4OBE2U-BKYAZUh_.js +34 -0
  178. package/studio/web/assets/wardley-WFR3VGLG-BO7f36ci.js +1 -0
  179. package/studio/web/assets/{wardleyDiagram-VM6X3IG4-CjrkKWUR.js → wardleyDiagram-VNRHLVJA-Djb0JDQc.js} +3 -3
  180. package/studio/web/assets/{workers-BgoXIqQe.js → workers-Cs52GyHv.js} +1 -1
  181. package/studio/web/assets/x-vYntCxm4.js +1 -0
  182. package/studio/web/assets/{xml-BwSeDMiP.js → xml-Co5ow_Ix.js} +1 -1
  183. package/studio/web/assets/{xychartDiagram-S5SC5T6Z-Biok4GYV.js → xychartDiagram-PMCCYNJV-BQh9ubvb.js} +3 -3
  184. package/studio/web/assets/{yaml-DotCUG5l.js → yaml-BcngpXye.js} +1 -1
  185. package/studio/web/assets/yaml.worker-DAK2o_H1.js +479 -0
  186. package/studio/web/auth/fabric-globe-dark.png +0 -0
  187. package/studio/web/auth/fabric-globe-light.png +0 -0
  188. package/studio/web/auth/fabric-platform-dark.png +0 -0
  189. package/studio/web/auth/fabric-platform-light.png +0 -0
  190. package/studio/web/index.html +15 -15
  191. package/studio/web/assets/FloatingChat-omlNMDcJ.js +0 -23
  192. package/studio/web/assets/applications-DvFDYJgK.js +0 -296
  193. package/studio/web/assets/architecture-7GRP2DOG-LB-MLAAb.js +0 -1
  194. package/studio/web/assets/architectureDiagram-5GKGNRK7-7SW3GD-K.js +0 -36
  195. package/studio/web/assets/authStore-C3Nfubqr.js +0 -3
  196. package/studio/web/assets/c4Diagram-7LVT6UL2-LBNf8t_X.js +0 -38
  197. package/studio/web/assets/channel-yictG-U-.js +0 -1
  198. package/studio/web/assets/chevron-up-DtKGqDn3.js +0 -1
  199. package/studio/web/assets/chunk-4HAMMTFA-DWtTut21.js +0 -62
  200. package/studio/web/assets/chunk-DU6HZSFF-Chq20Ba5.js +0 -127
  201. package/studio/web/assets/chunk-GMAD6QVW-BeS7S07A.js +0 -72
  202. package/studio/web/assets/chunk-IMKFNOWR-Bnh3tAVd.js +0 -231
  203. package/studio/web/assets/chunk-L3NEJ4N5-COfUyKII.js +0 -1
  204. package/studio/web/assets/chunk-P2QGCYS3-CP1VhG_c.js +0 -1
  205. package/studio/web/assets/chunk-SHT3W25Y-LpQkMsah.js +0 -168
  206. package/studio/web/assets/chunk-TICWLB2K-VOwzetX-.js +0 -206
  207. package/studio/web/assets/classDiagram-ZZMXUADV-VaEwSy_g.js +0 -1
  208. package/studio/web/assets/classDiagram-v2-VYDZK3BY-VaEwSy_g.js +0 -1
  209. package/studio/web/assets/cose-bilkent-JH36ORCC-Cuuf67Bh.js +0 -1
  210. package/studio/web/assets/createLucideIcon-CzW9508A.js +0 -1
  211. package/studio/web/assets/cynefin-OW5HDTMX-BbdbCvub.js +0 -1
  212. package/studio/web/assets/cynefinDiagram-5FMLGOSQ-TP-aIqbt.js +0 -62
  213. package/studio/web/assets/cytoscape.esm-C2x7inlt.js +0 -321
  214. package/studio/web/assets/dagre-GXQ25YYZ-DShnGpGo.js +0 -4
  215. package/studio/web/assets/dagre-PrKaheQc.js +0 -1
  216. package/studio/web/assets/diagram-UQ7AKVKN-DglXtQ6x.js +0 -41
  217. package/studio/web/assets/dialog-Cn2uWgD4.js +0 -1
  218. package/studio/web/assets/download-B5T5r7ss.js +0 -1
  219. package/studio/web/assets/editor.worker-DwcOiOeP.js +0 -30
  220. package/studio/web/assets/eventmodeling-NTZA5JFV-CLxnp2CR.js +0 -1
  221. package/studio/web/assets/flowDiagram-HODETNUW-BIbhmz9f.js +0 -1
  222. package/studio/web/assets/gitGraph-4MIJSDKK-D2s2w8lE.js +0 -1
  223. package/studio/web/assets/graphlib-DS17s2tU.js +0 -1
  224. package/studio/web/assets/index-7RMEgVG1.css +0 -1
  225. package/studio/web/assets/index-Dfpeofdu.js +0 -824
  226. package/studio/web/assets/index.lazy-B1VOIv-t.js +0 -2
  227. package/studio/web/assets/info-A6RAGUB7-DYjkvb0C.js +0 -1
  228. package/studio/web/assets/infoDiagram-27XIBGKW-Bnp1FJE5.js +0 -2
  229. package/studio/web/assets/json.worker-fO_hOLCP.js +0 -62
  230. package/studio/web/assets/languageServices-IKH4GUHl.js +0 -1
  231. package/studio/web/assets/linear-Cnt8506Q.js +0 -1
  232. package/studio/web/assets/mermaid.core-BlkGaMIH.js +0 -44
  233. package/studio/web/assets/packet-AYTQ26CC-Bi3V04Zi.js +0 -1
  234. package/studio/web/assets/pie-WAS4IAKB-_6DoDbng.js +0 -1
  235. package/studio/web/assets/profile-Q4-T6c-S.js +0 -1
  236. package/studio/web/assets/radar-RG4KPBEZ-DDdVczcL.js +0 -1
  237. package/studio/web/assets/railroad-74A4TZTK-BJUP4Jds.js +0 -1
  238. package/studio/web/assets/railroad-abnf-HS5TGJTU-Bm3L1L0h.js +0 -1
  239. package/studio/web/assets/railroad-ebnf-LZEXJU2U-CKzLGlkw.js +0 -1
  240. package/studio/web/assets/railroad-peg-WCYAUIDC-S8xLjslx.js +0 -1
  241. package/studio/web/assets/regions-CtkV0xje.js +0 -1
  242. package/studio/web/assets/sankeyDiagram-P5KCCOFB-0vSOdymH.js +0 -40
  243. package/studio/web/assets/sequenceDiagram-WJ2MYXX4-hETizDWE.js +0 -162
  244. package/studio/web/assets/setComponentFile-ZWLcWv5X.js +0 -1
  245. package/studio/web/assets/sizeCapture-INFHLROL-B0uUizjq.js +0 -1
  246. package/studio/web/assets/stateDiagram-D77RDMKH-CdYQ_KtC.js +0 -1
  247. package/studio/web/assets/stateDiagram-v2-MP3YSRHH-CdKuzQMT.js +0 -1
  248. package/studio/web/assets/status--aNm8isn.js +0 -61
  249. package/studio/web/assets/swimlanes-42K2YHIH-B8cHIpU4.js +0 -1
  250. package/studio/web/assets/swimlanesDiagram-VR7AAH4N-DmOSJwaH.js +0 -8
  251. package/studio/web/assets/timeline-definition-24CTP7MA-BJWYSXqF.js +0 -120
  252. package/studio/web/assets/toggleHighContrast-Cq_lt3XD.js +0 -49
  253. package/studio/web/assets/treeView-Q6P3EWNA-qxe_v6CQ.js +0 -1
  254. package/studio/web/assets/treemap-WGGIJYW6-dDo97XXF.js +0 -1
  255. package/studio/web/assets/useLocalStorage-BqMR3D8_.js +0 -1
  256. package/studio/web/assets/vendor-core-c2JRRJpV.js +0 -58
  257. package/studio/web/assets/vendor-datadog-CLUcJXOo.js +0 -6
  258. package/studio/web/assets/vendor-react-CJV_K1u4.js +0 -9
  259. package/studio/web/assets/vendor-tanstack-DxzraizX.js +0 -1
  260. package/studio/web/assets/vendor-ui-BUjK0h8a.js +0 -41
  261. package/studio/web/assets/vennDiagram-4TSXK5OY-A3i-lCdl.js +0 -34
  262. package/studio/web/assets/wardley-WFR3VGLG-B0ik-_6g.js +0 -1
  263. package/studio/web/assets/x-DIzaLEdK.js +0 -1
  264. package/studio/web/assets/yaml.worker-BDL8_iuk.js +0 -454
@@ -1,19 +1,19 @@
1
- import{r as e,t}from"./rolldown-runtime-hePW80VL.js";import{S as n,_ as r,a as i,b as a,c as o,d as s,f as c,g as l,h as u,l as d,m as f,n as p,o as m,p as h,r as g,s as _,t as v,v as y,x as b,y as x}from"./vendor-core-c2JRRJpV.js";import{i as S,t as C}from"./button-BIsUKRZq.js";import{a as ee}from"./vendor-datadog-CLUcJXOo.js";import{r as te}from"./vendor-react-CJV_K1u4.js";import{L as ne,k as re,q as ie,z as ae}from"./vendor-tanstack-DxzraizX.js";import{n as oe}from"./setSessionStorage-B0bf71m4.js";import{It as se}from"./vendor-ui-BUjK0h8a.js";import{t as w}from"./createLucideIcon-CzW9508A.js";import{n as ce,r as le,t as ue}from"./chevron-up-DtKGqDn3.js";import{c as de,f as fe,g as pe,h as me,i as he,l as ge,m as _e,p as ve,r as ye,t as be,u as xe}from"./setComponentFile-ZWLcWv5X.js";import{t as Se}from"./x-DIzaLEdK.js";import{n as Ce}from"./setLocalStorage-D_kflv4U.js";import{t as we}from"./useLocalStorage-BqMR3D8_.js";import{An as Te,Dr as Ee,En as De,H as Oe,It as ke,Mr as Ae,Mt as je,Nt as Me,Or as Ne,Pt as Pe,Tr as Fe,V as Ie,Z as Le,br as Re,c as ze,cr as Be,d as Ve,f as He,fr as Ue,ft as We,hr as Ge,in as Ke,m as qe,or as Je,ur as Ye,ut as Xe,yr as Ze,yt as Qe}from"./index-Dfpeofdu.js";import{t as $e}from"./useEntityRestURL-RZhaY8Rn.js";import{n as et,t as tt}from"./FloatingChat-omlNMDcJ.js";import{n as nt}from"./getAnalytics-GHK8ORfM.js";var rt=w(`between-horizontal-start`,[[`rect`,{width:`13`,height:`7`,x:`8`,y:`3`,rx:`1`,key:`pkso9a`}],[`path`,{d:`m2 9 3 3-3 3`,key:`1agib5`}],[`rect`,{width:`13`,height:`7`,x:`8`,y:`14`,rx:`1`,key:`1q5fc1`}]]),it=w(`book`,[[`path`,{d:`M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20`,key:`k3hazp`}]]),at=w(`chart-area`,[[`path`,{d:`M3 3v16a2 2 0 0 0 2 2h16`,key:`c24i48`}],[`path`,{d:`M7 11.207a.5.5 0 0 1 .146-.353l2-2a.5.5 0 0 1 .708 0l3.292 3.292a.5.5 0 0 0 .708 0l4.292-4.292a.5.5 0 0 1 .854.353V16a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1z`,key:`q0gr47`}]]),ot=w(`circle-x`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m15 9-6 6`,key:`1uzhvr`}],[`path`,{d:`m9 9 6 6`,key:`z0biqf`}]]),st=w(`file-pen`,[[`path`,{d:`M12.659 22H18a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v9.34`,key:`o6klzx`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M10.378 12.622a1 1 0 0 1 3 3.003L8.36 20.637a2 2 0 0 1-.854.506l-2.867.837a.5.5 0 0 1-.62-.62l.836-2.869a2 2 0 0 1 .506-.853z`,key:`zhnas1`}]]),ct=w(`logs`,[[`path`,{d:`M3 5h1`,key:`1mv5vm`}],[`path`,{d:`M3 12h1`,key:`lp3yf2`}],[`path`,{d:`M3 19h1`,key:`w6f3n9`}],[`path`,{d:`M8 5h1`,key:`1nxr5w`}],[`path`,{d:`M8 12h1`,key:`1con00`}],[`path`,{d:`M8 19h1`,key:`k7p10e`}],[`path`,{d:`M13 5h8`,key:`a7qcls`}],[`path`,{d:`M13 12h8`,key:`h98zly`}],[`path`,{d:`M13 19h8`,key:`c3s6r1`}]]),lt=w(`message-square-heart`,[[`path`,{d:`M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z`,key:`18887p`}],[`path`,{d:`M7.5 9.5c0 .687.265 1.383.697 1.844l3.009 3.264a1.14 1.14 0 0 0 .407.314 1 1 0 0 0 .783-.004 1.14 1.14 0 0 0 .398-.31l3.008-3.264A2.77 2.77 0 0 0 16.5 9.5 2.5 2.5 0 0 0 12 8a2.5 2.5 0 0 0-4.5 1.5`,key:`1faxuh`}]]),ut=w(`send`,[[`path`,{d:`M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z`,key:`1ffxy3`}],[`path`,{d:`m21.854 2.147-10.94 10.939`,key:`12cjpa`}]]),dt=w(`wrench`,[[`path`,{d:`M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z`,key:`1ngwbx`}]]);async function ft(){await S.delete(`/Chat/Messages/`)}var T=e(ee(),1),E=te();function pt({setMessages:e}){let[t,n]=(0,T.useState)(!1),r=(0,T.useCallback)(async()=>{if(!t){n(!0);try{await ft(),e([])}catch(e){console.error(`Failed to clear chat:`,e)}finally{n(!1)}}},[t,e]);return(0,E.jsxs)(`button`,{type:`button`,className:`clear-chat-button gap-1`,onClick:r,disabled:t,title:`Clear chat`,children:[t?(0,E.jsx)(Ze,{className:`animate-spin`,size:18}):(0,E.jsx)(Ye,{size:18}),`Clear`]})}async function mt(){let{data:e}=await S.get(`/Chat/Messages/`);return e}var ht=`vercel.ai.error`,gt=Symbol.for(ht),_t,vt,D=class e extends (vt=Error,_t=gt,vt){constructor({name:e,message:t,cause:n}){super(t),this[_t]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,ht)}static hasMarker(e,t){let n=Symbol.for(t);return typeof e==`object`&&!!e&&n in e&&typeof e[n]==`boolean`&&e[n]===!0}};function yt(e){return e==null?`unknown error`:typeof e==`string`?e:e instanceof Error?e.toString():JSON.stringify(e)}var bt=`AI_InvalidArgumentError`,xt=`vercel.ai.error.${bt}`,St=Symbol.for(xt),Ct,wt,Tt=class extends (wt=D,Ct=St,wt){constructor({message:e,cause:t,argument:n}){super({name:bt,message:e,cause:t}),this[Ct]=!0,this.argument=n}static isInstance(e){return D.hasMarker(e,xt)}},Et=`AI_JSONParseError`,Dt=`vercel.ai.error.${Et}`,Ot=Symbol.for(Dt),kt,At,jt=class extends (At=D,kt=Ot,At){constructor({text:e,cause:t}){super({name:Et,message:`JSON parsing failed: Text: ${e}.
2
- Error message: ${yt(t)}`,cause:t}),this[kt]=!0,this.text=e}static isInstance(e){return D.hasMarker(e,Dt)}},Mt=`AI_TypeValidationError`,Nt=`vercel.ai.error.${Mt}`,Pt=Symbol.for(Nt),Ft,It,O=class e extends (It=D,Ft=Pt,It){constructor({value:e,cause:t,context:n}){let r=`Type validation failed`;if(n?.field&&(r+=` for ${n.field}`),n?.entityName||n?.entityId){r+=` (`;let e=[];n.entityName&&e.push(n.entityName),n.entityId&&e.push(`id: "${n.entityId}"`),r+=e.join(`, `),r+=`)`}super({name:Mt,message:`${r}: Value: ${JSON.stringify(e)}.
3
- Error message: ${yt(t)}`,cause:t}),this[Ft]=!0,this.value=e,this.context=n}static isInstance(e){return D.hasMarker(e,Nt)}static wrap({value:t,cause:n,context:r}){return e.isInstance(n)&&n.value===t&&n.context?.field===r?.field&&n.context?.entityName===r?.entityName&&n.context?.entityId===r?.entityId?n:new e({value:t,cause:n,context:r})}},Lt=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}},Rt=10,zt=13,k=32;function Bt(e){}function Vt(e){if(typeof e==`function`)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=Bt,onError:n=Bt,onRetry:r=Bt,onComment:i,maxBufferSize:a}=e,o=[],s=0,c=!0,l,u=``,d=0,f,p=!1;function m(e){if(p)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),o.length===0){let t=g(e);t!==``&&(o.push(t),s=t.length),h();return}if(e.indexOf(`
4
- `)===-1&&e.indexOf(`\r`)===-1){o.push(e),s+=e.length,h();return}o.push(e);let t=o.join(``);o.length=0,s=0;let n=g(t);n!==``&&(o.push(n),s=n.length),h()}function h(){a!==void 0&&(s+u.length<=a||(p=!0,o.length=0,s=0,l=void 0,u=``,d=0,f=void 0,n(new Lt(`Buffered data exceeded max buffer size of ${a} characters`,{type:`max-buffer-size-exceeded`}))))}function g(e){let n=0;if(e.indexOf(`\r`)===-1){let r=e.indexOf(`
1
+ import{i as e,t}from"./rolldown-runtime-Dd_uD5pT.js";import{S as n,_ as r,a as i,b as a,c as o,d as s,f as c,g as l,h as u,l as d,m as f,n as p,o as m,p as h,r as g,s as _,t as v,v as y,x as b,y as x}from"./vendor-core-BdkdbUek.js";import{i as S,t as C}from"./button-MFP9n8Ck.js";import{a as ee}from"./vendor-datadog-fCQhBHGk.js";import{r as te}from"./vendor-react-izWchTRL.js";import{J as ne,L as re,k as ie,z as ae}from"./vendor-tanstack-CQ1aRjVa.js";import{n as oe}from"./setSessionStorage-B0bf71m4.js";import{It as se}from"./vendor-ui-aE1tHcW7.js";import{t as w}from"./createLucideIcon-bziYxJli.js";import{n as ce,r as le,t as ue}from"./chevron-up-CFe8x5Bp.js";import{c as de,f as fe,h as pe,i as me,l as he,m as ge,p as _e,r as ve,t as ye,u as be}from"./setComponentFile-BavlhfY0.js";import{t as xe}from"./x-vYntCxm4.js";import{n as Se}from"./setLocalStorage-D_kflv4U.js";import{t as Ce}from"./useLocalStorage-BYoZF60G.js";import{Ar as we,Dr as Te,H as Ee,It as De,Mn as Oe,Mt as ke,Nt as Ae,On as je,Pr as Me,Pt as Ne,Sr as Pe,V as Fe,Z as Ie,_n as Le,_r as Re,c as ze,cr as Be,d as Ve,f as He,fr as Ue,ft as We,in as Ge,kr as Ke,m as qe,mr as Je,ur as Ye,ut as Xe,xr as Ze,yt as Qe}from"./index-zZCxAIEb.js";import{t as $e}from"./useEntityRestURL-DSVwev9J.js";import{n as et,t as tt}from"./FloatingChat-BUlsFGMV.js";import{n as nt}from"./getAnalytics-CjthMQqF.js";var rt={name:`between-horizontal-start`,size:24,node:[[`rect`,{width:`13`,height:`7`,x:`8`,y:`3`,rx:`1`,key:`pkso9a`}],[`path`,{d:`m2 9 3 3-3 3`,key:`1agib5`}],[`rect`,{width:`13`,height:`7`,x:`8`,y:`14`,rx:`1`,key:`1q5fc1`}]],aliases:[`between-horizonal-start`]};rt.node;var it=w(rt),at={name:`book`,size:24,node:[[`path`,{d:`M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20`,key:`k3hazp`}]]};at.node;var ot=w(at),st={name:`chart-area`,size:24,node:[[`path`,{d:`M3 3v16a2 2 0 0 0 2 2h16`,key:`c24i48`}],[`path`,{d:`M7 11.207a.5.5 0 0 1 .146-.353l2-2a.5.5 0 0 1 .708 0l3.292 3.292a.5.5 0 0 0 .708 0l4.292-4.292a.5.5 0 0 1 .854.353V16a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1z`,key:`q0gr47`}]],aliases:[`area-chart`]};st.node;var ct=w(st),lt={name:`circle-x`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m15 9-6 6`,key:`1uzhvr`}],[`path`,{d:`m9 9 6 6`,key:`z0biqf`}]],aliases:[`x-circle`]};lt.node;var ut=w(lt),dt={name:`file-pen`,size:24,node:[[`path`,{d:`M12.659 22H18a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v9.34`,key:`o6klzx`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M10.378 12.622a1 1 0 0 1 3 3.003L8.36 20.637a2 2 0 0 1-.854.506l-2.867.837a.5.5 0 0 1-.62-.62l.836-2.869a2 2 0 0 1 .506-.853z`,key:`zhnas1`}]],aliases:[`file-edit`]};dt.node;var ft=w(dt),pt={name:`logs`,size:24,node:[[`path`,{d:`M3 5h1`,key:`1mv5vm`}],[`path`,{d:`M3 12h1`,key:`lp3yf2`}],[`path`,{d:`M3 19h1`,key:`w6f3n9`}],[`path`,{d:`M8 5h1`,key:`1nxr5w`}],[`path`,{d:`M8 12h1`,key:`1con00`}],[`path`,{d:`M8 19h1`,key:`k7p10e`}],[`path`,{d:`M13 5h8`,key:`a7qcls`}],[`path`,{d:`M13 12h8`,key:`h98zly`}],[`path`,{d:`M13 19h8`,key:`c3s6r1`}]]};pt.node;var mt=w(pt),ht={name:`message-square-heart`,size:24,node:[[`path`,{d:`M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z`,key:`18887p`}],[`path`,{d:`M7.5 9.5c0 .687.265 1.383.697 1.844l3.009 3.264a1.14 1.14 0 0 0 .407.314 1 1 0 0 0 .783-.004 1.14 1.14 0 0 0 .398-.31l3.008-3.264A2.77 2.77 0 0 0 16.5 9.5 2.5 2.5 0 0 0 12 8a2.5 2.5 0 0 0-4.5 1.5`,key:`1faxuh`}]]};ht.node;var gt=w(ht),_t={name:`send`,size:24,node:[[`path`,{d:`M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z`,key:`1ffxy3`}],[`path`,{d:`m21.854 2.147-10.94 10.939`,key:`12cjpa`}]]};_t.node;var vt=w(_t),yt={name:`wrench`,size:24,node:[[`path`,{d:`M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z`,key:`1ngwbx`}]]};yt.node;var bt=w(yt);async function xt(){await S.delete(`/Chat/Messages/`)}var T=e(ee(),1),E=te();function St({setMessages:e}){let[t,n]=(0,T.useState)(!1),r=(0,T.useCallback)(async()=>{if(!t){n(!0);try{await xt(),e([])}catch(e){console.error(`Failed to clear chat:`,e)}finally{n(!1)}}},[t,e]);return(0,E.jsxs)(`button`,{type:`button`,className:`clear-chat-button gap-1`,onClick:r,disabled:t,title:`Clear chat`,children:[t?(0,E.jsx)(Ze,{className:`animate-spin`,size:18}):(0,E.jsx)(Ue,{size:18}),`Clear`]})}async function Ct(){let{data:e}=await S.get(`/Chat/Messages/`);return e}var wt=`vercel.ai.error`,Tt=Symbol.for(wt),Et,Dt,D=class e extends (Dt=Error,Et=Tt,Dt){constructor({name:e,message:t,cause:n}){super(t),this[Et]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,wt)}static hasMarker(e,t){let n=Symbol.for(t);return typeof e==`object`&&!!e&&n in e&&typeof e[n]==`boolean`&&e[n]===!0}},Ot=`AI_APICallError`,kt=`vercel.ai.error.${Ot}`,At=Symbol.for(kt),jt,Mt,Nt=class extends (Mt=D,jt=At,Mt){constructor({message:e,url:t,requestBodyValues:n,statusCode:r,responseHeaders:i,responseBody:a,cause:o,isRetryable:s=r!=null&&(r===408||r===409||r===429||r>=500),data:c}){super({name:Ot,message:e,cause:o}),this[jt]=!0,this.url=t,this.requestBodyValues=n,this.statusCode=r,this.responseHeaders=i,this.responseBody=a,this.isRetryable=s,this.data=c}static isInstance(e){return D.hasMarker(e,kt)}},Pt=`AI_EmptyResponseBodyError`,Ft=`vercel.ai.error.${Pt}`,It=Symbol.for(Ft),Lt,Rt,zt=class extends (Rt=D,Lt=It,Rt){constructor({message:e=`Empty response body`}={}){super({name:Pt,message:e}),this[Lt]=!0}static isInstance(e){return D.hasMarker(e,Ft)}};function Bt(e){return e==null?`unknown error`:typeof e==`string`?e:e instanceof Error?e.toString():JSON.stringify(e)}var Vt=`AI_InvalidArgumentError`,Ht=`vercel.ai.error.${Vt}`,Ut=Symbol.for(Ht),Wt,Gt,Kt=class extends (Gt=D,Wt=Ut,Gt){constructor({message:e,cause:t,argument:n}){super({name:Vt,message:e,cause:t}),this[Wt]=!0,this.argument=n}static isInstance(e){return D.hasMarker(e,Ht)}},qt=`AI_JSONParseError`,Jt=`vercel.ai.error.${qt}`,Yt=Symbol.for(Jt),Xt,Zt,Qt=class extends (Zt=D,Xt=Yt,Zt){constructor({text:e,cause:t}){super({name:qt,message:`JSON parsing failed: Text: ${e}.
2
+ Error message: ${Bt(t)}`,cause:t}),this[Xt]=!0,this.text=e}static isInstance(e){return D.hasMarker(e,Jt)}},$t=`AI_TypeValidationError`,en=`vercel.ai.error.${$t}`,tn=Symbol.for(en),nn,rn,O=class e extends (rn=D,nn=tn,rn){constructor({value:e,cause:t,context:n}){let r=`Type validation failed`;if(n?.field&&(r+=` for ${n.field}`),n?.entityName||n?.entityId){r+=` (`;let e=[];n.entityName&&e.push(n.entityName),n.entityId&&e.push(`id: "${n.entityId}"`),r+=e.join(`, `),r+=`)`}super({name:$t,message:`${r}: Value: ${JSON.stringify(e)}.
3
+ Error message: ${Bt(t)}`,cause:t}),this[nn]=!0,this.value=e,this.context=n}static isInstance(e){return D.hasMarker(e,en)}static wrap({value:t,cause:n,context:r}){return e.isInstance(n)&&n.value===t&&n.context?.field===r?.field&&n.context?.entityName===r?.entityName&&n.context?.entityId===r?.entityId?n:new e({value:t,cause:n,context:r})}},an=`AI_UnsupportedFunctionalityError`,on=`vercel.ai.error.${an}`,sn=Symbol.for(on),cn,ln,un=class extends (ln=D,cn=sn,ln){constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:an,message:t}),this[cn]=!0,this.functionality=e}static isInstance(e){return D.hasMarker(e,on)}},dn=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}},fn=10,pn=13,k=32;function mn(e){}function hn(e){if(typeof e==`function`)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=mn,onError:n=mn,onRetry:r=mn,onComment:i,maxBufferSize:a}=e,o=[],s=0,c=!0,l,u=``,d=0,f,p=!1;function m(e){if(p)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),o.length===0){let t=g(e);t!==``&&(o.push(t),s=t.length),h();return}if(e.indexOf(`
4
+ `)===-1&&e.indexOf(`\r`)===-1){o.push(e),s+=e.length,h();return}o.push(e);let t=o.join(``);o.length=0,s=0;let n=g(t);n!==``&&(o.push(n),s=n.length),h()}function h(){a!==void 0&&(s+u.length<=a||(p=!0,o.length=0,s=0,l=void 0,u=``,d=0,f=void 0,n(new dn(`Buffered data exceeded max buffer size of ${a} characters`,{type:`max-buffer-size-exceeded`}))))}function g(e){let n=0;if(e.indexOf(`\r`)===-1){let r=e.indexOf(`
5
5
  `,n);for(;r!==-1;){if(n===r){d>0&&t({id:l,event:f,data:u}),l=void 0,u=``,d=0,f=void 0,n=r+1,r=e.indexOf(`
6
- `,n);continue}let i=e.charCodeAt(n);if(Ht(e,n,i)){let i=e.charCodeAt(n+5)===k?n+6:n+5,a=e.slice(i,r);if(d===0&&e.charCodeAt(r+1)===Rt){t({id:l,event:f,data:a}),l=void 0,u=``,f=void 0,n=r+2,r=e.indexOf(`
6
+ `,n);continue}let i=e.charCodeAt(n);if(gn(e,n,i)){let i=e.charCodeAt(n+5)===k?n+6:n+5,a=e.slice(i,r);if(d===0&&e.charCodeAt(r+1)===fn){t({id:l,event:f,data:a}),l=void 0,u=``,f=void 0,n=r+2,r=e.indexOf(`
7
7
  `,n);continue}u=d===0?a:`${u}
8
- ${a}`,d++}else Ut(e,n,i)?f=e.slice(e.charCodeAt(n+6)===k?n+7:n+6,r)||void 0:_(e,n,r);n=r+1,r=e.indexOf(`
8
+ ${a}`,d++}else _n(e,n,i)?f=e.slice(e.charCodeAt(n+6)===k?n+7:n+6,r)||void 0:_(e,n,r);n=r+1,r=e.indexOf(`
9
9
  `,n)}return e.slice(n)}for(;n<e.length;){let t=e.indexOf(`\r`,n),r=e.indexOf(`
10
- `,n),i=-1;if(t!==-1&&r!==-1?i=t<r?t:r:t===-1?r!==-1&&(i=r):i=t===e.length-1?-1:t,i===-1)break;_(e,n,i),n=i+1,e.charCodeAt(n-1)===zt&&e.charCodeAt(n)===Rt&&n++}return e.slice(n)}function _(e,t,n){if(t===n){y();return}let r=e.charCodeAt(t);if(Ht(e,t,r)){let r=e.charCodeAt(t+5)===k?t+6:t+5,i=e.slice(r,n);u=d===0?i:`${u}
11
- ${i}`,d++;return}if(Ut(e,t,r)){f=e.slice(e.charCodeAt(t+6)===k?t+7:t+6,n)||void 0;return}if(r===105&&e.charCodeAt(t+1)===100&&e.charCodeAt(t+2)===58){let r=e.slice(e.charCodeAt(t+3)===k?t+4:t+3,n);r.includes(`\0`)||(l=r);return}if(r===58){if(i){let r=e.slice(t,n);i(r.slice(e.charCodeAt(t+1)===k?2:1))}return}let a=e.slice(t,n),o=a.indexOf(`:`);if(o===-1){v(a,``,a);return}let s=a.slice(0,o),c=a.charCodeAt(o+1)===k?2:1;v(s,a.slice(o+c),a)}function v(e,t,i){switch(e){case`event`:f=t||void 0;break;case`data`:u=d===0?t:`${u}
12
- ${t}`,d++;break;case`id`:t.includes(`\0`)||(l=t);break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new Lt(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new Lt(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}))}}function y(){d>0&&t({id:l,event:f,data:u}),l=void 0,u=``,d=0,f=void 0}function b(e={}){if(e.consume&&o.length>0){let e=o.join(``);_(e,0,e.length)}c=!0,l=void 0,u=``,d=0,f=void 0,o.length=0,s=0,p=!1}return{feed:m,reset:b}}function Ht(e,t,n){return n===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function Ut(e,t,n){return n===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}var Wt=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n,maxBufferSize:r}={}){let i;super({start(a){i=Vt({onEvent:e=>{a.enqueue(e)},onError(t){typeof e==`function`&&e(t),(e===`terminate`||t.type===`max-buffer-size-exceeded`)&&a.error(t)},onRetry:t,onComment:n,maxBufferSize:r})},transform(e){i.feed(e)}})}};new TextDecoder;var{btoa:Gt,atob:Kt}=globalThis;function A(e){if(e==null)return{};let t={};if(e instanceof Headers)e.forEach((e,n)=>{t[n.toLowerCase()]=e});else{Array.isArray(e)||(e=Object.entries(e));for(let[n,r]of e)r!=null&&(t[n.toLowerCase()]=r)}return t}var qt=globalThis.fetch;Jt(qt);function Jt(e){if(typeof e!=`function`)return!1;let t=Function.prototype.toString.call(e);return t.includes(`internal/deps/undici`)||t.includes(`lazy loading of undici`)}var j=({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new Tt({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`},Yt=j();function Xt(e){return globalThis.Buffer?.isBuffer(e)??!1}var Zt=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,Qt=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function $t(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Zt.test(e)===!1&&Qt.test(e)===!1?t:en(t)}function en(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&n.constructor!==null&&typeof n.constructor==`object`&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function tn(e){let{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return $t(e)}try{return $t(e)}finally{Error.stackTraceLimit=t}}function nn(e){if(e.type===`object`||Array.isArray(e.type)&&e.type.includes(`object`)){let{additionalProperties:t}=e;e.additionalProperties=t!=null&&typeof t!=`boolean`&&M(t);let{properties:n}=e;if(n!=null)for(let e of Object.keys(n))n[e]=M(n[e])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(M):M(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(M)),e.allOf!=null&&(e.allOf=e.allOf.map(M)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(M));let{definitions:t}=e;if(t!=null)for(let e of Object.keys(t))t[e]=M(t[e]);return e}function M(e){return typeof e==`boolean`?e:nn(e)}var rn=Symbol(`Let zodToJsonSchema decide on which parser to use`),an={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`},on=e=>typeof e==`string`?{...an,name:e}:{...an,...e};function N(){return{}}function sn(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==`ZodAny`&&(n.items=L(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&(n.minItems=e.minLength.value),e.maxLength&&(n.maxItems=e.maxLength.value),e.exactLength&&(n.minItems=e.exactLength.value,n.maxItems=e.exactLength.value),n}function cn(e){let t={type:`integer`,format:`int64`};if(!e.checks)return t;for(let n of e.checks)switch(n.kind){case`min`:n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case`max`:n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case`multipleOf`:t.multipleOf=n.value}return t}function ln(){return{type:`boolean`}}function un(e,t){return L(e.type._def,t)}var dn=(e,t)=>L(e.innerType._def,t);function fn(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(n=>fn(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return pn(e)}}var pn=e=>{let t={type:`integer`,format:`unix-time`};for(let n of e.checks)switch(n.kind){case`min`:t.minimum=n.value;break;case`max`:t.maximum=n.value}return t};function mn(e,t){return{...L(e.innerType._def,t),default:e.defaultValue()}}function hn(e,t){return t.effectStrategy===`input`?L(e.schema._def,t):N()}function gn(e){return{type:`string`,enum:Array.from(e.values)}}var _n=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function vn(e,t){let n=[L(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),L(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=[];return n.forEach(e=>{if(_n(e))r.push(...e.allOf);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}r.push(t)}}),r.length?{allOf:r}:void 0}function yn(e){let t=typeof e.value;return t!==`bigint`&&t!==`number`&&t!==`boolean`&&t!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:{type:t===`bigint`?`integer`:t,const:e.value}}var bn=void 0,P={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(bn===void 0&&(bn=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),bn),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,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])$/,ipv4Cidr:/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function xn(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:n.minLength=typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value;break;case`max`:n.maxLength=typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value;break;case`email`:switch(t.emailStrategy){case`format:email`:F(n,`email`,r.message,t);break;case`format:idn-email`:F(n,`idn-email`,r.message,t);break;case`pattern:zod`:I(n,P.email,r.message,t)}break;case`url`:F(n,`uri`,r.message,t);break;case`uuid`:F(n,`uuid`,r.message,t);break;case`regex`:I(n,r.regex,r.message,t);break;case`cuid`:I(n,P.cuid,r.message,t);break;case`cuid2`:I(n,P.cuid2,r.message,t);break;case`startsWith`:I(n,RegExp(`^${Sn(r.value,t)}`),r.message,t);break;case`endsWith`:I(n,RegExp(`${Sn(r.value,t)}$`),r.message,t);break;case`datetime`:F(n,`date-time`,r.message,t);break;case`date`:F(n,`date`,r.message,t);break;case`time`:F(n,`time`,r.message,t);break;case`duration`:F(n,`duration`,r.message,t);break;case`length`:n.minLength=typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,n.maxLength=typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value;break;case`includes`:I(n,RegExp(Sn(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&F(n,`ipv4`,r.message,t),r.version!==`v4`&&F(n,`ipv6`,r.message,t);break;case`base64url`:I(n,P.base64url,r.message,t);break;case`jwt`:I(n,P.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&I(n,P.ipv4Cidr,r.message,t),r.version!==`v4`&&I(n,P.ipv6Cidr,r.message,t);break;case`emoji`:I(n,P.emoji(),r.message,t);break;case`ulid`:I(n,P.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:F(n,`binary`,r.message,t);break;case`contentEncoding:base64`:n.contentEncoding=`base64`;break;case`pattern:zod`:I(n,P.base64,r.message,t)}break;case`nanoid`:I(n,P.nanoid,r.message,t)}return n}function Sn(e,t){return t.patternStrategy===`escape`?wn(e):e}var Cn=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function wn(e){let t=``;for(let n=0;n<e.length;n++)Cn.has(e[n])||(t+=`\\`),t+=e[n];return t}function F(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):e.format=t}function I(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:Tn(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=Tn(t,r)}function Tn(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
10
+ `,n),i=-1;if(t!==-1&&r!==-1?i=t<r?t:r:t===-1?r!==-1&&(i=r):i=t===e.length-1?-1:t,i===-1)break;_(e,n,i),n=i+1,e.charCodeAt(n-1)===pn&&e.charCodeAt(n)===fn&&n++}return e.slice(n)}function _(e,t,n){if(t===n){y();return}let r=e.charCodeAt(t);if(gn(e,t,r)){let r=e.charCodeAt(t+5)===k?t+6:t+5,i=e.slice(r,n);u=d===0?i:`${u}
11
+ ${i}`,d++;return}if(_n(e,t,r)){f=e.slice(e.charCodeAt(t+6)===k?t+7:t+6,n)||void 0;return}if(r===105&&e.charCodeAt(t+1)===100&&e.charCodeAt(t+2)===58){let r=e.slice(e.charCodeAt(t+3)===k?t+4:t+3,n);r.includes(`\0`)||(l=r);return}if(r===58){if(i){let r=e.slice(t,n);i(r.slice(e.charCodeAt(t+1)===k?2:1))}return}let a=e.slice(t,n),o=a.indexOf(`:`);if(o===-1){v(a,``,a);return}let s=a.slice(0,o),c=a.charCodeAt(o+1)===k?2:1;v(s,a.slice(o+c),a)}function v(e,t,i){switch(e){case`event`:f=t||void 0;break;case`data`:u=d===0?t:`${u}
12
+ ${t}`,d++;break;case`id`:t.includes(`\0`)||(l=t);break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new dn(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new dn(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}))}}function y(){d>0&&t({id:l,event:f,data:u}),l=void 0,u=``,d=0,f=void 0}function b(e={}){if(e.consume&&o.length>0){let e=o.join(``);_(e,0,e.length)}c=!0,l=void 0,u=``,d=0,f=void 0,o.length=0,s=0,p=!1}return{feed:m,reset:b}}function gn(e,t,n){return n===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function _n(e,t,n){return n===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}var vn=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n,maxBufferSize:r}={}){let i;super({start(a){i=hn({onEvent:e=>{a.enqueue(e)},onError(t){typeof e==`function`&&e(t),(e===`terminate`||t.type===`max-buffer-size-exceeded`)&&a.error(t)},onRetry:t,onComment:n,maxBufferSize:r})},transform(e){i.feed(e)}})}};new TextDecoder;var{btoa:yn,atob:bn}=globalThis;function A(e){if(e==null)return{};let t={};if(e instanceof Headers)e.forEach((e,n)=>{t[n.toLowerCase()]=e});else{Array.isArray(e)||(e=Object.entries(e));for(let[n,r]of e)r!=null&&(t[n.toLowerCase()]=r)}return t}var j=({prefix:e,size:t=16,alphabet:n=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:r=`-`}={})=>{let i=()=>{let e=n.length,r=Array(t);for(let i=0;i<t;i++)r[i]=n[Math.random()*e|0];return r.join(``)};if(e==null)return i;if(n.includes(r))throw new Kt({argument:`separator`,message:`The separator "${r}" must not be part of the alphabet "${n}".`});return()=>`${e}${r}${i()}`},xn=j();function Sn(e){return globalThis.Buffer?.isBuffer(e)??!1}var Cn=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,wn=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function Tn(e){let t=JSON.parse(e);return typeof t!=`object`||!t||Cn.test(e)===!1&&wn.test(e)===!1?t:En(t)}function En(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&n.constructor!==null&&typeof n.constructor==`object`&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function Dn(e){let{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return Tn(e)}try{return Tn(e)}finally{Error.stackTraceLimit=t}}function On(e){if(e.type===`object`||Array.isArray(e.type)&&e.type.includes(`object`)){let{additionalProperties:t}=e;e.additionalProperties=t!=null&&typeof t!=`boolean`&&M(t);let{properties:n}=e;if(n!=null)for(let e of Object.keys(n))n[e]=M(n[e])}e.items!=null&&(e.items=Array.isArray(e.items)?e.items.map(M):M(e.items)),e.anyOf!=null&&(e.anyOf=e.anyOf.map(M)),e.allOf!=null&&(e.allOf=e.allOf.map(M)),e.oneOf!=null&&(e.oneOf=e.oneOf.map(M));let{definitions:t}=e;if(t!=null)for(let e of Object.keys(t))t[e]=M(t[e]);return e}function M(e){return typeof e==`boolean`?e:On(e)}var kn=Symbol(`Let zodToJsonSchema decide on which parser to use`),An={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`},jn=e=>typeof e==`string`?{...An,name:e}:{...An,...e};function N(){return{}}function Mn(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==`ZodAny`&&(n.items=L(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&(n.minItems=e.minLength.value),e.maxLength&&(n.maxItems=e.maxLength.value),e.exactLength&&(n.minItems=e.exactLength.value,n.maxItems=e.exactLength.value),n}function Nn(e){let t={type:`integer`,format:`int64`};if(!e.checks)return t;for(let n of e.checks)switch(n.kind){case`min`:n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case`max`:n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case`multipleOf`:t.multipleOf=n.value}return t}function Pn(){return{type:`boolean`}}function Fn(e,t){return L(e.type._def,t)}var In=(e,t)=>L(e.innerType._def,t);function Ln(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(n=>Ln(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return Rn(e)}}var Rn=e=>{let t={type:`integer`,format:`unix-time`};for(let n of e.checks)switch(n.kind){case`min`:t.minimum=n.value;break;case`max`:t.maximum=n.value}return t};function zn(e,t){return{...L(e.innerType._def,t),default:e.defaultValue()}}function Bn(e,t){return t.effectStrategy===`input`?L(e.schema._def,t):N()}function Vn(e){return{type:`string`,enum:Array.from(e.values)}}var Hn=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Un(e,t){let n=[L(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),L(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=[];return n.forEach(e=>{if(Hn(e))r.push(...e.allOf);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}r.push(t)}}),r.length?{allOf:r}:void 0}function Wn(e){let t=typeof e.value;return t!==`bigint`&&t!==`number`&&t!==`boolean`&&t!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:{type:t===`bigint`?`integer`:t,const:e.value}}var Gn=void 0,P={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Gn===void 0&&(Gn=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),Gn),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,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])$/,ipv4Cidr:/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Kn(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:n.minLength=typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value;break;case`max`:n.maxLength=typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value;break;case`email`:switch(t.emailStrategy){case`format:email`:F(n,`email`,r.message,t);break;case`format:idn-email`:F(n,`idn-email`,r.message,t);break;case`pattern:zod`:I(n,P.email,r.message,t)}break;case`url`:F(n,`uri`,r.message,t);break;case`uuid`:F(n,`uuid`,r.message,t);break;case`regex`:I(n,r.regex,r.message,t);break;case`cuid`:I(n,P.cuid,r.message,t);break;case`cuid2`:I(n,P.cuid2,r.message,t);break;case`startsWith`:I(n,RegExp(`^${qn(r.value,t)}`),r.message,t);break;case`endsWith`:I(n,RegExp(`${qn(r.value,t)}$`),r.message,t);break;case`datetime`:F(n,`date-time`,r.message,t);break;case`date`:F(n,`date`,r.message,t);break;case`time`:F(n,`time`,r.message,t);break;case`duration`:F(n,`duration`,r.message,t);break;case`length`:n.minLength=typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,n.maxLength=typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value;break;case`includes`:I(n,RegExp(qn(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&F(n,`ipv4`,r.message,t),r.version!==`v4`&&F(n,`ipv6`,r.message,t);break;case`base64url`:I(n,P.base64url,r.message,t);break;case`jwt`:I(n,P.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&I(n,P.ipv4Cidr,r.message,t),r.version!==`v4`&&I(n,P.ipv6Cidr,r.message,t);break;case`emoji`:I(n,P.emoji(),r.message,t);break;case`ulid`:I(n,P.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:F(n,`binary`,r.message,t);break;case`contentEncoding:base64`:n.contentEncoding=`base64`;break;case`pattern:zod`:I(n,P.base64,r.message,t)}break;case`nanoid`:I(n,P.nanoid,r.message,t)}return n}function qn(e,t){return t.patternStrategy===`escape`?Yn(e):e}var Jn=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Yn(e){let t=``;for(let n=0;n<e.length;n++)Jn.has(e[n])||(t+=`\\`),t+=e[n];return t}function F(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):e.format=t}function I(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:Xn(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=Xn(t,r)}function Xn(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
13
13
  ]))`;continue}if(r[e]===`$`){i+=`($|(?=[\r
14
14
  ]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r
15
15
  `:`[${r[e]}\r
16
- ]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function En(e,t){let n={type:`object`,additionalProperties:L(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(e.keyType?._def.typeName===`ZodString`&&e.keyType._def.checks?.length){let{type:r,...i}=xn(e.keyType._def,t);return{...n,propertyNames:i}}if(e.keyType?._def.typeName===`ZodEnum`)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===`ZodBranded`&&e.keyType._def.type._def.typeName===`ZodString`&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=un(e.keyType._def,t);return{...n,propertyNames:i}}return n}function Dn(e,t){return t.mapStrategy===`record`?En(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[L(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||N(),L(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||N()],minItems:2,maxItems:2}}}function On(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function kn(){return{not:N()}}function An(){return{type:`null`}}var jn={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function Mn(e,t){let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in jn&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=jn[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return Nn(e,t)}var Nn=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>L(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function Pn(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[jn[e.innerType._def.typeName],`null`]};let n=L(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function Fn(e){let t={type:`number`};if(!e.checks)return t;for(let n of e.checks)switch(n.kind){case`int`:t.type=`integer`;break;case`min`:n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case`max`:n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case`multipleOf`:t.multipleOf=n.value}return t}function In(e,t){let n={type:`object`,properties:{}},r=[],i=e.shape();for(let e in i){let a=i[e];if(a===void 0||a._def===void 0)continue;let o=Rn(a),s=L(a._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});s!==void 0&&(n.properties[e]=s,o||r.push(e))}r.length&&(n.required=r);let a=Ln(e,t);return a!==void 0&&(n.additionalProperties=a),n}function Ln(e,t){if(e.catchall._def.typeName!==`ZodNever`)return L(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function Rn(e){try{return e.isOptional()}catch{return!0}}var zn=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return L(e.innerType._def,t);let n=L(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:N()},n]}:N()},Bn=(e,t)=>{if(t.pipeStrategy===`input`)return L(e.in._def,t);if(t.pipeStrategy===`output`)return L(e.out._def,t);let n=L(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,L(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function Vn(e,t){return L(e.type._def,t)}function Hn(e,t){let n={type:`array`,uniqueItems:!0,items:L(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&(n.minItems=e.minSize.value),e.maxSize&&(n.maxItems=e.maxSize.value),n}function Un(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>L(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:L(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>L(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function Wn(){return{not:N()}}function Gn(){return N()}var Kn=(e,t)=>L(e.innerType._def,t),qn=(e,t,n)=>{switch(t){case`ZodString`:return xn(e,n);case`ZodNumber`:return Fn(e);case`ZodObject`:return In(e,n);case`ZodBigInt`:return cn(e);case`ZodBoolean`:return ln();case`ZodDate`:return fn(e,n);case`ZodUndefined`:return Wn();case`ZodNull`:return An();case`ZodArray`:return sn(e,n);case`ZodUnion`:case`ZodDiscriminatedUnion`:return Mn(e,n);case`ZodIntersection`:return vn(e,n);case`ZodTuple`:return Un(e,n);case`ZodRecord`:return En(e,n);case`ZodLiteral`:return yn(e);case`ZodEnum`:return gn(e);case`ZodNativeEnum`:return On(e);case`ZodNullable`:return Pn(e,n);case`ZodOptional`:return zn(e,n);case`ZodMap`:return Dn(e,n);case`ZodSet`:return Hn(e,n);case`ZodLazy`:return()=>e.getter()._def;case`ZodPromise`:return Vn(e,n);case`ZodNaN`:case`ZodNever`:return kn();case`ZodEffects`:return hn(e,n);case`ZodAny`:return N();case`ZodUnknown`:return Gn();case`ZodDefault`:return mn(e,n);case`ZodBranded`:return un(e,n);case`ZodReadonly`:return Kn(e,n);case`ZodCatch`:return dn(e,n);case`ZodPipeline`:return Bn(e,n);case`ZodFunction`:case`ZodVoid`:case`ZodSymbol`:return;default:return(e=>void 0)(t)}},Jn=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function L(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.call(t,e,t,r,n);if(i!==rn)return i}if(r&&!n){let e=Yn(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=qn(e,e.typeName,t),o=typeof a==`function`?L(a(),t):a;if(o&&Xn(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var Yn=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:Jn(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),N()):t.$refStrategy===`seen`?N():void 0}},Xn=(e,t,n)=>(e.description&&(n.description=e.description),n),Zn=e=>{let t=on(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}},Qn=(e,t)=>{let n=Zn(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:L(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??N()}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=L(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??N(),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o);let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return s.$schema=`http://json-schema.org/draft-07/schema#`,s},$n=Symbol.for(`vercel.ai.schema`);function er(e){let t;return()=>(t??=e(),t)}function tr(e,{validate:t}={}){return{[$n]:!0,_type:void 0,get jsonSchema(){return typeof e==`function`&&(e=e()),e},validate:t}}function nr(e){return typeof e==`object`&&!!e&&$n in e&&e[$n]===!0&&`jsonSchema`in e&&`validate`in e}function rr(e){return e==null?tr({type:`object`,properties:{},additionalProperties:!1}):nr(e)?e:`~standard`in e?e[`~standard`].vendor===`zod`?lr(e):ir(e):e()}function ir(e){return tr(()=>{if(!ar(e))throw Error(`Standard schema vendor '${e[`~standard`].vendor}' does not support JSON Schema conversion.`);return nn(e[`~standard`].jsonSchema.input({target:`draft-07`}))},{validate:async t=>{let n=await e[`~standard`].validate(t);return`value`in n?{success:!0,value:n.value}:{success:!1,error:new O({value:t,cause:n.issues})}}})}function ar(e){return e[`~standard`].jsonSchema!=null}function or(e,t){let n=t?.useReferences??!1;return tr(()=>Qn(e,{$refStrategy:n?`root`:`none`}),{validate:async t=>{let n=await e.safeParseAsync(t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}function sr(e,t){let r=t?.useReferences??!1;return tr(()=>nn(n(e,{target:`draft-7`,io:`input`,reused:r?`ref`:`inline`})),{validate:async t=>{let n=await b(e,t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}function cr(e){return`_zod`in e}function lr(e,t){return cr(e)?sr(e,t):or(e,t)}async function ur({value:e,schema:t,context:n}){let r=await dr({value:e,schema:t,context:n});if(!r.success)throw O.wrap({value:e,cause:r.error,context:n});return r.value}async function dr({value:e,schema:t,context:n}){let r=rr(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};let t=await r.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:O.wrap({value:e,cause:t.error,context:n}),rawValue:e}}catch(t){return{success:!1,error:O.wrap({value:e,cause:t,context:n}),rawValue:e}}}async function R({text:e,schema:t}){try{let n=tn(e);return t==null?{success:!0,value:n,rawValue:n}:await dr({value:n,schema:t})}catch(t){return{success:!1,error:jt.isInstance(t)?t:new jt({text:e,cause:t}),rawValue:void 0}}}function fr({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Wt).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await R({text:e,schema:t}))}}))}async function z(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}new TextDecoder;var pr=Object.defineProperty,mr=(e,t)=>{for(var n in t)pr(e,n,{get:t[n],enumerable:!0})},hr=`AI_InvalidArgumentError`,gr=`vercel.ai.error.${hr}`,_r=Symbol.for(gr),vr,yr,br=class extends (yr=D,vr=_r,yr){constructor({parameter:e,value:t,message:n}){super({name:hr,message:`Invalid argument for parameter ${e}: ${n}`}),this[vr]=!0,this.parameter=e,this.value=t}static isInstance(e){return D.hasMarker(e,gr)}},xr=`AI_NoObjectGeneratedError`,Sr=`vercel.ai.error.${xr}`,Cr=Symbol.for(Sr),wr,Tr,B=class extends (Tr=D,wr=Cr,Tr){constructor({message:e=`No object generated.`,cause:t,text:n,response:r,usage:i,finishReason:a}){super({name:xr,message:e,cause:t}),this[wr]=!0,this.text=n,this.response=r,this.usage=i,this.finishReason=a}static isInstance(e){return D.hasMarker(e,Sr)}},Er=`AI_UIMessageStreamError`,Dr=`vercel.ai.error.${Er}`,Or=Symbol.for(Dr),kr,Ar,V=class extends (Ar=D,kr=Or,Ar){constructor({chunkType:e,chunkId:t,message:n}){super({name:Er,message:n}),this[kr]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return D.hasMarker(e,Dr)}};function jr(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;let n={...e};for(let r in t)if(r!==`__proto__`&&r!==`constructor`&&r!==`prototype`&&Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(i===void 0)continue;let a=r in e?e[r]:void 0,o=typeof i==`object`&&!!i&&!Array.isArray(i)&&!(i instanceof Date)&&!(i instanceof RegExp),s=typeof a==`object`&&!!a&&!Array.isArray(a)&&!(a instanceof Date)&&!(a instanceof RegExp);n[r]=o&&s?jr(a,i):i}return n}var H={array:m,boolean:_,custom:o,discriminatedUnion:d,enum:v,instanceof:p,lazy:s,literal:c,looseObject:h,never:f,null:g,number:u,object:l,record:r,string:y,union:x,unknown:a},U=H.lazy(()=>H.union([H.null(),H.string(),H.number(),H.boolean(),H.record(H.string(),U.optional()),H.array(U)])),W=H.record(H.string(),H.record(H.string(),U.optional())),Mr=H.union([H.string(),H.instanceof(Uint8Array),H.instanceof(ArrayBuffer),H.custom(Xt,{message:`Must be a Buffer`})]),Nr=H.record(H.string(),H.string()),Pr=H.object({type:H.literal(`text`),text:H.string(),providerOptions:W.optional()}),Fr=H.object({type:H.literal(`image`),image:H.union([Mr,H.instanceof(URL),Nr]),mediaType:H.string().optional(),providerOptions:W.optional()}),Ir=H.discriminatedUnion(`type`,[H.object({type:H.literal(`data`),data:Mr}),H.object({type:H.literal(`url`),url:H.instanceof(URL)}),H.object({type:H.literal(`reference`),reference:Nr}),H.object({type:H.literal(`text`),text:H.string()})]),Lr=H.discriminatedUnion(`type`,[H.object({type:H.literal(`data`),data:Mr}),H.object({type:H.literal(`url`),url:H.instanceof(URL)})]),Rr=H.object({type:H.literal(`file`),data:H.union([Ir,Mr,H.instanceof(URL),Nr]),filename:H.string().optional(),mediaType:H.string(),providerOptions:W.optional()}),zr=H.object({type:H.literal(`reasoning`),text:H.string(),providerOptions:W.optional()}),Br=H.object({type:H.literal(`custom`),kind:H.string().transform(e=>e),providerOptions:W.optional()}),Vr=H.object({type:H.literal(`reasoning-file`),data:H.union([Lr,Mr,H.instanceof(URL)]),mediaType:H.string(),providerOptions:W.optional()}),Hr=H.object({type:H.literal(`tool-call`),toolCallId:H.string(),toolName:H.string(),input:H.unknown(),providerOptions:W.optional(),providerExecuted:H.boolean().optional()}),Ur=H.discriminatedUnion(`type`,[H.object({type:H.literal(`text`),value:H.string(),providerOptions:W.optional()}),H.object({type:H.literal(`json`),value:U,providerOptions:W.optional()}),H.object({type:H.literal(`execution-denied`),reason:H.string().optional(),providerOptions:W.optional()}),H.object({type:H.literal(`error-text`),value:H.string(),providerOptions:W.optional()}),H.object({type:H.literal(`error-json`),value:U,providerOptions:W.optional()}),H.object({type:H.literal(`content`),value:H.array(H.union([H.object({type:H.literal(`text`),text:H.string(),providerOptions:W.optional()}),H.object({type:H.literal(`file`),data:Ir,mediaType:H.string(),filename:H.string().optional(),providerOptions:W.optional()}),H.object({type:H.literal(`file-data`),data:H.string(),mediaType:H.string(),filename:H.string().optional(),providerOptions:W.optional()}),H.object({type:H.literal(`file-url`),url:H.string(),mediaType:H.string().optional(),providerOptions:W.optional()}),H.object({type:H.literal(`file-id`),fileId:H.union([H.string(),H.record(H.string(),H.string())]),providerOptions:W.optional()}),H.object({type:H.literal(`file-reference`),providerReference:H.record(H.string(),H.string()),providerOptions:W.optional()}),H.object({type:H.literal(`image-data`),data:H.string(),mediaType:H.string(),providerOptions:W.optional()}),H.object({type:H.literal(`image-url`),url:H.string(),providerOptions:W.optional()}),H.object({type:H.literal(`image-file-id`),fileId:H.union([H.string(),H.record(H.string(),H.string())]),providerOptions:W.optional()}),H.object({type:H.literal(`image-file-reference`),providerReference:H.record(H.string(),H.string()),providerOptions:W.optional()}),H.object({type:H.literal(`custom`),providerOptions:W.optional()})]))})]),Wr=H.object({type:H.literal(`tool-result`),toolCallId:H.string(),toolName:H.string(),output:Ur,providerOptions:W.optional()}),Gr=H.object({type:H.literal(`tool-approval-request`),approvalId:H.string(),toolCallId:H.string(),reason:H.string().optional()}),Kr=H.object({type:H.literal(`tool-approval-response`),approvalId:H.string(),approved:H.boolean(),reason:H.string().optional()}),qr=H.object({role:H.literal(`system`),content:H.string(),providerOptions:W.optional()}),Jr=H.object({role:H.literal(`user`),content:H.union([H.string(),H.array(H.union([Pr,Fr,Rr]))]),providerOptions:W.optional()}),Yr=H.object({role:H.literal(`assistant`),content:H.union([H.string(),H.array(H.union([Pr,Br,Rr,zr,Vr,Hr,Wr,Gr]))]),providerOptions:W.optional()}),Xr=H.object({role:H.literal(`tool`),content:H.array(H.union([Wr,Kr])),providerOptions:W.optional()});H.union([qr,Jr,Yr,Xr]),mr({},{array:()=>ti,choice:()=>ii,json:()=>ai,object:()=>ei,text:()=>$r});function Zr(e){let t=[`ROOT`],n=-1,r=null,i=0;function a(e){return e>=`0`&&e<=`9`||e>=`A`&&e<=`F`||e>=`a`&&e<=`f`}function o(e,i,a){switch(e){case`"`:n=i,t.pop(),t.push(a),t.push(`INSIDE_STRING`);break;case`f`:case`t`:case`n`:n=i,r=i,t.pop(),t.push(a),t.push(`INSIDE_LITERAL`);break;case`-`:t.pop(),t.push(a),t.push(`INSIDE_NUMBER`);break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=i,t.pop(),t.push(a),t.push(`INSIDE_NUMBER`);break;case`{`:n=i,t.pop(),t.push(a),t.push(`INSIDE_OBJECT_START`);break;case`[`:n=i,t.pop(),t.push(a),t.push(`INSIDE_ARRAY_START`)}}function s(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_COMMA`);break;case`}`:n=r,t.pop()}}function c(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`);break;case`]`:n=r,t.pop()}}for(let l=0;l<e.length;l++){let u=e[l];switch(t[t.length-1]){case`ROOT`:o(u,l,`FINISH`);break;case`INSIDE_OBJECT_START`:switch(u){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`);break;case`}`:n=l,t.pop()}break;case`INSIDE_OBJECT_AFTER_COMMA`:u===`"`&&(t.pop(),t.push(`INSIDE_OBJECT_KEY`));break;case`INSIDE_OBJECT_KEY`:u===`"`&&(t.pop(),t.push(`INSIDE_OBJECT_AFTER_KEY`));break;case`INSIDE_OBJECT_AFTER_KEY`:u===`:`&&(t.pop(),t.push(`INSIDE_OBJECT_BEFORE_VALUE`));break;case`INSIDE_OBJECT_BEFORE_VALUE`:o(u,l,`INSIDE_OBJECT_AFTER_VALUE`);break;case`INSIDE_OBJECT_AFTER_VALUE`:s(u,l);break;case`INSIDE_STRING`:switch(u){case`"`:t.pop(),n=l;break;case`\\`:t.push(`INSIDE_STRING_ESCAPE`);break;default:n=l}break;case`INSIDE_ARRAY_START`:switch(u){case`]`:n=l,t.pop();break;default:n=l,o(u,l,`INSIDE_ARRAY_AFTER_VALUE`)}break;case`INSIDE_ARRAY_AFTER_VALUE`:switch(u){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`);break;case`]`:n=l,t.pop();break;default:n=l}break;case`INSIDE_ARRAY_AFTER_COMMA`:o(u,l,`INSIDE_ARRAY_AFTER_VALUE`);break;case`INSIDE_STRING_ESCAPE`:t.pop(),u===`u`?(i=0,t.push(`INSIDE_STRING_UNICODE_ESCAPE`)):n=l;break;case`INSIDE_STRING_UNICODE_ESCAPE`:a(u)&&(i++,i===4&&(t.pop(),n=l));break;case`INSIDE_NUMBER`:switch(u){case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=l;break;case`e`:case`E`:case`-`:case`.`:break;case`,`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&c(u,l),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&s(u,l);break;case`}`:t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&s(u,l);break;case`]`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&c(u,l);break;default:t.pop()}break;case`INSIDE_LITERAL`:{let i=e.substring(r,l+1);!`false`.startsWith(i)&&!`true`.startsWith(i)&&!`null`.startsWith(i)?(t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`?s(u,l):t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&c(u,l)):n=l;break}}}let l=e.slice(0,n+1);for(let n=t.length-1;n>=0;n--)switch(t[n]){case`INSIDE_STRING`:l+=`"`;break;case`INSIDE_OBJECT_KEY`:case`INSIDE_OBJECT_AFTER_KEY`:case`INSIDE_OBJECT_AFTER_COMMA`:case`INSIDE_OBJECT_START`:case`INSIDE_OBJECT_BEFORE_VALUE`:case`INSIDE_OBJECT_AFTER_VALUE`:l+=`}`;break;case`INSIDE_ARRAY_START`:case`INSIDE_ARRAY_AFTER_COMMA`:case`INSIDE_ARRAY_AFTER_VALUE`:l+=`]`;break;case`INSIDE_LITERAL`:{let t=e.substring(r,e.length);`true`.startsWith(t)?l+=`true`.slice(t.length):`false`.startsWith(t)?l+=`false`.slice(t.length):`null`.startsWith(t)&&(l+=`null`.slice(t.length))}}return l}async function Qr(e){if(e===void 0)return{value:void 0,state:`undefined-input`};let t=await R({text:e});return t.success?{value:t.value,state:`successful-parse`}:(t=await R({text:Zr(e)}),t.success?{value:t.value,state:`repaired-parse`}:{value:void 0,state:`failed-parse`})}var $r=()=>({name:`text`,responseFormat:Promise.resolve({type:`text`}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),ei=({schema:e,name:t,description:n})=>{let r=rr(e);return{name:`object`,responseFormat:z(r.jsonSchema).then(e=>({type:`json`,schema:e,...t!=null&&{name:t},...n!=null&&{description:n}})),async parseCompleteOutput({text:e},t){let n=await R({text:e});if(!n.success)throw new B({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let i=await dr({value:n.value,schema:r});if(!i.success)throw new B({message:`No object generated: response did not match schema.`,cause:i.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});return i.value},async parsePartialOutput({text:e}){let t=await Qr(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:return{partial:t.value}}},createElementStreamTransform(){}}},ti=({element:e,minItems:t,maxItems:n,name:r,description:i})=>{if(ni({name:`minItems`,value:t}),ni({name:`maxItems`,value:n}),t!=null&&n!=null&&t>n)throw new br({parameter:`minItems`,value:t,message:`minItems must be less than or equal to maxItems`});let a=rr(e);return{name:`array`,responseFormat:z(a.jsonSchema).then(e=>{let{$schema:a,definitions:o,$defs:s,...c}=e;return{type:`json`,schema:{$schema:`http://json-schema.org/draft-07/schema#`,...o!=null&&{definitions:o},...s!=null&&{$defs:s},type:`object`,properties:{elements:{type:`array`,items:c,...t!=null&&{minItems:t},...n!=null&&{maxItems:n}}},required:[`elements`],additionalProperties:!1},...r!=null&&{name:r},...i!=null&&{description:i}}}),async parseCompleteOutput({text:e},r){let i=await R({text:e});if(!i.success)throw new B({message:`No object generated: could not parse the response.`,cause:i.error,text:e,response:r.response,usage:r.usage,finishReason:r.finishReason});let o=i.value;if(typeof o!=`object`||!o||!(`elements`in o)||!Array.isArray(o.elements))throw new B({message:`No object generated: response did not match schema.`,cause:new O({value:o,cause:`response must be an object with an elements array`}),text:e,response:r.response,usage:r.usage,finishReason:r.finishReason});let s=ri({value:o.elements,minItems:t,maxItems:n});if(s!=null)throw new B({message:`No object generated: response did not match schema.`,cause:s,text:e,response:r.response,usage:r.usage,finishReason:r.finishReason});let c=[];for(let t of o.elements){let n=await dr({value:t,schema:a});if(!n.success)throw new B({message:`No object generated: response did not match schema.`,cause:n.error,text:e,response:r.response,usage:r.usage,finishReason:r.finishReason});c.push(n.value)}return c},async parsePartialOutput({text:e}){let t=await Qr(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:{let e=t.value;if(typeof e!=`object`||!e||!(`elements`in e)||!Array.isArray(e.elements))return;let n=t.state===`repaired-parse`&&e.elements.length>0?e.elements.slice(0,-1):e.elements,r=[];for(let e of n){let t=await dr({value:e,schema:a});t.success&&r.push(t.value)}return{partial:r}}}},createElementStreamTransform(){let e=0;return new TransformStream({transform({partialOutput:t},r){if(t!=null)for(;e<t.length;e++){if(n!=null&&e>=n){r.error(ri({value:t,maxItems:n}));return}r.enqueue(t[e])}}})}}};function ni({name:e,value:t}){if(t!=null){if(!Number.isInteger(t))throw new br({parameter:e,value:t,message:`${e} must be an integer`});if(t<0)throw new br({parameter:e,value:t,message:`${e} must be greater than or equal to 0`})}}function ri({value:e,minItems:t,maxItems:n}){if(t!=null&&e.length<t)return new O({value:e,cause:`elements array must contain at least ${t} items`});if(n!=null&&e.length>n)return new O({value:e,cause:`elements array must contain at most ${n} items`})}var ii=({options:e,name:t,description:n})=>({name:`choice`,responseFormat:Promise.resolve({type:`json`,schema:{$schema:`http://json-schema.org/draft-07/schema#`,type:`object`,properties:{result:{type:`string`,enum:e}},required:[`result`],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}),async parseCompleteOutput({text:t},n){let r=await R({text:t});if(!r.success)throw new B({message:`No object generated: could not parse the response.`,cause:r.error,text:t,response:n.response,usage:n.usage,finishReason:n.finishReason});let i=r.value;if(typeof i!=`object`||!i||!(`result`in i)||typeof i.result!=`string`||!e.includes(i.result))throw new B({message:`No object generated: response did not match schema.`,cause:new O({value:i,cause:`response must be an object that contains a choice value.`}),text:t,response:n.response,usage:n.usage,finishReason:n.finishReason});return i.result},async parsePartialOutput({text:t}){let n=await Qr(t);switch(n.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:{let t=n.value;if(typeof t!=`object`||!t||!(`result`in t)||typeof t.result!=`string`)return;let r=e.filter(e=>e.startsWith(t.result));return n.state===`successful-parse`?r.includes(t.result)?{partial:t.result}:void 0:r.length===1?{partial:r[0]}:void 0}}},createElementStreamTransform(){}}),ai=({name:e,description:t}={})=>({name:`json`,responseFormat:Promise.resolve({type:`json`,...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:e},t){let n=await R({text:e});if(!n.success)throw new B({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});return n.value},async parsePartialOutput({text:e}){let t=await Qr(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:return t.value===void 0?void 0:{partial:t.value}}},createElementStreamTransform(){}});new TextEncoder,new TextEncoder,j({prefix:`aitxt`,size:24}),j({prefix:`call`,size:24}),TransformStream;var G=H.record(H.string(),U.optional()),oi=er(()=>lr(H.union([H.looseObject({type:H.literal(`text-start`),id:H.string(),providerMetadata:W.optional()}),H.looseObject({type:H.literal(`text-delta`),id:H.string(),delta:H.string(),providerMetadata:W.optional()}),H.looseObject({type:H.literal(`text-end`),id:H.string(),providerMetadata:W.optional()}),H.looseObject({type:H.literal(`error`),errorText:H.string()}),H.looseObject({type:H.literal(`tool-input-start`),toolCallId:H.string(),toolName:H.string(),providerExecuted:H.boolean().optional(),providerMetadata:W.optional(),toolMetadata:G.optional(),dynamic:H.boolean().optional(),title:H.string().optional()}),H.looseObject({type:H.literal(`tool-input-delta`),toolCallId:H.string(),inputTextDelta:H.string()}),H.looseObject({type:H.literal(`tool-input-available`),toolCallId:H.string(),toolName:H.string(),input:H.unknown(),providerExecuted:H.boolean().optional(),providerMetadata:W.optional(),toolMetadata:G.optional(),dynamic:H.boolean().optional(),title:H.string().optional()}),H.looseObject({type:H.literal(`tool-input-error`),toolCallId:H.string(),toolName:H.string(),input:H.unknown(),providerExecuted:H.boolean().optional(),providerMetadata:W.optional(),toolMetadata:G.optional(),dynamic:H.boolean().optional(),errorText:H.string(),title:H.string().optional()}),H.looseObject({type:H.literal(`tool-approval-request`),approvalId:H.string(),toolCallId:H.string(),approvalDescriptor:H.unknown().optional(),reason:H.string().optional(),isAutomatic:H.boolean().optional(),signature:H.string().optional()}),H.looseObject({type:H.literal(`tool-approval-response`),approvalId:H.string(),approved:H.boolean(),reason:H.string().optional(),providerExecuted:H.boolean().optional(),providerMetadata:W.optional()}),H.looseObject({type:H.literal(`tool-output-available`),toolCallId:H.string(),output:H.unknown(),providerExecuted:H.boolean().optional(),providerMetadata:W.optional(),toolMetadata:G.optional(),dynamic:H.boolean().optional(),preliminary:H.boolean().optional()}),H.looseObject({type:H.literal(`tool-output-error`),toolCallId:H.string(),errorText:H.string(),providerExecuted:H.boolean().optional(),providerMetadata:W.optional(),toolMetadata:G.optional(),dynamic:H.boolean().optional()}),H.looseObject({type:H.literal(`tool-output-denied`),toolCallId:H.string()}),H.looseObject({type:H.literal(`reasoning-start`),id:H.string(),providerMetadata:W.optional()}),H.looseObject({type:H.literal(`reasoning-delta`),id:H.string(),delta:H.string(),providerMetadata:W.optional()}),H.looseObject({type:H.literal(`reasoning-end`),id:H.string(),providerMetadata:W.optional()}),H.looseObject({type:H.literal(`custom`),kind:H.string().transform(e=>e),providerMetadata:W.optional()}),H.looseObject({type:H.literal(`source-url`),sourceId:H.string(),url:H.string(),title:H.string().optional(),providerMetadata:W.optional()}),H.looseObject({type:H.literal(`source-document`),sourceId:H.string(),mediaType:H.string(),title:H.string(),filename:H.string().optional(),providerMetadata:W.optional()}),H.looseObject({type:H.literal(`file`),url:H.string(),mediaType:H.string(),providerMetadata:W.optional()}),H.looseObject({type:H.literal(`reasoning-file`),url:H.string(),mediaType:H.string(),providerMetadata:W.optional()}),H.looseObject({type:H.custom(e=>typeof e==`string`&&e.startsWith(`data-`),{message:`Type must start with "data-"`}),id:H.string().optional(),data:H.unknown(),transient:H.boolean().optional()}),H.looseObject({type:H.literal(`start-step`)}),H.looseObject({type:H.literal(`finish-step`)}),H.looseObject({type:H.literal(`reset-step`)}),H.looseObject({type:H.literal(`start`),messageId:H.string().optional(),messageMetadata:H.unknown().optional()}),H.looseObject({type:H.literal(`finish`),finishReason:H.enum([`stop`,`length`,`content-filter`,`tool-calls`,`error`,`other`]).optional(),messageMetadata:H.unknown().optional()}),H.looseObject({type:H.literal(`abort`),reason:H.string().optional()}),H.looseObject({type:H.literal(`message-metadata`),messageMetadata:H.unknown()})])));function si(e){return e.type.startsWith(`data-`)}function K(){return Object.create(null)}function ci(e){return e.type===`text`}function li(e){return e.type.startsWith(`tool-`)}function ui(e){return e.type===`dynamic-tool`}function q(e){return li(e)||ui(e)}function di(e){return e.type.split(`-`).slice(1).join(`-`)}function fi(e){return ui(e)?e.toolName:di(e)}function pi({lastMessage:e,messageId:t}){return{message:e?.role===`assistant`?e:{id:t,metadata:void 0,role:`assistant`,parts:[]},activeTextParts:K(),activeReasoningParts:K(),partialToolCalls:K()}}function mi({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:i,onToolCall:a,onData:o}){return e.pipeThrough(new TransformStream({async transform(e,s){await r(async({state:r,write:c})=>{function l(){let e=r.message.parts,t=e.length-1;for(;t>=0&&e[t].type!==`step-start`;)t--;return e.slice(t+1)}function u(){return l().filter(q)}function d(e){let t=u().find(t=>t.toolCallId===e);if(t==null){let n=r.message.parts;for(let r=n.length-1;r>=0;r--){let i=n[r];if(q(i)&&i.toolCallId===e){t=i;break}}}if(t==null)throw new V({chunkType:`tool-invocation`,chunkId:e,message:`No tool invocation found for tool call ID "${e}".`});return t}function f(e){let t=r.message.parts.filter(q).find(t=>t.approval?.id===e);if(t==null)throw new V({chunkType:`tool-approval-response`,chunkId:e,message:`No tool invocation found for approval ID "${e}".`});return t}function p(e,t){let n=t??l().find(t=>li(t)&&t.toolCallId===e.toolCallId),i=e,a=n;if(n!=null){n.state=e.state,a.input=i.input,a.output=i.output,a.errorText=i.errorText,a.rawInput=i.rawInput,a.preliminary=i.preliminary,e.title!==void 0&&(a.title=e.title),e.toolMetadata!==void 0&&(a.toolMetadata=e.toolMetadata),a.providerExecuted=i.providerExecuted??n.providerExecuted;let t=i.providerMetadata;if(t!=null){if(e.state===`output-available`||e.state===`output-error`){let e=n;e.resultProviderMetadata=t}else n.callProviderMetadata=t}}else r.message.parts.push({type:`tool-${e.toolName}`,toolCallId:e.toolCallId,state:e.state,title:e.title,...e.toolMetadata===void 0?{}:{toolMetadata:e.toolMetadata},input:i.input,output:i.output,rawInput:i.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted,preliminary:i.preliminary,...i.providerMetadata!=null&&(e.state===`output-available`||e.state===`output-error`)?{resultProviderMetadata:i.providerMetadata}:{},...i.providerMetadata!=null&&e.state!==`output-available`&&e.state!==`output-error`?{callProviderMetadata:i.providerMetadata}:{}})}function m(e,t){let n=t??l().find(t=>t.type===`dynamic-tool`&&t.toolCallId===e.toolCallId),i=e,a=n;if(n!=null){n.state=e.state,a.toolName=e.toolName,a.input=i.input,a.output=i.output,a.errorText=i.errorText,a.rawInput=i.rawInput??a.rawInput,a.preliminary=i.preliminary,e.title!==void 0&&(a.title=e.title),e.toolMetadata!==void 0&&(a.toolMetadata=e.toolMetadata),a.providerExecuted=i.providerExecuted??n.providerExecuted;let t=i.providerMetadata;if(t!=null){if(e.state===`output-available`||e.state===`output-error`){let e=n;e.resultProviderMetadata=t}else n.callProviderMetadata=t}}else r.message.parts.push({type:`dynamic-tool`,toolName:e.toolName,toolCallId:e.toolCallId,state:e.state,input:i.input,output:i.output,errorText:i.errorText,preliminary:i.preliminary,providerExecuted:i.providerExecuted,title:e.title,...e.toolMetadata===void 0?{}:{toolMetadata:e.toolMetadata},...i.providerMetadata!=null&&(e.state===`output-available`||e.state===`output-error`)?{resultProviderMetadata:i.providerMetadata}:{},...i.providerMetadata!=null&&e.state!==`output-available`&&e.state!==`output-error`?{callProviderMetadata:i.providerMetadata}:{}})}async function h(e){if(e!=null){let n=r.message.metadata==null?e:jr(r.message.metadata,e);t!=null&&await ur({value:n,schema:t,context:{field:`message.metadata`,entityId:r.message.id}}),r.message.metadata=n}}switch(e.type){case`text-start`:{let t={type:`text`,text:``,providerMetadata:e.providerMetadata,state:`streaming`};r.activeTextParts[e.id]=t,r.message.parts.push(t),c();break}case`text-delta`:{let t=r.activeTextParts[e.id];if(t==null)throw new V({chunkType:`text-delta`,chunkId:e.id,message:`Received text-delta for missing text part with ID "${e.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});t.text+=e.delta,t.providerMetadata=e.providerMetadata??t.providerMetadata,c();break}case`text-end`:{let t=r.activeTextParts[e.id];if(t==null)throw new V({chunkType:`text-end`,chunkId:e.id,message:`Received text-end for missing text part with ID "${e.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});t.state=`done`,t.providerMetadata=e.providerMetadata??t.providerMetadata,delete r.activeTextParts[e.id],c();break}case`custom`:{let t={type:`custom`,kind:e.kind,providerMetadata:e.providerMetadata};r.message.parts.push(t),c();break}case`reasoning-start`:{let t={type:`reasoning`,id:e.id,text:``,providerMetadata:e.providerMetadata,state:`streaming`};r.activeReasoningParts[e.id]=t,r.message.parts.push(t),c();break}case`reasoning-delta`:{let t=r.activeReasoningParts[e.id];if(t==null)throw new V({chunkType:`reasoning-delta`,chunkId:e.id,message:`Received reasoning-delta for missing reasoning part with ID "${e.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});t.text+=e.delta,t.providerMetadata=e.providerMetadata??t.providerMetadata,c();break}case`reasoning-end`:{let t=r.activeReasoningParts[e.id];if(t==null)throw new V({chunkType:`reasoning-end`,chunkId:e.id,message:`Received reasoning-end for missing reasoning part with ID "${e.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});t.providerMetadata=e.providerMetadata??t.providerMetadata,t.state=`done`,delete r.activeReasoningParts[e.id],c();break}case`file`:case`reasoning-file`:r.message.parts.push({type:e.type,mediaType:e.mediaType,url:e.url,...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata}}),c();break;case`source-url`:r.message.parts.push({type:`source-url`,sourceId:e.sourceId,url:e.url,title:e.title,providerMetadata:e.providerMetadata}),c();break;case`source-document`:r.message.parts.push({type:`source-document`,sourceId:e.sourceId,mediaType:e.mediaType,title:e.title,filename:e.filename,providerMetadata:e.providerMetadata}),c();break;case`tool-input-start`:{let t=l().filter(li);r.partialToolCalls[e.toolCallId]={text:``,toolName:e.toolName,index:t.length,dynamic:e.dynamic,title:e.title,toolMetadata:e.toolMetadata},e.dynamic?m({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-streaming`,input:void 0,providerExecuted:e.providerExecuted,title:e.title,toolMetadata:e.toolMetadata,providerMetadata:e.providerMetadata}):p({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-streaming`,input:void 0,providerExecuted:e.providerExecuted,title:e.title,toolMetadata:e.toolMetadata,providerMetadata:e.providerMetadata}),c();break}case`tool-input-delta`:{let t=r.partialToolCalls[e.toolCallId];if(t==null)throw new V({chunkType:`tool-input-delta`,chunkId:e.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${e.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});t.text+=e.inputTextDelta;let{value:n}=await Qr(t.text);t.dynamic?m({toolCallId:e.toolCallId,toolName:t.toolName,state:`input-streaming`,input:n,title:t.title,toolMetadata:t.toolMetadata}):p({toolCallId:e.toolCallId,toolName:t.toolName,state:`input-streaming`,input:n,title:t.title,toolMetadata:t.toolMetadata}),c();break}case`tool-input-available`:e.dynamic?m({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-available`,input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:e.title,toolMetadata:e.toolMetadata}):p({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-available`,input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:e.title,toolMetadata:e.toolMetadata}),c(),a&&!e.providerExecuted&&await a({toolCall:e});break;case`tool-input-error`:{let t=l().filter(q).find(t=>t.toolCallId===e.toolCallId);(t==null?e.dynamic:t.type===`dynamic-tool`)?m({toolCallId:e.toolCallId,toolName:e.toolName,state:`output-error`,input:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,toolMetadata:e.toolMetadata}):p({toolCallId:e.toolCallId,toolName:e.toolName,state:`output-error`,input:void 0,rawInput:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,toolMetadata:e.toolMetadata}),c();break}case`tool-approval-request`:{let t=d(e.toolCallId);t.state=`approval-requested`,t.approval={id:e.approvalId,...e.approvalDescriptor==null?{}:{descriptor:e.approvalDescriptor},...e.reason==null?{}:{requestReason:e.reason},...e.isAutomatic===!0?{isAutomatic:!0}:{},...e.signature==null?{}:{signature:e.signature}},c();break}case`tool-approval-response`:{let t=f(e.approvalId),n=t.approval==null?{id:e.approvalId}:t.approval;t.state=`approval-responded`,t.approval={...n,id:e.approvalId,approved:e.approved,...e.reason==null?{}:{reason:e.reason}},e.providerExecuted!=null&&(t.providerExecuted=e.providerExecuted),e.providerMetadata!=null&&(t.callProviderMetadata=e.providerMetadata),c();break}case`tool-output-denied`:{let t=d(e.toolCallId);t.state=`output-denied`,c();break}case`tool-output-available`:{let t=d(e.toolCallId);t.type===`dynamic-tool`?m({toolCallId:e.toolCallId,toolName:t.toolName,state:`output-available`,input:t.input,output:e.output,preliminary:e.preliminary,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata},t):p({toolCallId:e.toolCallId,toolName:di(t),state:`output-available`,input:t.input,output:e.output,providerExecuted:e.providerExecuted,preliminary:e.preliminary,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata},t),c();break}case`tool-output-error`:{let t=d(e.toolCallId);t.type===`dynamic-tool`?m({toolCallId:e.toolCallId,toolName:t.toolName,state:`output-error`,input:t.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata},t):p({toolCallId:e.toolCallId,toolName:di(t),state:`output-error`,input:t.input,rawInput:t.rawInput,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata},t),c();break}case`start-step`:r.message.parts.push({type:`step-start`});break;case`finish-step`:break;case`reset-step`:{let e=l();r.activeTextParts=K(),r.activeReasoningParts=K(),r.partialToolCalls=K(),e.length>0&&(r.message.parts.splice(r.message.parts.length-e.length,e.length),c());break}case`start`:e.messageId!=null&&(r.message.id=e.messageId),await h(e.messageMetadata),(e.messageId!=null||e.messageMetadata!=null)&&c({updateStatus:!1});break;case`finish`:e.finishReason!=null&&(r.finishReason=e.finishReason),await h(e.messageMetadata),e.messageMetadata!=null&&c();break;case`message-metadata`:await h(e.messageMetadata),e.messageMetadata!=null&&c();break;case`error`:i?.(Error(e.errorText));break;default:if(si(e)){if(n?.[e.type]!=null){let t=r.message.parts.findIndex(t=>`id`in t&&`data`in t&&t.id===e.id&&t.type===e.type),i=t>=0?t:r.message.parts.length;await ur({value:e.data,schema:n[e.type],context:{field:`message.parts[${i}].data`,entityName:e.type,entityId:e.id}})}let t=e;if(t.transient){o?.(t);break}let i=t.id==null?void 0:r.message.parts.find(e=>t.type===e.type&&t.id===e.id);i==null?r.message.parts.push(t):i.data=t.data,o?.(t),c()}}s.enqueue(e)})}}))}async function hi({stream:e,onError:t,abortSignal:n}){let r=e.getReader(),i=()=>{r.cancel().catch(()=>{})};n?.aborted?i():n?.addEventListener(`abort`,i,{once:!0});try{for(;;){let{done:e}=await r.read();if(e)break}}catch(e){t?.(e)}finally{n?.removeEventListener(`abort`,i),r.releaseLock()}}j({prefix:`aitxt`,size:24}),j({prefix:`call`,size:24}),j({prefix:`aitxt`,size:24}),j({prefix:`call`,size:24}),H.record(H.string(),U.optional()),H.record(H.string(),H.string()),j({prefix:`call`,size:24}),j({prefix:`call`,size:24}),new TextEncoder,j({prefix:`aiobj`,size:24});var gi=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise((t,n)=>{this.queue.push(async()=>{try{await e(),t()}catch(e){n(e)}}),this.processQueue()})}};j({prefix:`aiobj`,size:24}),j({prefix:`call`,size:24});async function _i(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw Error(`FileList is not supported in the current environment`);return Promise.all(Array.from(e).map(async e=>{let{name:t,type:n}=e;return{type:`file`,mediaType:n,filename:t,url:await new Promise((t,n)=>{let r=new FileReader;r.onload=e=>{t(e.target?.result)},r.onerror=e=>n(e),r.readAsDataURL(e)})}}))}var vi=class{constructor({api:e=`/api/chat`,credentials:t,headers:n,body:r,fetch:i,prepareSendMessagesRequest:a,prepareReconnectToStreamRequest:o}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=i,this.prepareSendMessagesRequest=a,this.prepareReconnectToStreamRequest=o}async sendMessages({abortSignal:e,...t}){let n=await z(this.body),r=await z(this.headers),i=await z(this.credentials),a={...A(r),...A(t.headers)},o=await this.prepareSendMessagesRequest?.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...n,...t.body},headers:a,credentials:i,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId}),s=o?.api??this.api,c=o?.headers===void 0?a:A(o.headers),l=o?.body===void 0?{...n,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId}:o.body,u=o?.credentials??i,d=await(this.fetch??globalThis.fetch)(s,{method:`POST`,headers:{"Content-Type":`application/json`,...c},body:JSON.stringify(l),credentials:u,signal:e});if(!d.ok)throw Error(await d.text()||`Failed to fetch the chat response.`);if(!d.body)throw Error(`The response body is empty.`);return this.processResponseStream(d.body)}async reconnectToStream(e){let t=await z(this.body),n=await z(this.headers),r=await z(this.credentials),i={...A(n),...A(e.headers)},a=await this.prepareReconnectToStreamRequest?.call(this,{api:this.api,id:e.chatId,body:{...t,...e.body},headers:i,credentials:r,requestMetadata:e.metadata}),o=a?.api??`${this.api}/${e.chatId}/stream`,s=a?.headers===void 0?i:A(a.headers),c=a?.credentials??r,l=await(this.fetch??globalThis.fetch)(o,{method:`GET`,headers:s,credentials:c,signal:e.abortSignal});if(l.status===204)return null;if(!l.ok)throw Error(await l.text()||`Failed to fetch the chat response.`);if(!l.body)throw Error(`The response body is empty.`);return this.processResponseStream(l.body)}},yi=class extends vi{constructor(e={}){super(e)}processResponseStream(e){return fr({stream:e,schema:oi}).pipeThrough(new TransformStream({async transform(e,t){if(!e.success)throw e.error;t.enqueue(e.value)}}))}},bi=class{constructor({generateId:e=Yt,id:t=e(),transport:n=new yi,messageMetadataSchema:r,dataPartSchemas:i,state:a,onError:o,onToolCall:s,onFinish:c,onData:l,sendAutomaticallyWhen:u}){this.pendingMessagePreparations=new Set,this.activeResponse=void 0,this.activeResumeRequest=void 0,this.jobExecutor=new gi,this.sendMessage=async(e,t)=>{if(e==null){await this.makeRequest({trigger:`submit-message`,messageId:this.lastMessage?.id,...t});return}let n;if(`text`in e||`files`in e){let t=new AbortController;this.pendingMessagePreparations.add(t);let r;try{r=Array.isArray(e.files)?e.files:await _i(e.files)}finally{this.pendingMessagePreparations.delete(t)}if(t.signal.aborted)return;n={parts:[...r,...`text`in e&&e.text!=null?[{type:`text`,text:e.text}]:[]]}}else n=e;if(e.messageId!=null){let t=this.state.messages.findIndex(t=>t.id===e.messageId);if(t===-1)throw Error(`message with id ${e.messageId} not found`);if(this.state.messages[t].role!==`user`)throw Error(`message with id ${e.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,t+1),this.state.replaceMessage(t,{id:e.messageId,...n,role:n.role??`user`,metadata:e.metadata})}else this.state.pushMessage({...n,id:n.id??this.generateId(),role:n.role??`user`,metadata:e.metadata});await this.makeRequest({trigger:`submit-message`,messageId:e.messageId,...t})},this.regenerate=async({messageId:e,...t}={})=>{let n=e==null?this.state.messages.length-1:this.state.messages.findIndex(t=>t.id===e);if(n===-1)throw Error(`message ${e} not found`);this.state.messages=this.state.messages.slice(0,this.messages[n].role===`assistant`?n:n+1),await this.makeRequest({trigger:`regenerate-message`,messageId:e,...t})},this.resumeStream=async(e={})=>{await this.makeRequest({trigger:`resume-stream`,...e})},this.clearError=()=>{this.status===`error`&&(this.state.error=void 0,this.setStatus({status:`ready`}))},this.addToolApprovalResponse=async({id:e,approved:t,reason:n,options:r})=>this.jobExecutor.run(async()=>{let i=this.state.messages,a=i[i.length-1],o=r=>q(r)&&r.state===`approval-requested`&&r.approval.id===e?{...r,state:`approval-responded`,approval:{...r.approval,id:e,approved:t,reason:n}}:r;this.state.replaceMessage(i.length-1,{...a,parts:a.parts.map(o)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(o)),this.status!==`streaming`&&this.status!==`submitted`&&this.sendAutomaticallyWhen&&this.shouldSendAutomatically().then(e=>{e&&this.makeRequest({trigger:`submit-message`,messageId:this.lastMessage?.id,...r})})}),this.addToolOutput=async({state:e=`output-available`,toolCallId:t,output:n,errorText:r,options:i})=>this.jobExecutor.run(async()=>{let a=this.state.messages,o=a[a.length-1],s=i=>q(i)&&i.toolCallId===t?{...i,state:e,output:n,errorText:r}:i;this.state.replaceMessage(a.length-1,{...o,parts:o.parts.map(s)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(s)),this.status!==`streaming`&&this.status!==`submitted`&&this.sendAutomaticallyWhen&&this.shouldSendAutomatically().then(e=>{e&&this.makeRequest({trigger:`submit-message`,messageId:this.lastMessage?.id,...i})})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{var e,t;for(let e of this.pendingMessagePreparations)e.abort();(e=this.activeResumeRequest)==null||e.abortController.abort(),(t=this.activeResponse)==null||t.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=i,this.state=a,this.onError=o,this.onToolCall=s,this.onFinish=c,this.onData=l,this.sendAutomaticallyWhen=u}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async shouldSendAutomatically(){if(!this.sendAutomaticallyWhen)return!1;let e=this.sendAutomaticallyWhen({messages:this.state.messages});return e&&typeof e==`object`&&`then`in e?await e:e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:i}){var a,o;let s=new AbortController,c=e===`resume-stream`?{abortController:s}:void 0;c&&((a=this.activeResumeRequest)==null||a.abortController.abort(),this.activeResumeRequest=c);let l=()=>c==null||this.activeResumeRequest===c,u=()=>{this.activeResumeRequest===c&&(this.activeResumeRequest=void 0)},d;if(e===`resume-stream`)try{let e=await this.transport.reconnectToStream({chatId:this.id,abortSignal:s.signal,metadata:t,headers:n,body:r});if(s.signal.aborted||!l()){await e?.cancel().catch(()=>{}),l()&&this.setStatus({status:`ready`}),u();return}if(e==null){this.setStatus({status:`ready`}),u();return}d=e}catch(e){if(s.signal.aborted||e.name===`AbortError`){l()&&this.setStatus({status:`ready`}),u();return}if(!l())return;this.onError&&e instanceof Error&&this.onError(e),this.setStatus({status:`error`,error:e}),u();return}this.setStatus({status:`submitted`,error:void 0});let f=this.lastMessage,p=!1,m=!1,h=!1,g;try{let a={state:pi({lastMessage:e===`resume-stream`||e===`regenerate-message`?void 0:this.state.snapshot(f),messageId:this.generateId()}),abortController:s};g=a,a.abortController.signal.addEventListener(`abort`,()=>{p=!0}),this.activeResponse=a;let o;if(o=e===`resume-stream`?d:await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:a.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:i}),await hi({stream:mi({stream:o,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:e=>this.jobExecutor.run(()=>a.abortController.signal.aborted?Promise.resolve():e({state:a.state,write:({updateStatus:e=!0}={})=>{a.abortController.signal.aborted||(e&&this.setStatus({status:`streaming`}),a.state.message.id===this.lastMessage?.id?this.state.replaceMessage(this.state.messages.length-1,a.state.message):this.state.pushMessage(a.state.message))}})),onError:e=>{throw e}}),abortSignal:a.abortController.signal,onError:e=>{throw e}}),p)return l()&&this.setStatus({status:`ready`}),null;l()&&this.setStatus({status:`ready`})}catch(e){if(p||e.name===`AbortError`)return p=!0,l()&&this.setStatus({status:`ready`}),null;if(!l())return null;h=!0,e instanceof TypeError&&(e.message.toLowerCase().includes(`fetch`)||e.message.toLowerCase().includes(`network`))&&(m=!0),this.onError&&e instanceof Error&&this.onError(e),this.setStatus({status:`error`,error:e})}finally{try{g&&((o=this.onFinish)==null||o.call(this,{message:g.state.message,messages:this.state.messages,isAbort:p,isDisconnect:m,isError:h,finishReason:g.state.finishReason}))}finally{this.activeResponse===g&&(this.activeResponse=void 0),u()}}!h&&await this.shouldSendAutomatically()&&await this.makeRequest({trigger:`submit-message`,messageId:this.lastMessage?.id,metadata:t,headers:n,body:r})}};function xi({messages:e}){let t=e[e.length-1];if(!t||t.role!==`assistant`)return!1;let n=t.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),r=t.parts.slice(n+1).filter(q).filter(e=>!e.providerExecuted);return r.length>0&&r.every(e=>e.state===`output-available`||e.state===`output-error`)}function Si(e){return new yi({api:_e(`/`,`Chat/Messages/`),credentials:`include`,body:{orgId:e}})}var Ci=e(t(((e,t)=>{function n(e,t){if(typeof e!=`function`)throw TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...i){clearTimeout(n);let a=Date.now(),o=t-(a-r);o<=0?(r=a,e.apply(this,i)):n=setTimeout(()=>{r=Date.now(),e.apply(this,i)},o)}}t.exports=n}))(),1),wi=(e,t,n)=>{if(!t.has(e))throw TypeError(`Cannot `+n)},J=(e,t,n)=>(wi(e,t,`read from private field`),n?n.call(e):t.get(e)),Y=(e,t,n)=>{if(t.has(e))throw TypeError(`Cannot add the same private member more than once`);t instanceof WeakSet?t.add(e):t.set(e,n)},X=(e,t,n,r)=>(wi(e,t,`write to private field`),r?r.call(e,n):t.set(e,n),n);function Ti(e,t){return t==null?e:(0,Ci.default)(e,t)}function Ei(e){return Array.isArray(e)?[...e]:typeof e==`object`&&e&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)?{...e}:e}var Z,Di,Oi,ki,Ai,ji,Q,Mi,Ni,Pi=class{constructor(e=[]){Y(this,Z,void 0),Y(this,Di,`ready`),Y(this,Oi,void 0),Y(this,ki,new Set),Y(this,Ai,new Set),Y(this,ji,new Set),this.pushMessage=e=>{X(this,Z,J(this,Z).concat(e)),J(this,Q).call(this)},this.popMessage=()=>{X(this,Z,J(this,Z).slice(0,-1)),J(this,Q).call(this)},this.replaceMessage=(e,t)=>{X(this,Z,[...J(this,Z).slice(0,e),this.snapshot(t),...J(this,Z).slice(e+1)]),J(this,Q).call(this)},this.snapshot=e=>{if(typeof e!=`object`||!e||!(`parts`in e)||!Array.isArray(e.parts))return e;let t=e,n={...t,parts:t.parts.map(e=>({...e}))};return`metadata`in t&&(n.metadata=Ei(t.metadata)),n},this[`~registerMessagesCallback`]=(e,t)=>{let n=t?Ti(e,t):e;return J(this,ki).add(n),()=>{J(this,ki).delete(n)}},this[`~registerStatusCallback`]=e=>(J(this,Ai).add(e),()=>{J(this,Ai).delete(e)}),this[`~registerErrorCallback`]=e=>(J(this,ji).add(e),()=>{J(this,ji).delete(e)}),Y(this,Q,()=>{J(this,ki).forEach(e=>e())}),Y(this,Mi,()=>{J(this,Ai).forEach(e=>e())}),Y(this,Ni,()=>{J(this,ji).forEach(e=>e())}),X(this,Z,e)}get status(){return J(this,Di)}set status(e){X(this,Di,e),J(this,Mi).call(this)}get error(){return J(this,Oi)}set error(e){X(this,Oi,e),J(this,Ni).call(this)}get messages(){return J(this,Z)}set messages(e){X(this,Z,[...e]),J(this,Q).call(this)}};Z=new WeakMap,Di=new WeakMap,Oi=new WeakMap,ki=new WeakMap,Ai=new WeakMap,ji=new WeakMap,Q=new WeakMap,Mi=new WeakMap,Ni=new WeakMap;var $,Fi=class extends bi{constructor({messages:e,...t}){let n=new Pi(e);super({...t,state:n}),Y(this,$,void 0),this[`~registerMessagesCallback`]=(e,t)=>J(this,$)[`~registerMessagesCallback`](e,t),this[`~registerStatusCallback`]=e=>J(this,$)[`~registerStatusCallback`](e),this[`~registerErrorCallback`]=e=>J(this,$)[`~registerErrorCallback`](e),X(this,$,n)}};$=new WeakMap;function Ii({throttle:e,experimental_throttle:t,resume:n=!1,...r}={}){let i=e??t,a=(0,T.useRef)({});`chat`in r||(a.current={onToolCall:r.onToolCall,onData:r.onData,onFinish:r.onFinish,onError:r.onError,sendAutomaticallyWhen:r.sendAutomaticallyWhen,transport:r.transport});let o,s=()=>a.current.transport??(o??=new yi),c={...r,transport:{sendMessages:e=>s().sendMessages(e),reconnectToStream:e=>s().reconnectToStream(e)},onToolCall:e=>{var t;return(t=a.current).onToolCall?.call(t,e)},onData:e=>{var t;return(t=a.current).onData?.call(t,e)},onFinish:e=>{var t;return(t=a.current).onFinish?.call(t,e)},onError:e=>{var t;return(t=a.current).onError?.call(t,e)},sendAutomaticallyWhen:e=>{var t;return(t=a.current).sendAutomaticallyWhen?.call(t,e)??!1}},l=(0,T.useRef)(`chat`in r?r.chat:new Fi(c));(`chat`in r&&r.chat!==l.current||`id`in r&&r.id!=null&&l.current.id!==r.id)&&(l.current=`chat`in r?r.chat:new Fi(c));let u=l.current,d=(0,T.useRef)({chat:u,messages:u.messages});d.current.chat!==u&&(d.current={chat:u,messages:u.messages});let f=(0,T.useCallback)(e=>{let t=!0,n=u[`~registerMessagesCallback`](()=>{!t||d.current.chat!==u||(d.current={chat:u,messages:u.messages},e())},i);return d.current={chat:u,messages:u.messages},()=>{t=!1,n()}},[u,i]),p=(0,T.useCallback)(()=>d.current.messages,[]),m=(0,T.useSyncExternalStore)(f,p,p),h=(0,T.useCallback)(e=>u[`~registerStatusCallback`](()=>{d.current.chat===u&&((u.status===`ready`||u.status===`error`)&&(d.current={chat:u,messages:u.messages}),e())}),[u]),g=(0,T.useCallback)(()=>u.status,[u]),_=(0,T.useSyncExternalStore)(h,g,g),v=(0,T.useSyncExternalStore)(l.current[`~registerErrorCallback`],()=>l.current.error,()=>l.current.error),y=(0,T.useCallback)(e=>{typeof e==`function`&&(e=e(l.current.messages)),l.current.messages=e},[l]);return(0,T.useEffect)(()=>{n&&l.current.resumeStream()},[n,l]),{id:l.current.id,messages:m,setMessages:y,sendMessage:l.current.sendMessage,regenerate:l.current.regenerate,clearError:l.current.clearError,stop:l.current.stop,error:v,resumeStream:l.current.resumeStream,status:_,addToolResult:l.current.addToolOutput,addToolOutput:l.current.addToolOutput,addToolApprovalResponse:l.current.addToolApprovalResponse}}function Li({input:e,setInput:t,onSubmit:n,disabled:r,autoFocus:i}){let a=(0,T.useRef)(null);return(0,T.useEffect)(()=>{i&&!r&&a.current?.focus()},[i,r]),(0,E.jsxs)(`form`,{onSubmit:n,className:`input-area`,children:[(0,E.jsx)(`input`,{ref:a,value:e,onChange:e=>t(e.target.value),placeholder:`Type a message...`,disabled:r}),(0,E.jsx)(`button`,{type:`submit`,disabled:r||!e.trim(),children:(0,E.jsx)(ut,{size:18})})]})}function Ri(){return(0,E.jsxs)(`div`,{className:`loading-state`,children:[(0,E.jsx)(Ze,{className:`animate-spin`,size:24}),(0,E.jsx)(`p`,{children:`Loading conversation...`})]})}var zi={name:`collectFeedback`,description:`Collects feedback from the user by fetching a link to a pre-populated GitHub Discussion. Use this if the user lets us know we did something well, or if the user seems frustrated, or wants to report a bug.`,inputSchema:l({feedbackSummary:y().describe(`A brief summary of the feedback, used as the discussion title.`),feedbackDetails:y().describe(`Detailed feedback from the user or agent observation.`),recap:y().describe(`A sanitized recap of what the agent and user did together and if it was successful. No sensitive information.`)})};async function Bi({input:{feedbackSummary:e,feedbackDetails:t,recap:n}}){let r=e,i=`${t}\n\n${n}`;return{success:!0,url:`https://github.com/HarperFast/harper-agent/discussions/new?category=usage-feedback&title=${encodeURIComponent(r)}&body=${encodeURIComponent(i)}`,message:`Feedback URL created! Ask the user to open it in their browser, and they will be brought to a form to approve the details of the feedback.`}}var Vi={...zi,icon:lt,execute:Bi},Hi={name:`createApp`,description:`Create a new Harper app with the specified name and template type.`,inputSchema:l({name:y().trim(),type:v(ve)})};async function Ui({input:{name:e,type:t},instanceClientParams:n,baseURL:r}){let i=Ke(e),a=ge(fe,`id`,t);if(!a)return{success:!1,message:`Error: Invalid template type, ${t}, please choose from: ${fe.map(e=>e.id).join(`, `)}`};let o=se.loading(`Creating from template...`,{description:`This may take a bit.`,duration:3e5});try{await xe({...n,project:i,template:a.npm||a.githubUrl})}catch(e){return{success:!1,message:`Error: ${e}`}}ke(`ReloadApplicationRootEntries`,!0),se.loading(`Created successfully!`,{description:`${i} created! Restarting the HTTP service...`,id:o,duration:3e5});try{await Qe({...n,operation:`restart_service`,replicated:n.entityType===`cluster`})}catch(e){return{success:!1,message:`Error: ${e}`}}return se.success(`Created successfully!`,{description:`${i} created!`,id:o,duration:5e3}),{success:!0,message:`App "${i}" created successfully.`,webURL:r}}var Wi={...Hi,icon:Re,execute:Ui,requiresApproval:!0},Gi={name:`deleteTableRecords`,description:`Deletes records in a particular table in a particular database on the server by their primary keys.`,inputSchema:l({database:y().trim(),table:y().trim(),primaryKeys:m(y())})};async function Ki({input:{database:e,table:t,primaryKeys:n},instanceClientParams:r,params:i}){try{let a=await He({...r,databaseName:e,tableName:t,hashValues:n}),{databaseName:o,tableName:s}=i;return await Je.invalidateQueries({queryKey:[r.entityId,o,s]}),{success:!0,data:a}}catch(e){return{success:!1,message:`Error: ${e}`}}}var qi={...Gi,icon:rt,execute:Ki,requiresApproval:!0},Ji={name:`dropComponentFile`,description:`Drops a component file by its full path (which was returned by getComponents)`,inputSchema:l({path:y().trim()})};async function Yi({input:{path:e},instanceClientParams:t}){try{let n=e.split(`/`),r=n.shift(),i=n.join(`/`);return{success:!0,data:await de({...t,file:i,project:r})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Xi={...Ji,icon:Ye,execute:Yi,requiresApproval:!0},Zi={name:`getAnalytics`,description:`Retrieves analytics metrics for the server, such as CPU usage or database operations (reads, writes, messages).`,inputSchema:l({metricName:y().describe(`The name of the metric to retrieve.`),startTime:u().describe(`The start of the time range for the metric, in milliseconds since the Unix epoch.`),endTime:u().describe(`The end of the time range for the metric, in milliseconds since the Unix epoch.`)})};async function Qi({input:e,instanceClientParams:t}){try{let{metricName:n,startTime:r,endTime:i}=e;return{success:!0,data:await nt({metric:n,startTime:r,endTime:i,instanceParams:t})}}catch(e){return{success:!1,message:`Error retrieving analytics: ${e}`}}}var $i={...Zi,icon:at,execute:Qi},ea={name:`getComponentFile`,description:`Returns the contents of a component file by its full path (which was returned by getComponents)`,inputSchema:l({path:y().trim()})};async function ta({input:{path:e},instanceClientParams:t}){try{let n=e.split(`/`),r=n.shift(),i=n.join(`/`);return{success:!0,data:await qe({...t,file:i,project:r})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var na={...ea,icon:pe,execute:ta},ra={name:`getComponents`,description:`Retrieves a tree of all the component (files and folders) names and sizes stored on the server.`,inputSchema:l({})};async function ia({instanceClientParams:e}){try{let t=await We(e),{rootEntries:n}=ye(t.entries);return{success:!0,items:he(n).items}}catch(e){return{success:!1,message:`Error: ${e}`}}}var aa={...ra,icon:me,execute:ia},oa={name:`getDescribeAll`,description:`Retrieves a map of the names of databases and their tables stored on the server.`,inputSchema:l({})};async function sa({instanceClientParams:e}){try{return{success:!0,map:await Xe(e)}}catch(e){return{success:!1,message:`Error: ${e}`}}}var ca={...oa,icon:Ne,execute:sa},la={name:`getDescribeTable`,description:`Returns the schema metadata describing a particular table in a particular database on the server.`,inputSchema:l({database:y().trim(),table:y().trim()})};async function ua({input:{database:e,table:t},instanceClientParams:n}){try{return{success:!0,data:await Ie({...n,databaseName:e,tableName:t})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var da={...la,icon:Ue,execute:ua},fa={name:`getUserContext`,description:`Retrieves the context of what the user is looking at on their screen, such as the current page, the file they are viewing, the database and table visible to them, that sort of thing.`,inputSchema:l({})};async function pa({instanceClientParams:e,params:t}){let n=De();if(n.includes(`/databases`)){let{databaseName:e,tableName:n}=t;return{success:!0,description:`viewing the database`,data:{databaseName:e,tableName:n}}}if(n.endsWith(`/apis`))return{success:!0,description:`viewing the APIs`};if(n.endsWith(`/status`))return{success:!0,description:`viewing the status graphs`};if(n.endsWith(`/logs`))return{success:!0,description:`viewing the logs`};if(n.includes(`/config/`))return{success:!0,description:`viewing the configuration pages`};let r=oe(`FileFocused/${e.entityId}`,void 0),i=oe(`FolderOpened/${e.entityId}`,[]),a=oe(`FileSelected/${e.entityId}`,[]);return r?{success:!0,description:`editing application files`,data:{openedPath:r,expandedItems:i,selectedItems:a}}:{success:!0,description:n}}var ma={...fa,icon:Be,execute:pa},ha={name:`insertTableRecords`,description:`Inserts one or more records into a particular table in a particular database on the server.`,inputSchema:l({database:y().trim(),table:y().trim(),records:m(i())})};async function ga({input:{database:e,table:t,records:n},instanceClientParams:r,params:i}){try{let a=await Le({...r,databaseName:e,tableName:t,records:n}),{databaseName:o,tableName:s}=i;return await Je.invalidateQueries({queryKey:[r.entityId,o,s]}),{success:!0,data:a}}catch(e){return{success:!1,message:`Error: ${e}`}}}var _a={...ha,icon:rt,execute:ga,requiresApproval:!0},va={name:`listAnalyticsMetrics`,description:`Lists the available analytics metric names available for calling getAnalytics upon.`,inputSchema:l({metricTypes:v([`builtin`,`custom`]),customWindowMS:u().optional().describe(`Default to one week time window for finding custom metrics.`)})};async function ya({metricTypes:e,customWindowMS:t,instanceParams:n}){let{data:r}=await n.instanceClient.post(`/`,{operation:`list_analytics_metrics`,metricTypes:e,customWindowMS:t});return r}async function ba({input:e,instanceClientParams:t}){try{let{metricTypes:n,customWindowMS:r}=e;return{success:!0,metricNames:await ya({metricTypes:n,customWindowMS:r,instanceParams:t})}}catch(e){return{success:!1,message:`Error retrieving analytics: ${e}`}}}var xa={...va,icon:at,execute:ba},Sa=[`adding-tables-with-schemas`,`automatic-apis`,`caching`,`checking-authentication`,`creating-a-fabric-account-and-cluster`,`creating-harper-apps`,`custom-resources`,`defining-relationships`,`delegating-to-the-built-in-agent`,`deploying-to-harper-fabric`,`extending-tables`,`handling-binary-data`,`load-env`,`logging`,`programmatic-table-requests`,`querying-rest-apis`,`real-time-apps`,`schema-design-tooling`,`serving-web-content`,`typescript-type-stripping`,`using-blob-datatype`,`v5-upgrade`,`vector-indexing`],Ca={"adding-tables-with-schemas":"---\nname: adding-tables-with-schemas\ndescription: Guidelines for adding tables to a Harper database using GraphQL schemas.\nmetadata:\n mode: synthesized\n---\n\n# Adding Tables with Schemas\n\nInstructions for the agent to follow when adding tables to a Harper database.\n\n## When to Use\n\nUse this skill when you need to define new data structures or modify existing ones in a Harper database.\n\n## How It Works\n\n1. **Create Dedicated Schema Files**: Prefer having a dedicated schema `.graphql` file for each table. Check the `config.yaml` file under `graphqlSchema.files` to see how it's configured. It typically accepts wildcards (e.g., `schemas/*.graphql`), but may be configured to point at a single file.\n2. **Use Directives**: All available directives for defining your schema are defined in `node_modules/harper/schema.graphql`. Common directives include `@table`, `@export`, `@primaryKey`, `@indexed`, and `@relationship`.\n3. **Define Relationships**: Link tables together using the `@relationship` directive. For more details, see the [Defining Relationships](defining-relationships.md) skill.\n4. **Enable Automatic APIs**: If you add `@table @export` to a schema type, Harper automatically sets up REST and WebSocket APIs for basic CRUD operations against that table. **Important**: REST endpoints also require `rest: true` in `config.yaml` — without it, `@export`ed tables will not respond to HTTP requests. For a detailed list of available endpoints and how to use them, see the [Automatic REST APIs](automatic-apis.md) skill.\n - `GET /{TableName}`: Describes the schema itself.\n - `GET /{TableName}/`: Lists all records (supports filtering, sorting, and pagination via query parameters). See the [Querying REST APIs](querying-rest-apis.md) skill for details.\n - `GET /{TableName}/{id}`: Retrieves a single record by its ID.\n - `POST /{TableName}/`: Creates a new record.\n - `PUT /{TableName}/{id}`: Updates an existing record.\n - `PATCH /{TableName}/{id}`: Performs a partial update on a record.\n - `DELETE /{TableName}/`: Deletes all records or filtered records.\n - `DELETE /{TableName}/{id}`: Deletes a single record by its ID.\n5. **Consider Table Extensions**: If you are going to [extend the table](./extending-tables.md) in your resources, then do not `@export` the table from the schema.\n\n## Examples\n\nIn a hypothetical `schemas/ExamplePerson.graphql`:\n\n```graphql\ntype ExamplePerson @table @export {\n id: ID @primaryKey\n name: String\n tag: String @indexed\n}\n```\n","automatic-apis":`---
16
+ ]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function Zn(e,t){let n={type:`object`,additionalProperties:L(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(e.keyType?._def.typeName===`ZodString`&&e.keyType._def.checks?.length){let{type:r,...i}=Kn(e.keyType._def,t);return{...n,propertyNames:i}}if(e.keyType?._def.typeName===`ZodEnum`)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===`ZodBranded`&&e.keyType._def.type._def.typeName===`ZodString`&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=Fn(e.keyType._def,t);return{...n,propertyNames:i}}return n}function Qn(e,t){return t.mapStrategy===`record`?Zn(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[L(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||N(),L(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||N()],minItems:2,maxItems:2}}}function $n(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function er(){return{not:N()}}function tr(){return{type:`null`}}var nr={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function rr(e,t){let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in nr&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=nr[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return ir(e,t)}var ir=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>L(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function ar(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[nr[e.innerType._def.typeName],`null`]};let n=L(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function or(e){let t={type:`number`};if(!e.checks)return t;for(let n of e.checks)switch(n.kind){case`int`:t.type=`integer`;break;case`min`:n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case`max`:n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case`multipleOf`:t.multipleOf=n.value}return t}function sr(e,t){let n={type:`object`,properties:{}},r=[],i=e.shape();for(let e in i){let a=i[e];if(a===void 0||a._def===void 0)continue;let o=lr(a),s=L(a._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});s!==void 0&&(n.properties[e]=s,o||r.push(e))}r.length&&(n.required=r);let a=cr(e,t);return a!==void 0&&(n.additionalProperties=a),n}function cr(e,t){if(e.catchall._def.typeName!==`ZodNever`)return L(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function lr(e){try{return e.isOptional()}catch{return!0}}var ur=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return L(e.innerType._def,t);let n=L(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:N()},n]}:N()},dr=(e,t)=>{if(t.pipeStrategy===`input`)return L(e.in._def,t);if(t.pipeStrategy===`output`)return L(e.out._def,t);let n=L(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,L(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function fr(e,t){return L(e.type._def,t)}function pr(e,t){let n={type:`array`,uniqueItems:!0,items:L(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&(n.minItems=e.minSize.value),e.maxSize&&(n.maxItems=e.maxSize.value),n}function mr(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>L(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:L(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>L(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function hr(){return{not:N()}}function gr(){return N()}var _r=(e,t)=>L(e.innerType._def,t),vr=(e,t,n)=>{switch(t){case`ZodString`:return Kn(e,n);case`ZodNumber`:return or(e);case`ZodObject`:return sr(e,n);case`ZodBigInt`:return Nn(e);case`ZodBoolean`:return Pn();case`ZodDate`:return Ln(e,n);case`ZodUndefined`:return hr();case`ZodNull`:return tr();case`ZodArray`:return Mn(e,n);case`ZodUnion`:case`ZodDiscriminatedUnion`:return rr(e,n);case`ZodIntersection`:return Un(e,n);case`ZodTuple`:return mr(e,n);case`ZodRecord`:return Zn(e,n);case`ZodLiteral`:return Wn(e);case`ZodEnum`:return Vn(e);case`ZodNativeEnum`:return $n(e);case`ZodNullable`:return ar(e,n);case`ZodOptional`:return ur(e,n);case`ZodMap`:return Qn(e,n);case`ZodSet`:return pr(e,n);case`ZodLazy`:return()=>e.getter()._def;case`ZodPromise`:return fr(e,n);case`ZodNaN`:case`ZodNever`:return er();case`ZodEffects`:return Bn(e,n);case`ZodAny`:return N();case`ZodUnknown`:return gr();case`ZodDefault`:return zn(e,n);case`ZodBranded`:return Fn(e,n);case`ZodReadonly`:return _r(e,n);case`ZodCatch`:return In(e,n);case`ZodPipeline`:return dr(e,n);case`ZodFunction`:case`ZodVoid`:case`ZodSymbol`:return;default:return(e=>void 0)(t)}},yr=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function L(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.call(t,e,t,r,n);if(i!==kn)return i}if(r&&!n){let e=br(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=vr(e,e.typeName,t),o=typeof a==`function`?L(a(),t):a;if(o&&xr(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var br=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:yr(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),N()):t.$refStrategy===`seen`?N():void 0}},xr=(e,t,n)=>(e.description&&(n.description=e.description),n),Sr=e=>{let t=jn(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}},Cr=(e,t)=>{let n=Sr(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:L(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??N()}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=L(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??N(),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o);let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return s.$schema=`http://json-schema.org/draft-07/schema#`,s},wr=Symbol.for(`vercel.ai.schema`);function Tr(e){let t;return()=>(t??=e(),t)}function Er(e,{validate:t}={}){return{[wr]:!0,_type:void 0,get jsonSchema(){return typeof e==`function`&&(e=e()),e},validate:t}}function Dr(e){return typeof e==`object`&&!!e&&wr in e&&e[wr]===!0&&`jsonSchema`in e&&`validate`in e}function Or(e){return e==null?Er({type:`object`,properties:{},additionalProperties:!1}):Dr(e)?e:`~standard`in e?e[`~standard`].vendor===`zod`?Pr(e):kr(e):e()}function kr(e){return Er(()=>{if(!Ar(e))throw Error(`Standard schema vendor '${e[`~standard`].vendor}' does not support JSON Schema conversion.`);return On(e[`~standard`].jsonSchema.input({target:`draft-07`}))},{validate:async t=>{let n=await e[`~standard`].validate(t);return`value`in n?{success:!0,value:n.value}:{success:!1,error:new O({value:t,cause:n.issues})}}})}function Ar(e){return e[`~standard`].jsonSchema!=null}function jr(e,t){let n=t?.useReferences??!1;return Er(()=>Cr(e,{$refStrategy:n?`root`:`none`}),{validate:async t=>{let n=await e.safeParseAsync(t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}function Mr(e,t){let r=t?.useReferences??!1;return Er(()=>On(n(e,{target:`draft-7`,io:`input`,reused:r?`ref`:`inline`})),{validate:async t=>{let n=await b(e,t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}function Nr(e){return`_zod`in e}function Pr(e,t){return Nr(e)?Mr(e,t):jr(e,t)}async function Fr({value:e,schema:t,context:n}){let r=await Ir({value:e,schema:t,context:n});if(!r.success)throw O.wrap({value:e,cause:r.error,context:n});return r.value}async function Ir({value:e,schema:t,context:n}){let r=Or(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};let t=await r.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:O.wrap({value:e,cause:t.error,context:n}),rawValue:e}}catch(t){return{success:!1,error:O.wrap({value:e,cause:t,context:n}),rawValue:e}}}async function R({text:e,schema:t}){try{let n=Dn(e);return t==null?{success:!0,value:n,rawValue:n}:await Ir({value:n,schema:t})}catch(t){return{success:!1,error:Qt.isInstance(t)?t:new Qt({text:e,cause:t}),rawValue:void 0}}}function Lr({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new vn).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await R({text:e,schema:t}))}}))}async function z(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}new TextDecoder;var Rr=Object.defineProperty,zr=(e,t)=>{for(var n in t)Rr(e,n,{get:t[n],enumerable:!0})},Br=`AI_InvalidArgumentError`,Vr=`vercel.ai.error.${Br}`,Hr=Symbol.for(Vr),Ur,Wr,B=class extends (Wr=D,Ur=Hr,Wr){constructor({parameter:e,value:t,message:n}){super({name:Br,message:`Invalid argument for parameter ${e}: ${n}`}),this[Ur]=!0,this.parameter=e,this.value=t}static isInstance(e){return D.hasMarker(e,Vr)}},Gr=`AI_NoObjectGeneratedError`,Kr=`vercel.ai.error.${Gr}`,qr=Symbol.for(Kr),Jr,Yr,V=class extends (Yr=D,Jr=qr,Yr){constructor({message:e=`No object generated.`,cause:t,text:n,response:r,usage:i,finishReason:a}){super({name:Gr,message:e,cause:t}),this[Jr]=!0,this.text=n,this.response=r,this.usage=i,this.finishReason=a}static isInstance(e){return D.hasMarker(e,Kr)}},Xr=`AI_UIMessageStreamError`,Zr=`vercel.ai.error.${Xr}`,Qr=Symbol.for(Zr),$r,ei,H=class extends (ei=D,$r=Qr,ei){constructor({chunkType:e,chunkId:t,message:n}){super({name:Xr,message:n}),this[$r]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return D.hasMarker(e,Zr)}};function ti({warning:e,provider:t,model:n}){let r=`AI SDK Warning${t!=null&&n!=null?` (${t} / ${n})`:``}:`;switch(e.type){case`unsupported`:{let t=`${r} The feature "${e.feature}" is not supported.`;return e.details&&(t+=` ${e.details}`),t}case`compatibility`:{let t=`${r} The feature "${e.feature}" is used in a compatibility mode.`;return e.details&&(t+=` ${e.details}`),t}case`deprecated`:return`${r} Deprecated: "${e.setting}". ${e.message}`;case`other`:return`${r} ${e.message}`;default:return`${r} ${JSON.stringify(e,null,2)}`}}var ni=`AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.`,ri=!1;function ii({message:e,type:t}){typeof process<`u`&&typeof process.emitWarning==`function`?process.emitWarning(e,{type:t}):console.warn(e)}var ai=e=>{if(e.warnings.length===0)return;let t=globalThis.AI_SDK_LOG_WARNINGS;if(t!==!1){if(typeof t==`function`){t(e);return}ri||(ri=!0,ii({message:ni,type:`Warning`}));for(let t of e.warnings)ii({message:ti({warning:t,provider:e.provider,model:e.model}),type:t.type===`deprecated`?`DeprecationWarning`:`Warning`})}};function oi(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;let n={...e};for(let r in t)if(r!==`__proto__`&&r!==`constructor`&&r!==`prototype`&&Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(i===void 0)continue;let a=r in e?e[r]:void 0,o=typeof i==`object`&&!!i&&!Array.isArray(i)&&!(i instanceof Date)&&!(i instanceof RegExp),s=typeof a==`object`&&!!a&&!Array.isArray(a)&&!(a instanceof Date)&&!(a instanceof RegExp);n[r]=o&&s?oi(a,i):i}return n}var U={array:m,boolean:_,custom:o,discriminatedUnion:d,enum:v,instanceof:p,lazy:s,literal:c,looseObject:h,never:f,null:g,number:u,object:l,record:r,string:y,union:x,unknown:a},W=U.lazy(()=>U.union([U.null(),U.string(),U.number(),U.boolean(),U.record(U.string(),W.optional()),U.array(W)])),G=U.record(U.string(),U.record(U.string(),W.optional())),si=U.union([U.string(),U.instanceof(Uint8Array),U.instanceof(ArrayBuffer),U.custom(Sn,{message:`Must be a Buffer`})]),ci=U.record(U.string(),U.string()),li=U.object({type:U.literal(`text`),text:U.string(),providerOptions:G.optional()}),ui=U.object({type:U.literal(`image`),image:U.union([si,U.instanceof(URL),ci]),mediaType:U.string().optional(),providerOptions:G.optional()}),di=U.discriminatedUnion(`type`,[U.object({type:U.literal(`data`),data:si}),U.object({type:U.literal(`url`),url:U.instanceof(URL)}),U.object({type:U.literal(`reference`),reference:ci}),U.object({type:U.literal(`text`),text:U.string()})]),fi=U.discriminatedUnion(`type`,[U.object({type:U.literal(`data`),data:si}),U.object({type:U.literal(`url`),url:U.instanceof(URL)})]),pi=U.object({type:U.literal(`file`),data:U.union([di,si,U.instanceof(URL),ci]),filename:U.string().optional(),mediaType:U.string(),providerOptions:G.optional()}),mi=U.object({type:U.literal(`reasoning`),text:U.string(),providerOptions:G.optional()}),hi=U.object({type:U.literal(`custom`),kind:U.string().transform(e=>e),providerOptions:G.optional()}),gi=U.object({type:U.literal(`reasoning-file`),data:U.union([fi,si,U.instanceof(URL)]),mediaType:U.string(),providerOptions:G.optional()}),_i=U.object({type:U.literal(`tool-call`),toolCallId:U.string(),toolName:U.string(),input:U.unknown(),providerOptions:G.optional(),providerExecuted:U.boolean().optional()}),vi=U.discriminatedUnion(`type`,[U.object({type:U.literal(`text`),value:U.string(),providerOptions:G.optional()}),U.object({type:U.literal(`json`),value:W,providerOptions:G.optional()}),U.object({type:U.literal(`execution-denied`),reason:U.string().optional(),providerOptions:G.optional()}),U.object({type:U.literal(`error-text`),value:U.string(),providerOptions:G.optional()}),U.object({type:U.literal(`error-json`),value:W,providerOptions:G.optional()}),U.object({type:U.literal(`content`),value:U.array(U.union([U.object({type:U.literal(`text`),text:U.string(),providerOptions:G.optional()}),U.object({type:U.literal(`file`),data:di,mediaType:U.string(),filename:U.string().optional(),providerOptions:G.optional()}),U.object({type:U.literal(`file-data`),data:U.string(),mediaType:U.string(),filename:U.string().optional(),providerOptions:G.optional()}),U.object({type:U.literal(`file-url`),url:U.string(),mediaType:U.string().optional(),providerOptions:G.optional()}),U.object({type:U.literal(`file-id`),fileId:U.union([U.string(),U.record(U.string(),U.string())]),providerOptions:G.optional()}),U.object({type:U.literal(`file-reference`),providerReference:U.record(U.string(),U.string()),providerOptions:G.optional()}),U.object({type:U.literal(`image-data`),data:U.string(),mediaType:U.string(),providerOptions:G.optional()}),U.object({type:U.literal(`image-url`),url:U.string(),providerOptions:G.optional()}),U.object({type:U.literal(`image-file-id`),fileId:U.union([U.string(),U.record(U.string(),U.string())]),providerOptions:G.optional()}),U.object({type:U.literal(`image-file-reference`),providerReference:U.record(U.string(),U.string()),providerOptions:G.optional()}),U.object({type:U.literal(`custom`),providerOptions:G.optional()})]))})]),yi=U.object({type:U.literal(`tool-result`),toolCallId:U.string(),toolName:U.string(),output:vi,providerOptions:G.optional()}),bi=U.object({type:U.literal(`tool-approval-request`),approvalId:U.string(),toolCallId:U.string(),reason:U.string().optional()}),xi=U.object({type:U.literal(`tool-approval-response`),approvalId:U.string(),approved:U.boolean(),reason:U.string().optional()}),Si=U.object({role:U.literal(`system`),content:U.string(),providerOptions:G.optional()}),Ci=U.object({role:U.literal(`user`),content:U.union([U.string(),U.array(U.union([li,ui,pi]))]),providerOptions:G.optional()}),wi=U.object({role:U.literal(`assistant`),content:U.union([U.string(),U.array(U.union([li,hi,pi,mi,gi,_i,yi,bi]))]),providerOptions:G.optional()}),Ti=U.object({role:U.literal(`tool`),content:U.array(U.union([yi,xi])),providerOptions:G.optional()});U.union([Si,Ci,wi,Ti]),zr({},{array:()=>Ai,choice:()=>Ni,json:()=>Pi,object:()=>ki,text:()=>Oi});function Ei(e){let t=[`ROOT`],n=-1,r=null,i=0;function a(e){return e>=`0`&&e<=`9`||e>=`A`&&e<=`F`||e>=`a`&&e<=`f`}function o(e,i,a){switch(e){case`"`:n=i,t.pop(),t.push(a),t.push(`INSIDE_STRING`);break;case`f`:case`t`:case`n`:n=i,r=i,t.pop(),t.push(a),t.push(`INSIDE_LITERAL`);break;case`-`:t.pop(),t.push(a),t.push(`INSIDE_NUMBER`);break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=i,t.pop(),t.push(a),t.push(`INSIDE_NUMBER`);break;case`{`:n=i,t.pop(),t.push(a),t.push(`INSIDE_OBJECT_START`);break;case`[`:n=i,t.pop(),t.push(a),t.push(`INSIDE_ARRAY_START`)}}function s(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_COMMA`);break;case`}`:n=r,t.pop()}}function c(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`);break;case`]`:n=r,t.pop()}}for(let l=0;l<e.length;l++){let u=e[l];switch(t[t.length-1]){case`ROOT`:o(u,l,`FINISH`);break;case`INSIDE_OBJECT_START`:switch(u){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`);break;case`}`:n=l,t.pop()}break;case`INSIDE_OBJECT_AFTER_COMMA`:u===`"`&&(t.pop(),t.push(`INSIDE_OBJECT_KEY`));break;case`INSIDE_OBJECT_KEY`:u===`"`&&(t.pop(),t.push(`INSIDE_OBJECT_AFTER_KEY`));break;case`INSIDE_OBJECT_AFTER_KEY`:u===`:`&&(t.pop(),t.push(`INSIDE_OBJECT_BEFORE_VALUE`));break;case`INSIDE_OBJECT_BEFORE_VALUE`:o(u,l,`INSIDE_OBJECT_AFTER_VALUE`);break;case`INSIDE_OBJECT_AFTER_VALUE`:s(u,l);break;case`INSIDE_STRING`:switch(u){case`"`:t.pop(),n=l;break;case`\\`:t.push(`INSIDE_STRING_ESCAPE`);break;default:n=l}break;case`INSIDE_ARRAY_START`:switch(u){case`]`:n=l,t.pop();break;default:n=l,o(u,l,`INSIDE_ARRAY_AFTER_VALUE`)}break;case`INSIDE_ARRAY_AFTER_VALUE`:switch(u){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`);break;case`]`:n=l,t.pop();break;default:n=l}break;case`INSIDE_ARRAY_AFTER_COMMA`:o(u,l,`INSIDE_ARRAY_AFTER_VALUE`);break;case`INSIDE_STRING_ESCAPE`:t.pop(),u===`u`?(i=0,t.push(`INSIDE_STRING_UNICODE_ESCAPE`)):n=l;break;case`INSIDE_STRING_UNICODE_ESCAPE`:a(u)&&(i++,i===4&&(t.pop(),n=l));break;case`INSIDE_NUMBER`:switch(u){case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=l;break;case`e`:case`E`:case`-`:case`.`:break;case`,`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&c(u,l),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&s(u,l);break;case`}`:t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&s(u,l);break;case`]`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&c(u,l);break;default:t.pop()}break;case`INSIDE_LITERAL`:{let i=e.substring(r,l+1);!`false`.startsWith(i)&&!`true`.startsWith(i)&&!`null`.startsWith(i)?(t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`?s(u,l):t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&c(u,l)):n=l;break}}}let l=e.slice(0,n+1);for(let n=t.length-1;n>=0;n--)switch(t[n]){case`INSIDE_STRING`:l+=`"`;break;case`INSIDE_OBJECT_KEY`:case`INSIDE_OBJECT_AFTER_KEY`:case`INSIDE_OBJECT_AFTER_COMMA`:case`INSIDE_OBJECT_START`:case`INSIDE_OBJECT_BEFORE_VALUE`:case`INSIDE_OBJECT_AFTER_VALUE`:l+=`}`;break;case`INSIDE_ARRAY_START`:case`INSIDE_ARRAY_AFTER_COMMA`:case`INSIDE_ARRAY_AFTER_VALUE`:l+=`]`;break;case`INSIDE_LITERAL`:{let t=e.substring(r,e.length);`true`.startsWith(t)?l+=`true`.slice(t.length):`false`.startsWith(t)?l+=`false`.slice(t.length):`null`.startsWith(t)&&(l+=`null`.slice(t.length))}}return l}async function Di(e){if(e===void 0)return{value:void 0,state:`undefined-input`};let t=await R({text:e});return t.success?{value:t.value,state:`successful-parse`}:(t=await R({text:Ei(e)}),t.success?{value:t.value,state:`repaired-parse`}:{value:void 0,state:`failed-parse`})}var Oi=()=>({name:`text`,responseFormat:Promise.resolve({type:`text`}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),ki=({schema:e,name:t,description:n})=>{let r=Or(e);return{name:`object`,responseFormat:z(r.jsonSchema).then(e=>({type:`json`,schema:e,...t!=null&&{name:t},...n!=null&&{description:n}})),async parseCompleteOutput({text:e},t){let n=await R({text:e});if(!n.success)throw new V({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let i=await Ir({value:n.value,schema:r});if(!i.success)throw new V({message:`No object generated: response did not match schema.`,cause:i.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});return i.value},async parsePartialOutput({text:e}){let t=await Di(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:return{partial:t.value}}},createElementStreamTransform(){}}},Ai=({element:e,minItems:t,maxItems:n,name:r,description:i})=>{if(ji({name:`minItems`,value:t}),ji({name:`maxItems`,value:n}),t!=null&&n!=null&&t>n)throw new B({parameter:`minItems`,value:t,message:`minItems must be less than or equal to maxItems`});let a=Or(e);return{name:`array`,responseFormat:z(a.jsonSchema).then(e=>{let{$schema:a,definitions:o,$defs:s,...c}=e;return{type:`json`,schema:{$schema:`http://json-schema.org/draft-07/schema#`,...o!=null&&{definitions:o},...s!=null&&{$defs:s},type:`object`,properties:{elements:{type:`array`,items:c,...t!=null&&{minItems:t},...n!=null&&{maxItems:n}}},required:[`elements`],additionalProperties:!1},...r!=null&&{name:r},...i!=null&&{description:i}}}),async parseCompleteOutput({text:e},r){let i=await R({text:e});if(!i.success)throw new V({message:`No object generated: could not parse the response.`,cause:i.error,text:e,response:r.response,usage:r.usage,finishReason:r.finishReason});let o=i.value;if(typeof o!=`object`||!o||!(`elements`in o)||!Array.isArray(o.elements))throw new V({message:`No object generated: response did not match schema.`,cause:new O({value:o,cause:`response must be an object with an elements array`}),text:e,response:r.response,usage:r.usage,finishReason:r.finishReason});let s=Mi({value:o.elements,minItems:t,maxItems:n});if(s!=null)throw new V({message:`No object generated: response did not match schema.`,cause:s,text:e,response:r.response,usage:r.usage,finishReason:r.finishReason});let c=[];for(let t of o.elements){let n=await Ir({value:t,schema:a});if(!n.success)throw new V({message:`No object generated: response did not match schema.`,cause:n.error,text:e,response:r.response,usage:r.usage,finishReason:r.finishReason});c.push(n.value)}return c},async parsePartialOutput({text:e}){let t=await Di(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:{let e=t.value;if(typeof e!=`object`||!e||!(`elements`in e)||!Array.isArray(e.elements))return;let n=t.state===`repaired-parse`&&e.elements.length>0?e.elements.slice(0,-1):e.elements,r=[];for(let e of n){let t=await Ir({value:e,schema:a});t.success&&r.push(t.value)}return{partial:r}}}},createElementStreamTransform(){let e=0;return new TransformStream({transform({partialOutput:t},r){if(t!=null)for(;e<t.length;e++){if(n!=null&&e>=n){r.error(Mi({value:t,maxItems:n}));return}r.enqueue(t[e])}}})}}};function ji({name:e,value:t}){if(t!=null){if(!Number.isInteger(t))throw new B({parameter:e,value:t,message:`${e} must be an integer`});if(t<0)throw new B({parameter:e,value:t,message:`${e} must be greater than or equal to 0`})}}function Mi({value:e,minItems:t,maxItems:n}){if(t!=null&&e.length<t)return new O({value:e,cause:`elements array must contain at least ${t} items`});if(n!=null&&e.length>n)return new O({value:e,cause:`elements array must contain at most ${n} items`})}var Ni=({options:e,name:t,description:n})=>({name:`choice`,responseFormat:Promise.resolve({type:`json`,schema:{$schema:`http://json-schema.org/draft-07/schema#`,type:`object`,properties:{result:{type:`string`,enum:e}},required:[`result`],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}),async parseCompleteOutput({text:t},n){let r=await R({text:t});if(!r.success)throw new V({message:`No object generated: could not parse the response.`,cause:r.error,text:t,response:n.response,usage:n.usage,finishReason:n.finishReason});let i=r.value;if(typeof i!=`object`||!i||!(`result`in i)||typeof i.result!=`string`||!e.includes(i.result))throw new V({message:`No object generated: response did not match schema.`,cause:new O({value:i,cause:`response must be an object that contains a choice value.`}),text:t,response:n.response,usage:n.usage,finishReason:n.finishReason});return i.result},async parsePartialOutput({text:t}){let n=await Di(t);switch(n.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:{let t=n.value;if(typeof t!=`object`||!t||!(`result`in t)||typeof t.result!=`string`)return;let r=e.filter(e=>e.startsWith(t.result));return n.state===`successful-parse`?r.includes(t.result)?{partial:t.result}:void 0:r.length===1?{partial:r[0]}:void 0}}},createElementStreamTransform(){}}),Pi=({name:e,description:t}={})=>({name:`json`,responseFormat:Promise.resolve({type:`json`,...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:e},t){let n=await R({text:e});if(!n.success)throw new V({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});return n.value},async parsePartialOutput({text:e}){let t=await Di(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:return t.value===void 0?void 0:{partial:t.value}}},createElementStreamTransform(){}});new TextEncoder,new TextEncoder,j({prefix:`aitxt`,size:24}),j({prefix:`call`,size:24}),TransformStream;var Fi=U.record(U.string(),W.optional()),Ii=Tr(()=>Pr(U.union([U.looseObject({type:U.literal(`text-start`),id:U.string(),providerMetadata:G.optional()}),U.looseObject({type:U.literal(`text-delta`),id:U.string(),delta:U.string(),providerMetadata:G.optional()}),U.looseObject({type:U.literal(`text-end`),id:U.string(),providerMetadata:G.optional()}),U.looseObject({type:U.literal(`error`),errorText:U.string()}),U.looseObject({type:U.literal(`tool-input-start`),toolCallId:U.string(),toolName:U.string(),providerExecuted:U.boolean().optional(),providerMetadata:G.optional(),toolMetadata:Fi.optional(),dynamic:U.boolean().optional(),title:U.string().optional()}),U.looseObject({type:U.literal(`tool-input-delta`),toolCallId:U.string(),inputTextDelta:U.string()}),U.looseObject({type:U.literal(`tool-input-available`),toolCallId:U.string(),toolName:U.string(),input:U.unknown(),providerExecuted:U.boolean().optional(),providerMetadata:G.optional(),toolMetadata:Fi.optional(),dynamic:U.boolean().optional(),title:U.string().optional()}),U.looseObject({type:U.literal(`tool-input-error`),toolCallId:U.string(),toolName:U.string(),input:U.unknown(),providerExecuted:U.boolean().optional(),providerMetadata:G.optional(),toolMetadata:Fi.optional(),dynamic:U.boolean().optional(),errorText:U.string(),title:U.string().optional()}),U.looseObject({type:U.literal(`tool-approval-request`),approvalId:U.string(),toolCallId:U.string(),approvalDescriptor:U.unknown().optional(),reason:U.string().optional(),isAutomatic:U.boolean().optional(),signature:U.string().optional()}),U.looseObject({type:U.literal(`tool-approval-response`),approvalId:U.string(),approved:U.boolean(),reason:U.string().optional(),providerExecuted:U.boolean().optional(),providerMetadata:G.optional()}),U.looseObject({type:U.literal(`tool-output-available`),toolCallId:U.string(),output:U.unknown(),providerExecuted:U.boolean().optional(),providerMetadata:G.optional(),toolMetadata:Fi.optional(),dynamic:U.boolean().optional(),preliminary:U.boolean().optional()}),U.looseObject({type:U.literal(`tool-output-error`),toolCallId:U.string(),errorText:U.string(),providerExecuted:U.boolean().optional(),providerMetadata:G.optional(),toolMetadata:Fi.optional(),dynamic:U.boolean().optional()}),U.looseObject({type:U.literal(`tool-output-denied`),toolCallId:U.string()}),U.looseObject({type:U.literal(`reasoning-start`),id:U.string(),providerMetadata:G.optional()}),U.looseObject({type:U.literal(`reasoning-delta`),id:U.string(),delta:U.string(),providerMetadata:G.optional()}),U.looseObject({type:U.literal(`reasoning-end`),id:U.string(),providerMetadata:G.optional()}),U.looseObject({type:U.literal(`custom`),kind:U.string().transform(e=>e),providerMetadata:G.optional()}),U.looseObject({type:U.literal(`source-url`),sourceId:U.string(),url:U.string(),title:U.string().optional(),providerMetadata:G.optional()}),U.looseObject({type:U.literal(`source-document`),sourceId:U.string(),mediaType:U.string(),title:U.string(),filename:U.string().optional(),providerMetadata:G.optional()}),U.looseObject({type:U.literal(`file`),url:U.string(),mediaType:U.string(),providerMetadata:G.optional()}),U.looseObject({type:U.literal(`reasoning-file`),url:U.string(),mediaType:U.string(),providerMetadata:G.optional()}),U.looseObject({type:U.custom(e=>typeof e==`string`&&e.startsWith(`data-`),{message:`Type must start with "data-"`}),id:U.string().optional(),data:U.unknown(),transient:U.boolean().optional()}),U.looseObject({type:U.literal(`start-step`)}),U.looseObject({type:U.literal(`finish-step`)}),U.looseObject({type:U.literal(`reset-step`)}),U.looseObject({type:U.literal(`start`),messageId:U.string().optional(),messageMetadata:U.unknown().optional()}),U.looseObject({type:U.literal(`finish`),finishReason:U.enum([`stop`,`length`,`content-filter`,`tool-calls`,`error`,`other`]).optional(),messageMetadata:U.unknown().optional()}),U.looseObject({type:U.literal(`abort`),reason:U.string().optional()}),U.looseObject({type:U.literal(`message-metadata`),messageMetadata:U.unknown()})])));function Li(e){return e.type.startsWith(`data-`)}function K(){return Object.create(null)}function Ri(e){return e.type===`text`}function zi(e){return e.type.startsWith(`tool-`)}function Bi(e){return e.type===`dynamic-tool`}function q(e){return zi(e)||Bi(e)}function Vi(e){return e.type.split(`-`).slice(1).join(`-`)}function Hi(e){return Bi(e)?e.toolName:Vi(e)}var Ui={type:`deprecated`,setting:`rawInput in output-error UI message parts`,message:`Use the "input" field instead. The "rawInput" field will be removed in the next major version.`};function Wi(e){e.some(e=>e.parts.some(e=>typeof e==`object`&&!!e&&`type`in e&&typeof e.type==`string`&&(e.type===`dynamic-tool`||e.type.startsWith(`tool-`))&&`state`in e&&e.state===`output-error`&&Object.prototype.hasOwnProperty.call(e,`rawInput`)&&`rawInput`in e&&e.rawInput!==void 0))&&ai({warnings:[Ui]})}function Gi({lastMessage:e,messageId:t}){return{message:e?.role===`assistant`?e:{id:t,metadata:void 0,role:`assistant`,parts:[]},activeTextParts:K(),activeReasoningParts:K(),partialToolCalls:K()}}function Ki({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:i,onToolCall:a,onData:o}){return e.pipeThrough(new TransformStream({async transform(e,s){await r(async({state:r,write:c})=>{function l(){let e=r.message.parts,t=e.length-1;for(;t>=0&&e[t].type!==`step-start`;)t--;return e.slice(t+1)}function u(){return l().filter(q)}function d(e){let t=u().find(t=>t.toolCallId===e);if(t==null){let n=r.message.parts;for(let r=n.length-1;r>=0;r--){let i=n[r];if(q(i)&&i.toolCallId===e){t=i;break}}}if(t==null)throw new H({chunkType:`tool-invocation`,chunkId:e,message:`No tool invocation found for tool call ID "${e}".`});return t}function f(e){let t=r.message.parts.filter(q).find(t=>t.approval?.id===e);if(t==null)throw new H({chunkType:`tool-approval-response`,chunkId:e,message:`No tool invocation found for approval ID "${e}".`});return t}function p(e,t){let n=t??l().find(t=>zi(t)&&t.toolCallId===e.toolCallId),i=e,a=n;if(n!=null){n.state=e.state,a.input=i.input,a.output=i.output,a.errorText=i.errorText,a.rawInput=i.rawInput,a.preliminary=i.preliminary,e.title!==void 0&&(a.title=e.title),e.toolMetadata!==void 0&&(a.toolMetadata=e.toolMetadata),a.providerExecuted=i.providerExecuted??n.providerExecuted;let t=i.providerMetadata;if(t!=null){if(e.state===`output-available`||e.state===`output-error`){let e=n;e.resultProviderMetadata=t}else n.callProviderMetadata=t}}else r.message.parts.push({type:`tool-${e.toolName}`,toolCallId:e.toolCallId,state:e.state,title:e.title,...e.toolMetadata===void 0?{}:{toolMetadata:e.toolMetadata},input:i.input,output:i.output,rawInput:i.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted,preliminary:i.preliminary,...i.providerMetadata!=null&&(e.state===`output-available`||e.state===`output-error`)?{resultProviderMetadata:i.providerMetadata}:{},...i.providerMetadata!=null&&e.state!==`output-available`&&e.state!==`output-error`?{callProviderMetadata:i.providerMetadata}:{}})}function m(e,t){let n=t??l().find(t=>t.type===`dynamic-tool`&&t.toolCallId===e.toolCallId),i=e,a=n;if(n!=null){n.state=e.state,a.toolName=e.toolName,a.input=i.input,a.output=i.output,a.errorText=i.errorText,a.rawInput=i.rawInput??a.rawInput,a.preliminary=i.preliminary,e.title!==void 0&&(a.title=e.title),e.toolMetadata!==void 0&&(a.toolMetadata=e.toolMetadata),a.providerExecuted=i.providerExecuted??n.providerExecuted;let t=i.providerMetadata;if(t!=null){if(e.state===`output-available`||e.state===`output-error`){let e=n;e.resultProviderMetadata=t}else n.callProviderMetadata=t}}else r.message.parts.push({type:`dynamic-tool`,toolName:e.toolName,toolCallId:e.toolCallId,state:e.state,input:i.input,output:i.output,errorText:i.errorText,preliminary:i.preliminary,providerExecuted:i.providerExecuted,title:e.title,...e.toolMetadata===void 0?{}:{toolMetadata:e.toolMetadata},...i.providerMetadata!=null&&(e.state===`output-available`||e.state===`output-error`)?{resultProviderMetadata:i.providerMetadata}:{},...i.providerMetadata!=null&&e.state!==`output-available`&&e.state!==`output-error`?{callProviderMetadata:i.providerMetadata}:{}})}async function h(e){if(e!=null){let n=r.message.metadata==null?e:oi(r.message.metadata,e);t!=null&&await Fr({value:n,schema:t,context:{field:`message.metadata`,entityId:r.message.id}}),r.message.metadata=n}}switch(e.type){case`text-start`:{let t={type:`text`,text:``,providerMetadata:e.providerMetadata,state:`streaming`};r.activeTextParts[e.id]=t,r.message.parts.push(t),c();break}case`text-delta`:{let t=r.activeTextParts[e.id];if(t==null)throw new H({chunkType:`text-delta`,chunkId:e.id,message:`Received text-delta for missing text part with ID "${e.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});t.text+=e.delta,t.providerMetadata=e.providerMetadata??t.providerMetadata,c();break}case`text-end`:{let t=r.activeTextParts[e.id];if(t==null)throw new H({chunkType:`text-end`,chunkId:e.id,message:`Received text-end for missing text part with ID "${e.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});t.state=`done`,t.providerMetadata=e.providerMetadata??t.providerMetadata,delete r.activeTextParts[e.id],c();break}case`custom`:{let t={type:`custom`,kind:e.kind,providerMetadata:e.providerMetadata};r.message.parts.push(t),c();break}case`reasoning-start`:{let t={type:`reasoning`,id:e.id,text:``,providerMetadata:e.providerMetadata,state:`streaming`};r.activeReasoningParts[e.id]=t,r.message.parts.push(t),c();break}case`reasoning-delta`:{let t=r.activeReasoningParts[e.id];if(t==null)throw new H({chunkType:`reasoning-delta`,chunkId:e.id,message:`Received reasoning-delta for missing reasoning part with ID "${e.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});t.text+=e.delta,t.providerMetadata=e.providerMetadata??t.providerMetadata,c();break}case`reasoning-end`:{let t=r.activeReasoningParts[e.id];if(t==null)throw new H({chunkType:`reasoning-end`,chunkId:e.id,message:`Received reasoning-end for missing reasoning part with ID "${e.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});t.providerMetadata=e.providerMetadata??t.providerMetadata,t.state=`done`,delete r.activeReasoningParts[e.id],c();break}case`file`:case`reasoning-file`:r.message.parts.push({type:e.type,mediaType:e.mediaType,url:e.url,...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata}}),c();break;case`source-url`:r.message.parts.push({type:`source-url`,sourceId:e.sourceId,url:e.url,title:e.title,providerMetadata:e.providerMetadata}),c();break;case`source-document`:r.message.parts.push({type:`source-document`,sourceId:e.sourceId,mediaType:e.mediaType,title:e.title,filename:e.filename,providerMetadata:e.providerMetadata}),c();break;case`tool-input-start`:{let t=l().filter(zi);r.partialToolCalls[e.toolCallId]={text:``,toolName:e.toolName,index:t.length,dynamic:e.dynamic,title:e.title,toolMetadata:e.toolMetadata},e.dynamic?m({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-streaming`,input:void 0,providerExecuted:e.providerExecuted,title:e.title,toolMetadata:e.toolMetadata,providerMetadata:e.providerMetadata}):p({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-streaming`,input:void 0,providerExecuted:e.providerExecuted,title:e.title,toolMetadata:e.toolMetadata,providerMetadata:e.providerMetadata}),c();break}case`tool-input-delta`:{let t=r.partialToolCalls[e.toolCallId];if(t==null)throw new H({chunkType:`tool-input-delta`,chunkId:e.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${e.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});t.text+=e.inputTextDelta;let{value:n}=await Di(t.text);t.dynamic?m({toolCallId:e.toolCallId,toolName:t.toolName,state:`input-streaming`,input:n,title:t.title,toolMetadata:t.toolMetadata}):p({toolCallId:e.toolCallId,toolName:t.toolName,state:`input-streaming`,input:n,title:t.title,toolMetadata:t.toolMetadata}),c();break}case`tool-input-available`:e.dynamic?m({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-available`,input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:e.title,toolMetadata:e.toolMetadata}):p({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-available`,input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:e.title,toolMetadata:e.toolMetadata}),c(),a&&!e.providerExecuted&&await a({toolCall:e});break;case`tool-input-error`:{let t=l().filter(q).find(t=>t.toolCallId===e.toolCallId);(t==null?e.dynamic:t.type===`dynamic-tool`)?m({toolCallId:e.toolCallId,toolName:e.toolName,state:`output-error`,input:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,toolMetadata:e.toolMetadata}):(p({toolCallId:e.toolCallId,toolName:e.toolName,state:`output-error`,input:void 0,rawInput:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,toolMetadata:e.toolMetadata}),Wi([r.message])),c();break}case`tool-approval-request`:{let t=d(e.toolCallId);t.state=`approval-requested`,t.approval={id:e.approvalId,...e.approvalDescriptor==null?{}:{descriptor:e.approvalDescriptor},...e.reason==null?{}:{requestReason:e.reason},...e.isAutomatic===!0?{isAutomatic:!0}:{},...e.signature==null?{}:{signature:e.signature}},c();break}case`tool-approval-response`:{let t=f(e.approvalId),n=t.approval==null?{id:e.approvalId}:t.approval;t.state=`approval-responded`,t.approval={...n,id:e.approvalId,approved:e.approved,...e.reason==null?{}:{reason:e.reason}},e.providerExecuted!=null&&(t.providerExecuted=e.providerExecuted),e.providerMetadata!=null&&(t.callProviderMetadata=e.providerMetadata),c();break}case`tool-output-denied`:{let t=d(e.toolCallId);t.state=`output-denied`,c();break}case`tool-output-available`:{let t=d(e.toolCallId);t.type===`dynamic-tool`?m({toolCallId:e.toolCallId,toolName:t.toolName,state:`output-available`,input:t.input,output:e.output,preliminary:e.preliminary,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata},t):p({toolCallId:e.toolCallId,toolName:Vi(t),state:`output-available`,input:t.input,output:e.output,providerExecuted:e.providerExecuted,preliminary:e.preliminary,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata},t),c();break}case`tool-output-error`:{let t=d(e.toolCallId);t.type===`dynamic-tool`?m({toolCallId:e.toolCallId,toolName:t.toolName,state:`output-error`,input:t.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata},t):p({toolCallId:e.toolCallId,toolName:Vi(t),state:`output-error`,input:t.input,rawInput:t.rawInput,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata},t),c();break}case`start-step`:r.message.parts.push({type:`step-start`});break;case`finish-step`:break;case`reset-step`:{let e=l();r.activeTextParts=K(),r.activeReasoningParts=K(),r.partialToolCalls=K(),e.length>0&&(r.message.parts.splice(r.message.parts.length-e.length,e.length),c());break}case`start`:e.messageId!=null&&(r.message.id=e.messageId),await h(e.messageMetadata),(e.messageId!=null||e.messageMetadata!=null)&&c({updateStatus:!1});break;case`finish`:e.finishReason!=null&&(r.finishReason=e.finishReason),await h(e.messageMetadata),e.messageMetadata!=null&&c();break;case`message-metadata`:await h(e.messageMetadata),e.messageMetadata!=null&&c();break;case`error`:i?.(Error(e.errorText));break;default:if(Li(e)){if(n?.[e.type]!=null){let t=r.message.parts.findIndex(t=>`id`in t&&`data`in t&&t.id===e.id&&t.type===e.type),i=t>=0?t:r.message.parts.length;await Fr({value:e.data,schema:n[e.type],context:{field:`message.parts[${i}].data`,entityName:e.type,entityId:e.id}})}let t=e;if(t.transient){o?.(t);break}let i=t.id==null?void 0:r.message.parts.find(e=>t.type===e.type&&t.id===e.id);i==null?r.message.parts.push(t):i.data=t.data,o?.(t),c()}}s.enqueue(e)})}}))}async function qi({stream:e,onError:t,abortSignal:n}){let r=e.getReader(),i=()=>{r.cancel().catch(()=>{})};n?.aborted?i():n?.addEventListener(`abort`,i,{once:!0});try{for(;;){let{done:e}=await r.read();if(e)break}}catch(e){t?.(e)}finally{n?.removeEventListener(`abort`,i),r.releaseLock()}}j({prefix:`aitxt`,size:24}),j({prefix:`call`,size:24}),j({prefix:`aitxt`,size:24}),j({prefix:`call`,size:24}),U.record(U.string(),W.optional()),U.record(U.string(),U.string()),j({prefix:`call`,size:24}),j({prefix:`call`,size:24}),new TextEncoder,j({prefix:`aiobj`,size:24});var{atob:Ji}=globalThis,Yi=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise((t,n)=>{this.queue.push(async()=>{try{await e(),t()}catch(e){n(e)}}),this.processQueue()})}};j({prefix:`aiobj`,size:24}),U.object({token:U.string().refine(e=>e.trim().length>0),url:U.string().refine(e=>{try{let t=new URL(e);return(t.protocol===`ws:`||t.protocol===`wss:`)&&t.hostname!==``}catch{return!1}}),expiresAt:U.number().positive().max(2**53-1).optional(),tools:U.array(U.object({type:U.literal(`function`),name:U.string().min(1),description:U.string().optional(),parameters:U.record(U.string(),U.unknown())})).optional()}),j({prefix:`call`,size:24});async function Xi({response:e,url:t,fallbackMessage:n}){let r=await e.text();return new Nt({message:r||n,url:t,requestBodyValues:void 0,statusCode:e.status,responseBody:r})}async function Zi(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw new un({functionality:`FileList`,message:`FileList is not supported in the current environment`});return Promise.all(Array.from(e).map(async e=>{let{name:t,type:n}=e;return{type:`file`,mediaType:n,filename:t,url:await new Promise((t,n)=>{let r=new FileReader;r.onload=e=>{t(e.target?.result)},r.onerror=e=>n(e),r.readAsDataURL(e)})}}))}function Qi(e,t){let n=e.search(/[?#]/);return n===-1?`${e}${t}`:`${e.slice(0,n)}${t}${e.slice(n)}`}var $i=class{constructor({api:e=`/api/chat`,credentials:t,headers:n,body:r,fetch:i,prepareSendMessagesRequest:a,prepareReconnectToStreamRequest:o}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=i,this.prepareSendMessagesRequest=a,this.prepareReconnectToStreamRequest=o}async sendMessages({abortSignal:e,...t}){let n=await z(this.body),r=await z(this.headers),i=await z(this.credentials),a={...A(r),...A(t.headers)},o=await this.prepareSendMessagesRequest?.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...n,...t.body},headers:a,credentials:i,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId}),s=o?.api??this.api,c=o?.headers===void 0?a:A(o.headers),l=o?.body===void 0?{...n,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId}:o.body,u=o?.credentials??i,d=await(this.fetch??globalThis.fetch)(s,{method:`POST`,headers:{"content-type":`application/json`,...c},body:JSON.stringify(l),credentials:u,signal:e});if(!d.ok)throw await Xi({response:d,url:s,fallbackMessage:`Failed to fetch the chat response.`});if(!d.body)throw new zt({message:`The response body is empty.`});return this.processResponseStream(d.body)}async reconnectToStream(e){let t=await z(this.body),n=await z(this.headers),r=await z(this.credentials),i={...A(n),...A(e.headers)},a=await this.prepareReconnectToStreamRequest?.call(this,{api:this.api,id:e.chatId,body:{...t,...e.body},headers:i,credentials:r,requestMetadata:e.metadata}),o=a?.api??Qi(this.api,`/${e.chatId}/stream`),s=a?.headers===void 0?i:A(a.headers),c=a?.credentials??r,l=await(this.fetch??globalThis.fetch)(o,{method:`GET`,headers:s,credentials:c,signal:e.abortSignal});if(l.status===204)return null;if(!l.ok)throw await Xi({response:l,url:o,fallbackMessage:`Failed to fetch the chat response.`});if(!l.body)throw new zt({message:`The response body is empty.`});return this.processResponseStream(l.body)}},ea=class extends $i{constructor(e={}){super(e)}processResponseStream(e){return Lr({stream:e,schema:Ii}).pipeThrough(new TransformStream({async transform(e,t){if(!e.success)throw e.error;t.enqueue(e.value)}}))}},ta=class{constructor({generateId:e=xn,id:t=e(),transport:n=new ea,messageMetadataSchema:r,dataPartSchemas:i,state:a,onError:o,onToolCall:s,onFinish:c,onData:l,sendAutomaticallyWhen:u}){this.pendingMessagePreparations=new Set,this.activeResponse=void 0,this.activeResumeRequest=void 0,this.jobExecutor=new Yi,this.sendMessage=async(e,t)=>{if(e==null){await this.makeRequest({trigger:`submit-message`,messageId:this.lastMessage?.id,...t});return}let n;if(`text`in e||`files`in e){let t=new AbortController;this.pendingMessagePreparations.add(t);let r;try{r=Array.isArray(e.files)?e.files:await Zi(e.files)}finally{this.pendingMessagePreparations.delete(t)}if(t.signal.aborted)return;n={parts:[...r,...`text`in e&&e.text!=null?[{type:`text`,text:e.text}]:[]]}}else n=e;if(e.messageId!=null){let t=this.state.messages.findIndex(t=>t.id===e.messageId);if(t===-1)throw new B({parameter:`message.messageId`,value:e.messageId,message:`message with id ${e.messageId} not found`});if(this.state.messages[t].role!==`user`)throw new B({parameter:`message.messageId`,value:e.messageId,message:`message with id ${e.messageId} is not a user message`});this.state.messages=this.state.messages.slice(0,t+1),this.state.replaceMessage(t,{id:e.messageId,...n,role:n.role??`user`,metadata:e.metadata})}else this.state.pushMessage({...n,id:n.id??this.generateId(),role:n.role??`user`,metadata:e.metadata});await this.makeRequest({trigger:`submit-message`,messageId:e.messageId,...t})},this.regenerate=async({messageId:e,...t}={})=>{let n=e==null?this.state.messages.length-1:this.state.messages.findIndex(t=>t.id===e);if(n===-1)throw new B({parameter:`messageId`,value:e,message:`message ${e} not found`});this.state.messages=this.state.messages.slice(0,this.messages[n].role===`assistant`?n:n+1),await this.makeRequest({trigger:`regenerate-message`,messageId:e,...t})},this.resumeStream=async(e={})=>{await this.makeRequest({trigger:`resume-stream`,...e})},this.clearError=()=>{this.status===`error`&&(this.state.error=void 0,this.setStatus({status:`ready`}))},this.addToolApprovalResponse=async({id:e,approved:t,reason:n,options:r})=>this.jobExecutor.run(async()=>{let i=this.state.messages,a=i[i.length-1],o=r=>q(r)&&r.state===`approval-requested`&&r.approval.id===e?{...r,state:`approval-responded`,approval:{...r.approval,id:e,approved:t,reason:n}}:r;this.state.replaceMessage(i.length-1,{...a,parts:a.parts.map(o)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(o)),this.status!==`streaming`&&this.status!==`submitted`&&this.sendAutomaticallyWhen&&this.shouldSendAutomatically().then(e=>{e&&this.makeRequest({trigger:`submit-message`,messageId:this.lastMessage?.id,...r})})}),this.addToolOutput=async({state:e=`output-available`,toolCallId:t,output:n,errorText:r,options:i})=>this.jobExecutor.run(async()=>{let a=this.state.messages,o=a[a.length-1],s=i=>q(i)&&i.toolCallId===t?{...i,state:e,output:n,errorText:r}:i;this.state.replaceMessage(a.length-1,{...o,parts:o.parts.map(s)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(s)),this.status!==`streaming`&&this.status!==`submitted`&&this.sendAutomaticallyWhen&&this.shouldSendAutomatically().then(e=>{e&&this.makeRequest({trigger:`submit-message`,messageId:this.lastMessage?.id,...i})})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{var e,t;for(let e of this.pendingMessagePreparations)e.abort();(e=this.activeResumeRequest)==null||e.abortController.abort(),(t=this.activeResponse)==null||t.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=i,this.state=a,this.onError=o,this.onToolCall=s,this.onFinish=c,this.onData=l,this.sendAutomaticallyWhen=u}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async shouldSendAutomatically(){if(!this.sendAutomaticallyWhen)return!1;let e=this.sendAutomaticallyWhen({messages:this.state.messages});return e&&typeof e==`object`&&`then`in e?await e:e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:i}){var a,o;let s=new AbortController,c=e===`resume-stream`?{abortController:s}:void 0;c&&((a=this.activeResumeRequest)==null||a.abortController.abort(),this.activeResumeRequest=c);let l=()=>c==null||this.activeResumeRequest===c,u=()=>{this.activeResumeRequest===c&&(this.activeResumeRequest=void 0)},d;if(e===`resume-stream`)try{let e=await this.transport.reconnectToStream({chatId:this.id,abortSignal:s.signal,metadata:t,headers:n,body:r});if(s.signal.aborted||!l()){await e?.cancel().catch(()=>{}),l()&&this.setStatus({status:`ready`}),u();return}if(e==null){this.setStatus({status:`ready`}),u();return}d=e}catch(e){if(s.signal.aborted||e.name===`AbortError`){l()&&this.setStatus({status:`ready`}),u();return}if(!l())return;this.onError&&e instanceof Error&&this.onError(e),this.setStatus({status:`error`,error:e}),u();return}this.setStatus({status:`submitted`,error:void 0});let f=this.lastMessage,p=!1,m=!1,h=!1,g;try{let a={state:Gi({lastMessage:e===`resume-stream`||e===`regenerate-message`?void 0:this.state.snapshot(f),messageId:this.generateId()}),abortController:s};g=a,a.abortController.signal.addEventListener(`abort`,()=>{p=!0}),this.activeResponse=a;let o;if(o=e===`resume-stream`?d:await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:a.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:i}),await qi({stream:Ki({stream:o,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:e=>this.jobExecutor.run(()=>a.abortController.signal.aborted?Promise.resolve():e({state:a.state,write:({updateStatus:e=!0}={})=>{a.abortController.signal.aborted||(e&&this.setStatus({status:`streaming`}),a.state.message.id===this.lastMessage?.id?this.state.replaceMessage(this.state.messages.length-1,a.state.message):this.state.pushMessage(a.state.message))}})),onError:e=>{throw e}}),abortSignal:a.abortController.signal,onError:e=>{throw e}}),p)return l()&&this.setStatus({status:`ready`}),null;l()&&this.setStatus({status:`ready`})}catch(e){if(p||e.name===`AbortError`)return p=!0,l()&&this.setStatus({status:`ready`}),null;if(!l())return null;h=!0,e instanceof TypeError&&(e.message.toLowerCase().includes(`fetch`)||e.message.toLowerCase().includes(`network`))&&(m=!0),this.onError&&e instanceof Error&&this.onError(e),this.setStatus({status:`error`,error:e})}finally{try{g&&((o=this.onFinish)==null||o.call(this,{message:g.state.message,messages:this.state.messages,isAbort:p,isDisconnect:m,isError:h,finishReason:g.state.finishReason}))}finally{this.activeResponse===g&&(this.activeResponse=void 0),u()}}!h&&await this.shouldSendAutomatically()&&await this.makeRequest({trigger:`submit-message`,messageId:this.lastMessage?.id,metadata:t,headers:n,body:r})}};function na({messages:e}){let t=e[e.length-1];if(!t||t.role!==`assistant`)return!1;let n=t.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),r=t.parts.slice(n+1).filter(q).filter(e=>!e.providerExecuted);return r.length>0&&r.every(e=>e.state===`output-available`&&e.preliminary!==!0||e.state===`output-error`)}function ra(e){return new ea({api:Le(`/`,`Chat/Messages/`),credentials:`include`,body:{orgId:e}})}var ia=e(t(((e,t)=>{function n(e,t){if(typeof e!=`function`)throw TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...i){clearTimeout(n);let a=Date.now(),o=t-(a-r);o<=0?(r=a,e.apply(this,i)):n=setTimeout(()=>{r=Date.now(),e.apply(this,i)},o)}}t.exports=n}))(),1),aa=(e,t,n)=>{if(!t.has(e))throw TypeError(`Cannot `+n)},J=(e,t,n)=>(aa(e,t,`read from private field`),n?n.call(e):t.get(e)),Y=(e,t,n)=>{if(t.has(e))throw TypeError(`Cannot add the same private member more than once`);t instanceof WeakSet?t.add(e):t.set(e,n)},X=(e,t,n,r)=>(aa(e,t,`write to private field`),r?r.call(e,n):t.set(e,n),n);function oa(e,t){return t==null?e:(0,ia.default)(e,t)}function sa(e){return Array.isArray(e)?[...e]:typeof e==`object`&&e&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)?{...e}:e}var Z,ca,la,ua,da,fa,Q,pa,ma,ha=class{constructor(e=[]){Y(this,Z,void 0),Y(this,ca,`ready`),Y(this,la,void 0),Y(this,ua,new Set),Y(this,da,new Set),Y(this,fa,new Set),this.pushMessage=e=>{X(this,Z,J(this,Z).concat(e)),J(this,Q).call(this)},this.popMessage=()=>{X(this,Z,J(this,Z).slice(0,-1)),J(this,Q).call(this)},this.replaceMessage=(e,t)=>{X(this,Z,[...J(this,Z).slice(0,e),this.snapshot(t),...J(this,Z).slice(e+1)]),J(this,Q).call(this)},this.snapshot=e=>{if(typeof e!=`object`||!e||!(`parts`in e)||!Array.isArray(e.parts))return e;let t=e,n={...t,parts:t.parts.map(e=>({...e}))};return`metadata`in t&&(n.metadata=sa(t.metadata)),n},this[`~registerMessagesCallback`]=(e,t)=>{let n=t?oa(e,t):e;return J(this,ua).add(n),()=>{J(this,ua).delete(n)}},this[`~registerStatusCallback`]=e=>(J(this,da).add(e),()=>{J(this,da).delete(e)}),this[`~registerErrorCallback`]=e=>(J(this,fa).add(e),()=>{J(this,fa).delete(e)}),Y(this,Q,()=>{J(this,ua).forEach(e=>e())}),Y(this,pa,()=>{J(this,da).forEach(e=>e())}),Y(this,ma,()=>{J(this,fa).forEach(e=>e())}),X(this,Z,e)}get status(){return J(this,ca)}set status(e){X(this,ca,e),J(this,pa).call(this)}get error(){return J(this,la)}set error(e){X(this,la,e),J(this,ma).call(this)}get messages(){return J(this,Z)}set messages(e){X(this,Z,[...e]),J(this,Q).call(this)}};Z=new WeakMap,ca=new WeakMap,la=new WeakMap,ua=new WeakMap,da=new WeakMap,fa=new WeakMap,Q=new WeakMap,pa=new WeakMap,ma=new WeakMap;var $,ga=class extends ta{constructor({messages:e,...t}){let n=new ha(e);super({...t,state:n}),Y(this,$,void 0),this[`~registerMessagesCallback`]=(e,t)=>J(this,$)[`~registerMessagesCallback`](e,t),this[`~registerStatusCallback`]=e=>J(this,$)[`~registerStatusCallback`](e),this[`~registerErrorCallback`]=e=>J(this,$)[`~registerErrorCallback`](e),X(this,$,n)}};$=new WeakMap;function _a({throttle:e,experimental_throttle:t,resume:n=!1,...r}={}){let i=e??t,a=(0,T.useRef)({});`chat`in r||(a.current={onToolCall:r.onToolCall,onData:r.onData,onFinish:r.onFinish,onError:r.onError,sendAutomaticallyWhen:r.sendAutomaticallyWhen,transport:r.transport});let o,s=()=>a.current.transport??(o??=new ea),c={...r,transport:{sendMessages:e=>s().sendMessages(e),reconnectToStream:e=>s().reconnectToStream(e)},onToolCall:e=>{var t;return(t=a.current).onToolCall?.call(t,e)},onData:e=>{var t;return(t=a.current).onData?.call(t,e)},onFinish:e=>{var t;return(t=a.current).onFinish?.call(t,e)},onError:e=>{var t;return(t=a.current).onError?.call(t,e)},sendAutomaticallyWhen:e=>{var t;return(t=a.current).sendAutomaticallyWhen?.call(t,e)??!1}},l=`chat`in r?r.chat:r.id,{chat:u,isExternallyManaged:d}=(0,T.useMemo)(()=>({chat:`chat`in r?r.chat:new ga(c),isExternallyManaged:`chat`in r}),[l]);(0,T.useEffect)(()=>{if(!d)return()=>{u.stop()}},[u,d]);let f=(0,T.useMemo)(()=>({messages:u.messages}),[u]),p=(0,T.useCallback)(e=>{let t=!0,n=u[`~registerMessagesCallback`](()=>{t&&(f.messages=u.messages,e())},i);return f.messages=u.messages,()=>{t=!1,n()}},[u,f,i]),m=(0,T.useCallback)(()=>f.messages,[f]),h=(0,T.useSyncExternalStore)(p,m,m),g=(0,T.useCallback)(e=>u[`~registerStatusCallback`](()=>{(u.status===`ready`||u.status===`error`)&&(f.messages=u.messages),e()}),[u,f]),_=(0,T.useCallback)(()=>u.status,[u]),v=(0,T.useSyncExternalStore)(g,_,_),y=(0,T.useSyncExternalStore)(u[`~registerErrorCallback`],()=>u.error,()=>u.error),b=(0,T.useCallback)(e=>{typeof e==`function`&&(e=e(u.messages)),u.messages=e},[u]);return(0,T.useEffect)(()=>{n&&u.resumeStream()},[n,u]),{id:u.id,messages:h,setMessages:b,sendMessage:u.sendMessage,regenerate:u.regenerate,clearError:u.clearError,stop:u.stop,error:y,resumeStream:u.resumeStream,status:v,addToolResult:u.addToolOutput,addToolOutput:u.addToolOutput,addToolApprovalResponse:u.addToolApprovalResponse}}function va({input:e,setInput:t,onSubmit:n,disabled:r,autoFocus:i}){let a=(0,T.useRef)(null);return(0,T.useEffect)(()=>{i&&!r&&a.current?.focus()},[i,r]),(0,E.jsxs)(`form`,{onSubmit:n,className:`input-area`,children:[(0,E.jsx)(`input`,{ref:a,value:e,onChange:e=>t(e.target.value),placeholder:`Type a message...`,disabled:r}),(0,E.jsx)(`button`,{type:`submit`,disabled:r||!e.trim(),children:(0,E.jsx)(vt,{size:18})})]})}function ya(){return(0,E.jsxs)(`div`,{className:`loading-state`,children:[(0,E.jsx)(Ze,{className:`animate-spin`,size:24}),(0,E.jsx)(`p`,{children:`Loading conversation...`})]})}var ba={name:`collectFeedback`,description:`Collects feedback from the user by fetching a link to a pre-populated GitHub Discussion. Use this if the user lets us know we did something well, or if the user seems frustrated, or wants to report a bug.`,inputSchema:l({feedbackSummary:y().describe(`A brief summary of the feedback, used as the discussion title.`),feedbackDetails:y().describe(`Detailed feedback from the user or agent observation.`),recap:y().describe(`A sanitized recap of what the agent and user did together and if it was successful. No sensitive information.`)})};async function xa({input:{feedbackSummary:e,feedbackDetails:t,recap:n}}){let r=e,i=`${t}\n\n${n}`;return{success:!0,url:`https://github.com/HarperFast/harper-agent/discussions/new?category=usage-feedback&title=${encodeURIComponent(r)}&body=${encodeURIComponent(i)}`,message:`Feedback URL created! Ask the user to open it in their browser, and they will be brought to a form to approve the details of the feedback.`}}var Sa={...ba,icon:gt,execute:xa},Ca={name:`createApp`,description:`Create a new Harper app with the specified name and template type.`,inputSchema:l({name:y().trim(),type:v(_e)})};async function wa({input:{name:e,type:t},instanceClientParams:n,baseURL:r}){let i=Ge(e),a=he(fe,`id`,t);if(!a)return{success:!1,message:`Error: Invalid template type, ${t}, please choose from: ${fe.map(e=>e.id).join(`, `)}`};let o=se.loading(`Creating from template...`,{description:`This may take a bit.`,duration:3e5});try{await be({...n,project:i,template:a.npm||a.githubUrl})}catch(e){return{success:!1,message:`Error: ${e}`}}De(`ReloadApplicationRootEntries`,!0),se.loading(`Created successfully!`,{description:`${i} created! Restarting the HTTP service...`,id:o,duration:3e5});try{await Qe({...n,operation:`restart_service`,replicated:n.entityType===`cluster`})}catch(e){return{success:!1,message:`Error: ${e}`}}return se.success(`Created successfully!`,{description:`${i} created!`,id:o,duration:5e3}),{success:!0,message:`App "${i}" created successfully.`,webURL:r}}var Ta={...Ca,icon:Pe,execute:wa,requiresApproval:!0},Ea={name:`deleteTableRecords`,description:`Deletes records in a particular table in a particular database on the server by their primary keys.`,inputSchema:l({database:y().trim(),table:y().trim(),primaryKeys:m(y())})};async function Da({input:{database:e,table:t,primaryKeys:n},instanceClientParams:r,params:i}){try{let a=await He({...r,databaseName:e,tableName:t,hashValues:n}),{databaseName:o,tableName:s}=i;return await Be.invalidateQueries({queryKey:[r.entityId,o,s]}),{success:!0,data:a}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Oa={...Ea,icon:it,execute:Da,requiresApproval:!0},ka={name:`dropComponentFile`,description:`Drops a component file by its full path (which was returned by getComponents)`,inputSchema:l({path:y().trim()})};async function Aa({input:{path:e},instanceClientParams:t}){try{let n=e.split(`/`),r=n.shift(),i=n.join(`/`);return{success:!0,data:await de({...t,file:i,project:r})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var ja={...ka,icon:Ue,execute:Aa,requiresApproval:!0},Ma={name:`getAnalytics`,description:`Retrieves analytics metrics for the server, such as CPU usage or database operations (reads, writes, messages).`,inputSchema:l({metricName:y().describe(`The name of the metric to retrieve.`),startTime:u().describe(`The start of the time range for the metric, in milliseconds since the Unix epoch.`),endTime:u().describe(`The end of the time range for the metric, in milliseconds since the Unix epoch.`)})};async function Na({input:e,instanceClientParams:t}){try{let{metricName:n,startTime:r,endTime:i}=e;return{success:!0,data:await nt({metric:n,startTime:r,endTime:i,instanceParams:t})}}catch(e){return{success:!1,message:`Error retrieving analytics: ${e}`}}}var Pa={...Ma,icon:ct,execute:Na},Fa={name:`getComponentFile`,description:`Returns the contents of a component file by its full path (which was returned by getComponents)`,inputSchema:l({path:y().trim()})};async function Ia({input:{path:e},instanceClientParams:t}){try{let n=e.split(`/`),r=n.shift(),i=n.join(`/`);return{success:!0,data:await qe({...t,file:i,project:r})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var La={...Fa,icon:pe,execute:Ia},Ra={name:`getComponents`,description:`Retrieves a tree of all the component (files and folders) names and sizes stored on the server.`,inputSchema:l({})};async function za({instanceClientParams:e}){try{let t=await We(e),{rootEntries:n}=ve(t.entries);return{success:!0,items:me(n).items}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Ba={...Ra,icon:ge,execute:za},Va={name:`getDescribeAll`,description:`Retrieves a map of the names of databases and their tables stored on the server.`,inputSchema:l({})};async function Ha({instanceClientParams:e}){try{return{success:!0,map:await Xe(e)}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Ua={...Va,icon:we,execute:Ha},Wa={name:`getDescribeTable`,description:`Returns the schema metadata describing a particular table in a particular database on the server.`,inputSchema:l({database:y().trim(),table:y().trim()})};async function Ga({input:{database:e,table:t},instanceClientParams:n}){try{return{success:!0,data:await Fe({...n,databaseName:e,tableName:t})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Ka={...Wa,icon:Je,execute:Ga},qa={name:`getUserContext`,description:`Retrieves the context of what the user is looking at on their screen, such as the current page, the file they are viewing, the database and table visible to them, that sort of thing.`,inputSchema:l({})};async function Ja({instanceClientParams:e,params:t}){let n=je();if(n.includes(`/databases`)){let{databaseName:e,tableName:n}=t;return{success:!0,description:`viewing the database`,data:{databaseName:e,tableName:n}}}if(n.endsWith(`/apis`))return{success:!0,description:`viewing the APIs`};if(n.endsWith(`/status`))return{success:!0,description:`viewing the status graphs`};if(n.endsWith(`/logs`))return{success:!0,description:`viewing the logs`};if(n.includes(`/config/`))return{success:!0,description:`viewing the configuration pages`};let r=oe(`FileFocused/${e.entityId}`,void 0),i=oe(`FolderOpened/${e.entityId}`,[]),a=oe(`FileSelected/${e.entityId}`,[]);return r?{success:!0,description:`editing application files`,data:{openedPath:r,expandedItems:i,selectedItems:a}}:{success:!0,description:n}}var Ya={...qa,icon:Ye,execute:Ja},Xa={name:`insertTableRecords`,description:`Inserts one or more records into a particular table in a particular database on the server.`,inputSchema:l({database:y().trim(),table:y().trim(),records:m(i())})};async function Za({input:{database:e,table:t,records:n},instanceClientParams:r,params:i}){try{let a=await Ie({...r,databaseName:e,tableName:t,records:n}),{databaseName:o,tableName:s}=i;return await Be.invalidateQueries({queryKey:[r.entityId,o,s]}),{success:!0,data:a}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Qa={...Xa,icon:it,execute:Za,requiresApproval:!0},$a={name:`listAnalyticsMetrics`,description:`Lists the available analytics metric names available for calling getAnalytics upon.`,inputSchema:l({metricTypes:v([`builtin`,`custom`]),customWindowMS:u().optional().describe(`Default to one week time window for finding custom metrics.`)})};async function eo({metricTypes:e,customWindowMS:t,instanceParams:n}){let{data:r}=await n.instanceClient.post(`/`,{operation:`list_analytics_metrics`,metricTypes:e,customWindowMS:t});return r}async function to({input:e,instanceClientParams:t}){try{let{metricTypes:n,customWindowMS:r}=e;return{success:!0,metricNames:await eo({metricTypes:n,customWindowMS:r,instanceParams:t})}}catch(e){return{success:!1,message:`Error retrieving analytics: ${e}`}}}var no={...$a,icon:ct,execute:to},ro=[`adding-tables-with-schemas`,`automatic-apis`,`caching`,`checking-authentication`,`creating-a-fabric-account-and-cluster`,`creating-harper-apps`,`custom-resources`,`defining-relationships`,`delegating-to-the-built-in-agent`,`deploying-to-harper-fabric`,`extending-tables`,`handling-binary-data`,`load-env`,`logging`,`programmatic-table-requests`,`querying-rest-apis`,`real-time-apps`,`schema-design-tooling`,`serving-web-content`,`typescript-type-stripping`,`using-blob-datatype`,`v5-upgrade`,`vector-indexing`],io={"adding-tables-with-schemas":"---\nname: adding-tables-with-schemas\ndescription: Guidelines for adding tables to a Harper database using GraphQL schemas.\nmetadata:\n mode: synthesized\n---\n\n# Adding Tables with Schemas\n\nInstructions for the agent to follow when adding tables to a Harper database.\n\n## When to Use\n\nUse this skill when you need to define new data structures or modify existing ones in a Harper database.\n\n## How It Works\n\n1. **Create Dedicated Schema Files**: Prefer having a dedicated schema `.graphql` file for each table. Check the `config.yaml` file under `graphqlSchema.files` to see how it's configured. It typically accepts wildcards (e.g., `schemas/*.graphql`), but may be configured to point at a single file.\n2. **Use Directives**: All available directives for defining your schema are defined in `node_modules/harper/schema.graphql`. Common directives include `@table`, `@export`, `@primaryKey`, `@indexed`, and `@relationship`.\n3. **Define Relationships**: Link tables together using the `@relationship` directive. For more details, see the [Defining Relationships](defining-relationships.md) skill.\n4. **Enable Automatic APIs**: If you add `@table @export` to a schema type, Harper automatically sets up REST and WebSocket APIs for basic CRUD operations against that table. **Important**: REST endpoints also require `rest: true` in `config.yaml` — without it, `@export`ed tables will not respond to HTTP requests. For a detailed list of available endpoints and how to use them, see the [Automatic REST APIs](automatic-apis.md) skill.\n - `GET /{TableName}`: Describes the resource itself — table, database, and declared attributes. No trailing slash.\n - `GET /{TableName}/`: Lists all records (supports filtering, sorting, and pagination via query parameters). See the [Querying REST APIs](querying-rest-apis.md) skill for details.\n - `GET /{TableName}/{id}`: Retrieves a single record by its primary key.\n - `POST /{TableName}/`: Creates a record and returns `201` with the Harper-assigned primary key in the `Location` response header (the bare key, not a URL). **The trailing slash is required** — `POST /{TableName}` returns `404`, and `POST /{TableName}/{id}` returns `405`.\n - `PUT /{TableName}/{id}`: Creates **or replaces** the record at `{id}` (upsert). **Properties omitted from the body are removed** — send the complete record, or use `PATCH` to change a subset. Three exceptions survive the replacement: an `@updatedTime` attribute is re-stamped with the time of the write, a `@createdTime` attribute keeps its original value, and the primary key is forced to match the `{id}` in the URL, so a mismatched key in the body cannot create a second record.\n - `PATCH /{TableName}/{id}`: Merges the request body into the existing record, preserving unspecified properties. The merge is **shallow** — a nested object in the body replaces the stored one wholesale rather than being deep-merged.\n - `DELETE /{TableName}/{id}`: Deletes a single record by its primary key.\n - `DELETE /{TableName}/`: Deletes every record matching the query parameters. **With no query parameters it matches — and deletes — every record in the table.** Always pass a filter unless emptying the table is the intent.\n5. **Consider Table Extensions**: If you are going to [extend the table](./extending-tables.md) in your resources, then do not `@export` the table from the schema.\n\n## Examples\n\nIn a hypothetical `schemas/ExamplePerson.graphql`:\n\n```graphql\ntype ExamplePerson @table @export {\n id: ID @primaryKey\n name: String\n tag: String @indexed\n}\n```\n","automatic-apis":`---
17
17
  name: automatic-apis
18
18
  description: How to use Harper's automatically generated REST and WebSocket APIs.
19
19
  metadata:
@@ -400,6 +400,7 @@ metadata:
400
400
  - >-
401
401
  reference/v5/resources/resource-api.md#\`getCurrentUser(): User |
402
402
  undefined\`
403
+ - 'reference/v5/resources/resource-api.md#\`getContext(): Context\`'
403
404
  - reference/v5/resources/resource-api.md#Session and Login from a Resource
404
405
  - reference/v5/security/jwt-authentication.md#Create Authentication Tokens
405
406
  - reference/v5/security/jwt-authentication.md#Using the Operation Token
@@ -411,8 +412,8 @@ metadata:
411
412
  - reference/v5/security/jwt-authentication.md#Token Expiry Configuration
412
413
  - reference/v5/security/jwt-authentication.md#When to Use JWT Auth
413
414
  - reference/v5/security/jwt-authentication.md#Security Notes
414
- sourceCommit: 677ad213d67822e109c83619e181ca23a59823db
415
- inputHash: 084363f039abfe73
415
+ sourceCommit: 9e6ecf87dd25bb488ad44dc2876ca6439ccd682e
416
+ inputHash: 1837f39fdfe06fac
416
417
  ---
417
418
 
418
419
  # Checking Authentication
@@ -421,207 +422,100 @@ Instructions for the agent to handle user authentication, sessions, and JWT toke
421
422
 
422
423
  ## When to Use
423
424
 
424
- Apply this rule when implementing login/logout flows, protecting Resource endpoints by checking the current user, issuing or refreshing JWT tokens, or configuring token expiry in Harper. Use it whenever a custom Resource needs to authenticate callers or mint credentials for downstream consumers. See [custom-resources.md](custom-resources.md) for the broader Resource authoring context.
425
+ Apply this rule when implementing login/logout flows, reading the current authenticated user, issuing or refreshing JWT tokens, or minting scoped tokens from a custom Resource. Use it whenever a Resource must gate behavior on identity or credentials. See [custom-resources.md](custom-resources.md) for the broader Resource authoring model.
425
426
 
426
427
  ## How It Works
427
428
 
428
- 1. **Check the current authenticated user**: Call \`getCurrentUser()\` inside any Resource method. It returns the user object (with \`username\`, \`role\`, and \`role.permission\`) or \`undefined\` if unauthenticated. Guard endpoints by returning a 401 when no user is present.
429
-
430
- \`\`\`javascript
431
- async get(target) {
432
- const user = this.getCurrentUser();
433
- if (!user) return new Response(null, { status: 401 });
434
- return { username: user.username, role: user.role };
435
- }
436
- \`\`\`
437
-
438
- 2. **Enable sessions before using login/logout**: Set \`authentication.enableSessions: true\` in \`harperdb-config.yaml\`. Without this, \`context.login\` and \`context.session\` are unavailable.
429
+ ### 1. Reading the Current Authenticated User
439
430
 
440
- 3. **Implement login via \`getContext()\`**: Call \`this.getContext()\` to obtain the request context, then call \`context.login(username, password)\` to verify credentials and establish a session cookie.
431
+ **In an instance method**, call \`getCurrentUser()\` to get the user associated with the current request, or \`undefined\` if unauthenticated. The returned object exposes \`username\`, \`role\`, and \`role.permission\` flags.
441
432
 
442
- \`\`\`javascript
443
- export class SignIn extends Resource {
444
- async post(_target, data) {
445
- const context = this.getContext();
446
- try {
447
- await context.login(data.username, data.password);
448
- } catch {
449
- return new Response('Invalid credentials', { status: 403 });
450
- }
451
- return new Response('Logged in', { status: 200 });
452
- }
453
- }
454
- \`\`\`
433
+ **In a static verb**, read the user from the \`context\` argument instead — \`context.user\`:
455
434
 
456
- 4. **Implement logout**: Delete the session via \`context.session.delete(context.session.id)\`.
457
-
458
- \`\`\`javascript
459
- export class SignOut extends Resource {
460
- async post() {
461
- const context = this.getContext();
462
- if (!context.session) return new Response(null, { status: 401 });
463
- await context.session.delete(context.session.id);
464
- return new Response('Logged out', { status: 200 });
465
- }
466
- }
467
- \`\`\`
468
-
469
- Cookie-based sessions are intended for browser clients. For non-browser clients, use JWT issuance (steps below).
470
-
471
- 5. **Create authentication tokens**: Call \`create_authentication_tokens\` with credentials. No \`Authorization\` header is required for this operation.
472
-
473
- \`\`\`json
474
- {
475
- "operation": "create_authentication_tokens",
476
- "username": "username",
477
- "password": "password"
478
- }
479
- \`\`\`
435
+ \`\`\`javascript
436
+ static async get(_target, context) {
437
+ const user = context?.user;
438
+ if (!user) return new Response(null, { status: 401 });
439
+ return { username: user.username, role: user.role };
440
+ }
441
+ \`\`\`
480
442
 
481
- Response:
443
+ ### 2. Reading the Full Context
482
444
 
483
- \`\`\`json
484
- {
485
- "operation_token": "<jwt-operation-token>",
486
- "refresh_token": "<jwt-refresh-token>"
487
- }
488
- \`\`\`
445
+ **In an instance method**, call \`getContext()\` to retrieve the current context, which includes:
489
446
 
490
- 6. **Use the operation token**: Pass it as a \`Bearer\` token in the \`Authorization\` header on subsequent requests.
447
+ - \`user\` — User object with username, role, and authorization information
448
+ - \`transaction\` — The current transaction
491
449
 
492
- \`\`\`bash
493
- curl --location --request POST 'http://localhost:9925' \\
494
- --header 'Content-Type: application/json' \\
495
- --header 'Authorization: Bearer <operation_token>' \\
496
- --data-raw '{
497
- "operation": "search_by_hash",
498
- "schema": "dev",
499
- "table": "dog",
500
- "hash_values": [1],
501
- "get_attributes": ["*"]
502
- }'
503
- \`\`\`
450
+ **In a static verb**, the context is the trailing argument:
504
451
 
505
- 7. **Refresh an expired operation token**: When the \`operation_token\` expires, use \`refresh_operation_token\` and pass the \`refresh_token\` as \`Bearer <refresh_token>\`.
452
+ - \`(target, context)\` for \`get\`/\`delete\`
453
+ - \`(target, data, context)\` for \`put\`/\`patch\`/\`post\`
506
454
 
507
- \`\`\`bash
508
- curl --location --request POST 'http://localhost:9925' \\
509
- --header 'Content-Type: application/json' \\
510
- --header 'Authorization: Bearer <refresh_token>' \\
511
- --data-raw '{
512
- "operation": "refresh_operation_token"
513
- }'
514
- \`\`\`
455
+ When triggered by HTTP, the context also exposes \`url\`, \`method\`, \`headers\`, \`responseHeaders\`, \`pathname\`, \`host\`, \`ip\`, \`body\`, \`data\`, \`lastModified\`, and \`requestContext\`.
515
456
 
516
- Response:
457
+ ### 3. Handling Sessions and Login
517
458
 
518
- \`\`\`json
519
- {
520
- "operation_token": "<new-jwt-operation-token>"
521
- }
522
- \`\`\`
459
+ Enable sessions in \`harper-config.yaml\`:
523
460
 
524
- When both tokens have expired, call \`create_authentication_tokens\` again with username and password.
461
+ \`\`\`yaml
462
+ authentication:
463
+ enableSessions: true
464
+ \`\`\`
525
465
 
526
- 8. **Mint scoped tokens for limited access**: A super user can embed an inline role in \`create_authentication_tokens\` using the same \`permission\` structure as \`add_role\`. Include \`expires_in\` to control lifetime. Do not include a \`password\` field. The \`username\` is attribution only and must not match an existing user.
466
+ Use \`context.login\` in a static \`post\` verb to verify credentials and establish a session cookie:
527
467
 
528
- \`\`\`json
529
- {
530
- "operation": "create_authentication_tokens",
531
- "username": "reporting-service",
532
- "role": {
533
- "permission": {
534
- "operations": ["read_only"],
535
- "dev": {
536
- "tables": {
537
- "dog": {
538
- "read": true,
539
- "insert": false,
540
- "update": false,
541
- "delete": false,
542
- "attribute_permissions": []
543
- }
544
- }
545
- }
546
- }
547
- },
548
- "expires_in": "7d"
549
- }
550
- \`\`\`
468
+ \`\`\`javascript
469
+ export class SignIn extends Resource {
470
+ static async post(_target, data, context) {
471
+ const { username, password } = (await data) ?? {};
472
+ try {
473
+ await context.login(username, password);
474
+ } catch {
475
+ return new Response('Invalid credentials', { status: 403 });
476
+ }
477
+ return new Response('Logged in', { status: 200 });
478
+ }
479
+ }
551
480
 
552
- Key constraints for scoped tokens:
553
- - No refresh token is issued; no user record is created.
554
- - Scoped tokens cannot be revoked before expiry — choose short \`expires_in\` values.
555
- - \`super_user\` and \`cluster_user\` are always forced to \`false\` in the embedded role.
556
- - In mixed-version clusters, only nodes with scoped-token support accept these tokens; older nodes return 401.
481
+ export class SignOut extends Resource {
482
+ static async post(_target, _data, context) {
483
+ if (!context?.session?.user) return new Response(null, { status: 401 });
484
+ await context.session.update({ user: null });
485
+ return new Response('Logged out', { status: 200 });
486
+ }
487
+ }
488
+ \`\`\`
557
489
 
558
- 9. **Issue tokens from a custom Resource using \`server.operation\`**: Import \`server\` from \`harper\` and call \`server.operation()\` to mint tokens programmatically. Pass \`true\` as the **third argument** to run the operation as the current authenticated user; omit it when supplying credentials directly.
490
+ - \`context.login(username, password)\` verifies credentials and sets the session cookie on success.
491
+ - To end a session, call \`context.session.update({ user: null })\` — \`update\` is the session's only mutator.
492
+ - \`context.session\` is an empty object (not \`undefined\`) when sessions are enabled and no session cookie is present; test \`context?.session?.user\` to detect an established session.
493
+ - Cookie-based sessions are for browser clients. For non-browser clients, use JWT issuance.
559
494
 
560
- \`\`\`javascript
561
- import { Resource, server } from 'harper';
562
-
563
- export class IssueTokens extends Resource {
564
- static async get(_target, context) {
565
- const { operation_token, refresh_token } = await server.operation(
566
- { operation: 'create_authentication_tokens' },
567
- context,
568
- true,
569
- );
570
- return { operation_token, refresh_token };
571
- }
495
+ ### 4. Creating Authentication Tokens
572
496
 
573
- static async post(_target, data) {
574
- const { username, password } = await data;
575
- if (!username || !password) {
576
- return new Response('username and password required', { status: 400 });
577
- }
578
- const { operation_token, refresh_token } = await server.operation({
579
- operation: 'create_authentication_tokens',
580
- username,
581
- password,
582
- });
583
- return { operation_token, refresh_token };
584
- }
585
- }
497
+ Call \`create_authentication_tokens\` with credentials in the body — no \`Authorization\` header is required when \`username\` and \`password\` are supplied:
586
498
 
587
- export class RefreshJWT extends Resource {
588
- static async post(_target, data) {
589
- const { refresh_token } = await data;
590
- if (!refresh_token) {
591
- return new Response('refresh_token required', { status: 400 });
592
- }
593
- const { operation_token } = await server.operation({
594
- operation: 'refresh_operation_token',
595
- refresh_token,
596
- });
597
- return { operation_token };
598
- }
599
- }
600
- \`\`\`
601
-
602
- 10. **Configure token expiry**: Set timeouts in \`harper-config.yaml\` under the \`authentication\` section. Values follow the \`jsonwebtoken\` duration string format (e.g., \`1d\`, \`12h\`, \`60m\`).
499
+ \`\`\`json
500
+ {
501
+ "operation": "create_authentication_tokens",
502
+ "username": "username",
503
+ "password": "password"
504
+ }
505
+ \`\`\`
603
506
 
604
- \`\`\`yaml
605
- authentication:
606
- operationTokenTimeout: 1d # Default: 1 day
607
- refreshTokenTimeout: 30d # Default: 30 days
608
- \`\`\`
507
+ Response:
609
508
 
610
- ## Examples
509
+ \`\`\`json
510
+ {
511
+ "operation_token": "<jwt-operation-token>",
512
+ "refresh_token": "<jwt-refresh-token>"
513
+ }
514
+ \`\`\`
611
515
 
612
- ### Full JWT flow via cURL
516
+ Pass the \`operation_token\` as a \`Bearer\` token on subsequent requests:
613
517
 
614
518
  \`\`\`bash
615
- # Step 1: Create tokens
616
- curl --location --request POST 'http://localhost:9925' \\
617
- --header 'Content-Type: application/json' \\
618
- --data-raw '{
619
- "operation": "create_authentication_tokens",
620
- "username": "username",
621
- "password": "password"
622
- }'
623
-
624
- # Step 2: Use operation token
625
519
  curl --location --request POST 'http://localhost:9925' \\
626
520
  --header 'Content-Type: application/json' \\
627
521
  --header 'Authorization: Bearer <operation_token>' \\
@@ -632,8 +526,13 @@ curl --location --request POST 'http://localhost:9925' \\
632
526
  "hash_values": [1],
633
527
  "get_attributes": ["*"]
634
528
  }'
529
+ \`\`\`
530
+
531
+ ### 5. Refreshing the Operation Token
635
532
 
636
- # Step 3: Refresh when operation token expires
533
+ When the \`operation_token\` expires, pass the \`refresh_token\` as \`Bearer <refresh_token>\` and call \`refresh_operation_token\`:
534
+
535
+ \`\`\`bash
637
536
  curl --location --request POST 'http://localhost:9925' \\
638
537
  --header 'Content-Type: application/json' \\
639
538
  --header 'Authorization: Bearer <refresh_token>' \\
@@ -642,14 +541,138 @@ curl --location --request POST 'http://localhost:9925' \\
642
541
  }'
643
542
  \`\`\`
644
543
 
645
- ### Session-based login/logout Resource
544
+ Response:
545
+
546
+ \`\`\`json
547
+ {
548
+ "operation_token": "<new-jwt-operation-token>"
549
+ }
550
+ \`\`\`
551
+
552
+ When both tokens have expired, call \`create_authentication_tokens\` again with username and password.
553
+
554
+ ### 6. Minting Scoped Tokens
555
+
556
+ A \`super_user\` can mint a scoped token with embedded permissions using \`create_authentication_tokens\` with an inline \`role\`. The minter must be authenticated; no \`password\` may be included in the body. Use \`add_role\`-style \`permission\` structure:
557
+
558
+ \`\`\`json
559
+ {
560
+ "operation": "create_authentication_tokens",
561
+ "username": "reporting-service",
562
+ "role": {
563
+ "permission": {
564
+ "operations": ["read_only"],
565
+ "dev": {
566
+ "tables": {
567
+ "dog": {
568
+ "read": true,
569
+ "insert": false,
570
+ "update": false,
571
+ "delete": false,
572
+ "attribute_permissions": []
573
+ }
574
+ }
575
+ }
576
+ }
577
+ },
578
+ "expires_in": "7d"
579
+ }
580
+ \`\`\`
581
+
582
+ Authenticate the mint request with Basic Authentication or an existing \`super_user\` \`operation_token\`:
583
+
584
+ \`\`\`bash
585
+ curl --location --request POST 'http://localhost:9925' \\
586
+ --header 'Content-Type: application/json' \\
587
+ --header 'Authorization: Basic <base64 of super_user:password>' \\
588
+ --data-raw '{
589
+ "operation": "create_authentication_tokens",
590
+ "username": "reporting-service",
591
+ "role": { "permission": { "operations": ["read_only"] } },
592
+ "expires_in": "7d"
593
+ }'
594
+ \`\`\`
595
+
596
+ Key constraints for scoped tokens:
597
+
598
+ - \`username\` is attribution only and must not name an existing user.
599
+ - No refresh token is issued; no user record is created.
600
+ - Scoped tokens cannot be revoked before expiry — choose \`expires_in\` carefully and prefer short lifetimes.
601
+ - \`super_user\` and \`cluster_user\` are always forced to \`false\` in the embedded role.
602
+ - In **mixed-version** clusters, only nodes with scoped-token support accept these tokens; older nodes reject them with 401.
603
+
604
+ ### 7. Issuing Tokens from a Custom Resource
605
+
606
+ Use \`server.operation()\` to mint tokens programmatically inside a Resource. Pass \`authorize: true\` as the **third argument** when the operation should run as the current authenticated user:
607
+
608
+ \`\`\`javascript
609
+ import { Resource, server } from 'harper';
610
+
611
+ export class IssueTokens extends Resource {
612
+ static async get(_target, context) {
613
+ // Issue tokens for the current authenticated user
614
+ const { operation_token, refresh_token } = await server.operation(
615
+ { operation: 'create_authentication_tokens' },
616
+ context,
617
+ true, // third argument: authorize as current user
618
+ );
619
+ return { operation_token, refresh_token };
620
+ }
621
+
622
+ static async post(_target, data) {
623
+ // Issue tokens from credentials supplied in the body
624
+ const { username, password } = await data;
625
+ if (!username || !password) {
626
+ return new Response('username and password required', { status: 400 });
627
+ }
628
+ const { operation_token, refresh_token } = await server.operation({
629
+ operation: 'create_authentication_tokens',
630
+ username,
631
+ password,
632
+ });
633
+ return { operation_token, refresh_token };
634
+ }
635
+ }
636
+
637
+ export class RefreshJWT extends Resource {
638
+ static async post(_target, data) {
639
+ const { refresh_token } = await data;
640
+ if (!refresh_token) {
641
+ return new Response('refresh_token required', { status: 400 });
642
+ }
643
+ const { operation_token } = await server.operation({
644
+ operation: 'refresh_operation_token',
645
+ refresh_token,
646
+ });
647
+ return { operation_token };
648
+ }
649
+ }
650
+ \`\`\`
651
+
652
+ Omit the third argument (or pass \`false\`) when the operation supplies its own credentials.
653
+
654
+ ### 8. Configuring Token Expiry
655
+
656
+ Set timeouts in \`harper-config.yaml\` under the \`authentication\` section:
657
+
658
+ \`\`\`yaml
659
+ authentication:
660
+ operationTokenTimeout: 1d # Default: 1 day
661
+ refreshTokenTimeout: 30d # Default: 30 days
662
+ \`\`\`
663
+
664
+ Valid duration strings follow the \`jsonwebtoken\` package format (e.g., \`1d\`, \`12h\`, \`60m\`). The \`expires_in\` field on scoped token minting accepts the same format.
665
+
666
+ ## Examples
667
+
668
+ ### Full Sign-In / Sign-Out Resource
646
669
 
647
670
  \`\`\`javascript
648
671
  export class SignIn extends Resource {
649
- async post(_target, data) {
650
- const context = this.getContext();
672
+ static async post(_target, data, context) {
673
+ const { username, password } = (await data) ?? {};
651
674
  try {
652
- await context.login(data.username, data.password);
675
+ await context.login(username, password);
653
676
  } catch {
654
677
  return new Response('Invalid credentials', { status: 403 });
655
678
  }
@@ -658,23 +681,44 @@ export class SignIn extends Resource {
658
681
  }
659
682
 
660
683
  export class SignOut extends Resource {
661
- async post() {
662
- const context = this.getContext();
663
- if (!context.session) return new Response(null, { status: 401 });
664
- await context.session.delete(context.session.id);
684
+ static async post(_target, _data, context) {
685
+ if (!context?.session?.user) return new Response(null, { status: 401 });
686
+ await context.session.update({ user: null });
665
687
  return new Response('Logged out', { status: 200 });
666
688
  }
667
689
  }
668
690
  \`\`\`
669
691
 
692
+ ### Reading the Current Authenticated User in a Static Verb
693
+
694
+ \`\`\`javascript
695
+ static async get(_target, context) {
696
+ const user = context?.user;
697
+ if (!user) return new Response(null, { status: 401 });
698
+ return { username: user.username, role: user.role };
699
+ }
700
+ \`\`\`
701
+
702
+ ### Minting Tokens via cURL
703
+
704
+ \`\`\`bash
705
+ curl --location --request POST 'http://localhost:9925' \\
706
+ --header 'Content-Type: application/json' \\
707
+ --data-raw '{
708
+ "operation": "create_authentication_tokens",
709
+ "username": "username",
710
+ "password": "password"
711
+ }'
712
+ \`\`\`
713
+
670
714
  ## Notes
671
715
 
672
- - JWT authentication is **preferred over Basic Auth** when you want to avoid sending credentials on every request, when the client can store tokens, or when making multiple sequential requests. For simple or server-to-server scenarios, use Basic Authentication.
716
+ - JWT authentication is **preferred over Basic Auth** when you want to avoid sending credentials on every request, your client can store tokens, or you have multiple sequential requests. For simple or **server-to-server** scenarios, use **Basic Authentication**.
673
717
  - Always use **HTTPS** in production to protect tokens in transit.
674
718
  - Treat tokens like passwords. If a token is compromised, it remains valid until expiry — use shorter \`operationTokenTimeout\` values in high-security environments.
675
- - \`enableSessions\` must be \`true\` in config before \`context.login\` or \`context.session\` will work.
676
- - The \`third argument\` (\`true\`) to \`server.operation\` controls whether the operation runs as the current authenticated user. Omit it when the operation body supplies its own credentials.
677
- - Scoped tokens have a 12KB limit when encoded into an \`Authorization\` header.
719
+ - \`context.login\` and \`context.session\` require \`enableSessions: true\` in \`harperdb-config.yaml\`; they are for browser clients only.
720
+ - The \`server.operation()\` third argument (\`authorize: true\`) attributes the operation to — and permission-checks against — the current authenticated user. Omit it when supplying credentials directly in the operation body.
721
+ - In **mixed-version** clusters, scoped tokens are only accepted by nodes that support them; older nodes return 401.
678
722
  `,"creating-a-fabric-account-and-cluster":`---
679
723
  name: creating-a-fabric-account-and-cluster
680
724
  description: How to create a Harper Fabric account, organization, and cluster.
@@ -767,9 +811,9 @@ metadata:
767
811
  sources:
768
812
  - reference/v5/resources/overview.md#Custom External Data Source
769
813
  - reference/v5/resources/overview.md#Exporting Resources as Endpoints
770
- - reference/v5/components/javascript-environment.md#Module Loading
771
- sourceCommit: f37a8c4021e20d5c74c1d339a6b6c8c196b5603e
772
- inputHash: df69870433c0b3e5
814
+ - reference/v5/components/javascript-environment.md#Module Formats
815
+ sourceCommit: 9e6ecf87dd25bb488ad44dc2876ca6439ccd682e
816
+ inputHash: 86858206e33925f0
773
817
  ---
774
818
 
775
819
  # Custom Resources
@@ -778,11 +822,11 @@ Instructions for the agent to follow when defining custom REST endpoints with Ja
778
822
 
779
823
  ## When to Use
780
824
 
781
- Apply this rule when creating custom HTTP endpoints, wrapping external APIs, or registering routes programmatically in a Harper application. Use it any time business logic must live outside a table-backed schema, or when a specific URL shape is required.
825
+ Apply this rule when creating custom HTTP endpoints, wrapping external APIs, or registering routes programmatically in a Harper application. Use it any time business logic must live outside a table-backed resource or when a specific URL shape is required.
782
826
 
783
827
  ## How It Works
784
828
 
785
- 1. **Import \`Resource\` from \`harper\`**: Always import from the \`harper\` package rather than relying on globals.
829
+ 1. **Import \`Resource\` from the \`harper\` package**: Always import explicitly rather than relying on globals.
786
830
 
787
831
  \`\`\`javascript
788
832
  import { tables, Resource } from 'harper';
@@ -800,7 +844,7 @@ Apply this rule when creating custom HTTP endpoints, wrapping external APIs, or
800
844
  }
801
845
  \`\`\`
802
846
 
803
- 3. **Use \`async\` static methods for external calls**: Await fetch or other async operations inside \`static\` handlers.
847
+ 3. **Use \`async\` static methods to call external services**: Return or forward the response directly.
804
848
 
805
849
  \`\`\`javascript
806
850
  export class MyExternalData extends Resource {
@@ -818,7 +862,7 @@ Apply this rule when creating custom HTTP endpoints, wrapping external APIs, or
818
862
  }
819
863
  \`\`\`
820
864
 
821
- 4. **Export the class to create an endpoint**: The export form controls the resulting URL. Choose the form that matches the URL shape you need.
865
+ 4. **Export the class to expose it as an endpoint**: The export form controls the resulting URL. Choose the form that matches the URL shape you need.
822
866
 
823
867
  | Export form | URL | Notes |
824
868
  | ------------------------------------------- | --------------- | --------------------------------------------------------------- |
@@ -829,12 +873,17 @@ Apply this rule when creating custom HTTP endpoints, wrapping external APIs, or
829
873
  | \`static path = '/widget/:id'\` (class field) | \`/widget/:id\` | Declare path on the class; overrides the export name. |
830
874
  | \`server.resources.set('my-path', Foo);\` | \`/my-path/\` | Programmatic registration for dynamic paths. |
831
875
 
832
- URL path matching is case-sensitive — \`/Foo/\` and \`/foo/\` are different endpoints.
876
+ 5. **Register programmatically when the path is dynamic**: Use \`server.resources.set(\` with a path string and the resource class.
877
+
878
+ \`\`\`javascript
879
+ server.resources.set('my-path', Foo);
880
+ \`\`\`
833
881
 
834
- 5. **Declare path parameters with \`static path\`**: Use \`:name\` for a single segment and \`*name\` as a catch-all. Matched values are bound onto \`target.<name>\`.
882
+ 6. **Declare dynamic path segments with \`static path\`**: Use \`:name\` for a single segment and \`*name\` as a catch-all. Matched values are bound onto \`target.<name>\`.
835
883
 
836
884
  \`\`\`javascript
837
885
  export class Widget extends Resource {
886
+ // GET /widget/10/action/jump -> target.id === '10', target.action === 'jump'
838
887
  static path = '/widget/:id/action/:action';
839
888
  static get(target) {
840
889
  return { id: target.id, action: target.action };
@@ -842,22 +891,11 @@ Apply this rule when creating custom HTTP endpoints, wrapping external APIs, or
842
891
  }
843
892
  \`\`\`
844
893
 
845
- A \`static path\` takes precedence over the export name. A leading \`/\` makes the path root-relative (top-level). A leading \`./\` or bare name resolves relative to the component directory.
846
-
847
- 6. **Register programmatically when the path is dynamic**: Use \`server.resources.set(\` when the path cannot be known at export time.
848
-
849
- \`\`\`javascript
850
- server.resources.set('my-path', Foo);
851
- \`\`\`
852
-
853
- 7. **Optionally source a table from a custom resource**: Use the resource as a caching layer for a local table.
854
- \`\`\`javascript
855
- tables.MyCache.sourcedFrom(MyExternalData);
856
- \`\`\`
894
+ 7. **Resolve path precedence correctly**: Exact and static paths always win over parameterized ones. Among parameterized routes, more specific paths win: a literal segment beats a \`:param\`, which beats a \`*\` wildcard, compared left to right.
857
895
 
858
896
  ## Examples
859
897
 
860
- ### External API wrapper with GET and PUT
898
+ **Wrapping an external API and using it as a cache source:**
861
899
 
862
900
  \`\`\`javascript
863
901
  import { tables, Resource } from 'harper';
@@ -880,19 +918,9 @@ export class MyExternalData extends Resource {
880
918
  tables.MyCache.sourcedFrom(MyExternalData);
881
919
  \`\`\`
882
920
 
883
- ### Path parameters with \`static path\`
921
+ **Catch-all wildcard path:**
884
922
 
885
923
  \`\`\`javascript
886
- import { Resource } from 'harper';
887
-
888
- export class Widget extends Resource {
889
- // GET /widget/10/action/jump -> target.id === '10', target.action === 'jump'
890
- static path = '/widget/:id/action/:action';
891
- static get(target) {
892
- return { id: target.id, action: target.action };
893
- }
894
- }
895
-
896
924
  export class Files extends Resource {
897
925
  // GET /files/a/b/c.txt -> target.rest === 'a/b/c.txt'
898
926
  static path = '/files/*rest';
@@ -902,28 +930,27 @@ export class Files extends Resource {
902
930
  }
903
931
  \`\`\`
904
932
 
905
- ### Programmatic registration
933
+ **Root-relative fixed route:**
906
934
 
907
935
  \`\`\`javascript
908
- import { Resource } from 'harper';
909
-
910
- export class Foo extends Resource {
936
+ export class AcmeChallenge extends Resource {
937
+ static path = '/.well-known/acme-challenge/:token';
911
938
  static get(target) {
912
- return { data: doSomething() };
939
+ return { token: target.token };
913
940
  }
914
941
  }
915
-
916
- server.resources.set('my-path', Foo);
917
942
  \`\`\`
918
943
 
919
944
  ## Notes
920
945
 
921
- - A bare \`*\` wildcard (no name) binds under \`target.wildcard\`. A wildcard must be the final segment of the path.
922
- - Resolution order: exact/static paths always win over parameterized ones. Among parameterized routes, more specific paths win — a literal segment beats \`:param\`, which beats \`*\`, compared left to right.
923
- - Parameterized routes appear in the generated OpenAPI document as templated paths (e.g. \`/widget/{id}/action/{action}\`) and in MCP \`resources/templates/list\` as \`{param}\` URI templates.
924
- - If a resource \`extends\` an existing table, avoid conflicting exports between the schema and the JavaScript implementation.
946
+ - URL path matching is case-sensitive — \`/Foo/\` and \`/foo/\` are different endpoints.
947
+ - A leading \`/\` in \`static path\` makes the path root-relative (top-level), independent of the file's location.
948
+ - A leading \`./\` or a bare name in \`static path\` resolves relative to the component directory.
949
+ - A bare \`*\` (no name) binds under \`target.wildcard\`. A wildcard must be the final segment of the path.
950
+ - \`static path\` takes precedence over the export name when both are present.
951
+ - Parameterized routes appear in the generated OpenAPI document as templated paths (e.g. \`/widget/{id}/action/{action}\`) and in MCP \`resources/templates/list\` as URI templates.
952
+ - When a resource \`extends\` an existing table, avoid conflicting exports between the schema and the JavaScript implementation.
925
953
  - Link the \`harper\` package in your component directory to ensure correct typings: \`npm link harper\`. All installed components have \`harper\` automatically linked.
926
- - Harper runs as a single process — \`tables\`, \`databases\`, and other APIs are the same live, process-wide objects regardless of which component accesses them.
927
954
  `,"defining-relationships":`---
928
955
  name: defining-relationships
929
956
  description: How to define and use relationships between tables in Harper using GraphQL.
@@ -1895,7 +1922,7 @@ Tagged entries appear in \`hdb.log\` with the tag in the header:
1895
1922
  - \`console.log\` output is only forwarded to \`hdb.log\` when \`logging.console: true\` is explicitly set; it is not forwarded by default.
1896
1923
  - When logging to standard streams, run Harper in the foreground (\`harper\`, not \`harper start\`).
1897
1924
  - \`TaggedLogger\` is bound to the configured log level at creation time — always use \`?.\` on its methods.
1898
- `,"programmatic-table-requests":"---\nname: programmatic-table-requests\ndescription: How to interact with Harper tables programmatically using the `tables` object.\nmetadata:\n mode: generate\n sources:\n - reference/v5/database/api.md#`tables`\n - reference/v5/resources/resource-api.md#Query Object\n - 'reference/v5/database/api.md#`transaction(context?, callback)`'\n - >-\n reference/v5/resources/resource-api.md#`update(target: RequestTarget | Id,\n updates?: object): Promise<Resource>`\n - >-\n reference/v5/resources/resource-api.md#`addTo(property: string, value:\n number)`\n - reference/v5/components/javascript-environment.md#Module Loading\n sourceCommit: 677ad213d67822e109c83619e181ca23a59823db\n inputHash: ce2181ecade6522f\n---\n\n# Programmatic Table Requests\n\nInstructions for the agent to interact with Harper tables programmatically using the `tables` object, including querying, transactions, and module integration.\n\n## When to Use\n\nApply this rule when writing server-side Harper component code that reads from or writes to tables directly — bypassing REST endpoints — such as in request handlers, background jobs, timers, or SSR rendering. Use it whenever you need to construct queries with `conditions`, manage transactions explicitly, or perform CRDT-safe mutations.\n\n## How It Works\n\n1. **Import `tables` from `harper`**: Access all tables in the default `data` database via the `tables` object. Each table defined with `@table` in `schema.graphql` is a property.\n\n ```javascript\n import { tables } from 'harper';\n const { Product } = tables;\n // same as: databases.data.Product\n ```\n\n2. **Define your schema with `@table`**: Tables must be declared in `schema.graphql`. Use `@indexed` on attributes you intend to sort or filter efficiently.\n\n ```graphql\n type Product @table {\n id: Long @primaryKey\n name: String\n price: Float\n }\n ```\n\n3. **Use `search(` to query records**: Pass a Query object to `search(`. Iterate results with `for await`.\n\n ```javascript\n const query = {\n conditions: [{ attribute: 'price', comparator: 'less_than', value: 8.0 }],\n };\n for await (const record of Product.search(query)) {\n // process record\n }\n ```\n\n4. **Build `conditions` arrays to filter**: Each condition object supports these properties:\n\n | Property | Description |\n | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- |\n | `attribute` | Property name, or array for chained/joined properties (e.g. `['brand', 'name']`) |\n | `value` | The value to match |\n | `comparator` | `equals` (default), `greater_than`, `greater_than_equal`, `less_than`, `less_than_equal`, `starts_with`, `contains`, `ends_with`, `between`, `not_equal` |\n | `conditions` | Nested conditions array |\n | `operator` | `and` (default) or `or` for the nested `conditions` |\n\n5. **Apply `select` to shape results**: Return only the fields you need. Supports arrays, nested relationship selects, and special properties.\n\n ```javascript\n // Array of fields\n Product.search({ select: ['name', 'price'] });\n\n // Nested relationship select\n Book.get({ id: 42, select: ['id', 'title', { name: 'author', select: ['name'] }] });\n ```\n\n Special `select` values: `$id`, `$updatedtime`, `$distance`.\n\n6. **Apply `sort` with an `@indexed` attribute**: Harper uses an index to provide sort order. Sort by an `@indexed` attribute without requiring a condition, or provide at least one condition when sorting by a non-indexed attribute.\n\n ```javascript\n // Sort by primary key with an open-ended condition to avoid scan error\n Product.search({\n conditions: [{ attribute: 'id', comparator: 'greater_than', value: '' }],\n sort: { attribute: 'id' },\n });\n ```\n\n Sort object properties:\n\n | Property | Description |\n | ------------ | -------------------------------------------------------- |\n | `attribute` | Property name or array for chained relationship property |\n | `descending` | Sort descending if `true` (default: `false`) |\n | `next` | Secondary sort to resolve ties (same structure) |\n\n7. **Use `limit` and `offset` for pagination**:\n\n ```javascript\n Product.search({ conditions: [...], limit: 20, offset: 40 });\n ```\n\n8. **Use `explain` and `enforceExecutionOrder` for debugging**:\n - `explain: true` — returns conditions reordered as Harper will execute them.\n - `enforceExecutionOrder: true` — forces conditions to execute in the order supplied, disabling automatic re-ordering.\n\n9. **Use `addTo` for concurrent-safe numeric updates**: `addTo` uses CRDT incrementation, safe across threads and nodes.\n\n ```javascript\n static async post(target, data) {\n const record = await this.update(target.id);\n record.addTo('quantity', -1); // decrement safely across nodes\n }\n ```\n\n10. **Wrap background work in `transaction()`**: HTTP handlers get a transaction automatically. Use `transaction()` explicitly for timers, background jobs, or any code outside a natural transaction context.\n\n ```javascript\n import { tables } from 'harper';\n const { MyTable } = tables;\n\n if (isMainThread) {\n setInterval(async () => {\n let data = await (await fetch('https://example.com/data')).json();\n transaction(async (txn) => {\n for (let item of data) {\n await MyTable.put(item, txn);\n }\n });\n }, 3600000); // every hour\n }\n ```\n\n The `txn` object members:\n\n | Member | Type | Description |\n | --------------------- | --------------- | ------------------------------------------------------ |\n | `commit()` | `() => Promise` | Commits the current transaction |\n | `abort()` | `() => void` | Aborts the transaction and resets it |\n | `resetReadSnapshot()` | `() => void` | Resets the read snapshot to the latest committed state |\n | `timestamp` | `number` | Timestamp associated with the current transaction |\n\n11. **Understand atomicity boundaries**: All tables within the same database share one transactional context — writes across multiple tables commit atomically. Tables in different databases each get their own transaction with no cross-database atomicity guarantee.\n\n12. **Keep `harper` external in bundlers**: When using SSR bundlers, mark `harper` as external so it resolves to the live runtime. In `vite.config`:\n\n ```javascript\n ssr: {\n external: ['harper'];\n }\n ```\n\n## Examples\n\n### Nested conditions query\n\n```javascript\nProduct.search({\n conditions: [\n { attribute: 'price', comparator: 'less_than', value: 100 },\n {\n operator: 'or',\n conditions: [\n { attribute: 'rating', comparator: 'greater_than', value: 4 },\n { attribute: 'featured', value: true },\n ],\n },\n ],\n});\n```\n\n### Chained attribute reference (join/relationship)\n\n```javascript\nProduct.search({ conditions: [{ attribute: ['brand', 'name'], value: 'Harper' }] });\n```\n\n### Full CRUD sequence\n\n```javascript\n// Create a new record (id auto-generated)\nconst created = await Product.create({ name: 'Shirt', price: 9.5 });\n\n// Modify the record\nawait Product.patch(created.id, { price: Math.round(created.price * 0.8 * 100) / 100 });\n\n// Retrieve by primary key\nconst record = await Product.get(created.id);\n\n// Query with conditions\nconst query = {\n conditions: [{ attribute: 'price', comparator: 'less_than', value: 8.0 }],\n};\nfor await (const record of Product.search(query)) {\n // process record\n}\n```\n\n### SSR rendering with `tables`\n\n```typescript\nimport { tables } from 'harper';\n\nexport async function render(url: string): Promise<string> {\n const product = await tables.Product.get(idFromUrl(url));\n return renderToString(/* <App product={product} /> */);\n}\n```\n\n### Mutable update with `addTo`\n\n```javascript\nconst product = await Product.update(32);\nproduct.status = 'active';\nproduct.subtractFrom('quantity', 1);\nproduct.save();\n```\n\n## Notes\n\n- `tables` calls run in a trusted server-side context and do **not** automatically apply the target table's role permissions. Enforce authorization in your own application logic.\n- Destructive operations (`update`, `patch`, `delete`) act on live data and are not easily reversible. Always scope with specific `conditions`, validate the affected set before writing, and gate behind authorization controls.\n- Sorting by the bare `@primaryKey` alone with no conditions triggers `HdbError: <attribute> is not indexed and not combined with any other conditions`. Add an open-ended range condition or pass `allowFullScan: true` to permit an unconditional scan.\n- Selecting a relationship field without filtering on it behaves as a **LEFT JOIN**; adding a condition on a related attribute behaves as an **INNER JOIN**.\n- `transaction()` is safe to call defensively — if a transaction is already active on the context, it reuses it and executes the callback immediately.\n- Link the `harper` package for correct typings in standalone component directories: `npm link harper`.\n","querying-rest-apis":'---\nname: querying-rest-apis\ndescription: \'How to use query parameters to filter, sort, and paginate Harper REST APIs.\'\nmetadata:\n mode: generate\n sources:\n - reference/v5/rest/querying.md\n sourceCommit: 677ad213d67822e109c83619e181ca23a59823db\n inputHash: 0f8efee293628a52\n---\n\n# Querying REST APIs\n\nInstructions for the agent to filter, sort, select, and paginate Harper REST API collections using URL query parameters.\n\n## When to Use\n\nApply this rule whenever building or modifying code that queries Harper REST collection endpoints. Use it when you need to filter records by attribute values, apply comparison operators, sort or paginate results, or join across related tables. See [automatic-apis.md](automatic-apis.md) for how Harper exposes tables as REST endpoints.\n\n## How It Works\n\n1. **Filter by attribute**: Add query parameters matching attribute names and values. The queried attribute must be indexed.\n\n ```\n GET /Product/?category=software\n GET /Product/?category=software&inStock=true\n ```\n\n2. **Apply comparison operators (FIQL syntax)**: Use FIQL operators in the query string for numeric, string, and date comparisons.\n\n | Operator | Meaning |\n | -------------------- | -------------------------------------- |\n | `==` | Equal |\n | `=lt=` | Less than |\n | `=le=` | Less than or equal |\n | `=gt=` | Greater than |\n | `=ge=` | Greater than or equal |\n | `=ne=`, `!=` | Not equal |\n | `=ct=` | Contains (strings) |\n | `=sw=`, `==<value>*` | Starts with (strings) |\n | `=ew=` | Ends with (strings) |\n | `=`, `===` | Strict equality (no type conversion) |\n | `!==` | Strict inequality (no type conversion) |\n\n ```\n GET /Product/?price=gt=100\n GET /Product/?price=le=20\n GET /Product/?name==Keyboard*\n GET /Product/?category=software&price=gt=100&price=lt=200\n ```\n\n For date fields, URL-encode colons as `%3A`:\n\n ```\n GET /Product/?listDate=gt=2017-03-08T09%3A30%3A00.000Z\n ```\n\n3. **Chain conditions for range queries**: Omit the attribute name on the second condition to apply it to the same attribute. Only `gt`/`ge` combined with `lt`/`le` is supported.\n\n ```\n GET /Product/?price=gt=100&lt=200\n ```\n\n4. **Apply type conversion**: For FIQL comparators, Harper converts values automatically. Use explicit prefixes to force a type.\n\n | Syntax | Behavior |\n | ----------------------------------------- | ------------------------------------------- |\n | `name==null` | Converts to `null` |\n | `name==123` | Converts to number if attribute is untyped |\n | `name==true` | Converts to boolean if attribute is untyped |\n | `name==number:123` | Explicit number conversion |\n | `name==boolean:true` | Explicit boolean conversion |\n | `name==string:some%20text` | Keep as string with URL decode |\n | `name==date:2024-01-05T20%3A07%3A27.955Z` | Explicit Date conversion |\n\n For strict operators (`=`, `===`, `!==`), no automatic type conversion is applied.\n\n5. **Combine conditions with OR logic**: Use `|` instead of `&`.\n\n ```\n GET /Product/?rating=5|featured=true\n ```\n\n6. **Group conditions**: Use parentheses or square brackets to control order of operations. Prefer square brackets when constructing queries from user input, since standard URI encoding safely encodes `[` and `]`.\n\n ```\n GET /Product/?rating=5|(price=gt=100&price=lt=200)\n GET /Product/?rating=5&[tag=fast|tag=scalable|tag=efficient]\n ```\n\n Construct from JavaScript:\n\n ```javascript\n let url = `/Product/?rating=5&[${tags.map(encodeURIComponent).join(\'|\')}]`;\n ```\n\n7. **Select specific properties with `select(`**: Append `select(...)` as a query function separated by `&`.\n\n | Syntax | Returns |\n | -------------------------------------- | ------------------------------------------- |\n | `?select(property)` | Values of a single property directly |\n | `?select(property1,property2)` | Objects with only the specified properties |\n | `?select([property1,property2])` | Arrays of property values |\n | `?select(property1,)` | Objects with a single specified property |\n | `?select(property{subProp1,subProp2})` | Nested objects with specific sub-properties |\n\n8. **Paginate with `limit(`**: Use `limit(end)` or `limit(start,end)` to control result count and offset.\n\n9. **Sort with `sort(`**: Use `sort(property)` or `sort(+property,-property,...)`. Prefix `+` or no prefix = ascending; `-` = descending.\n\n10. **Query across relationships**: Use dot-syntax to filter by related table attributes. Relationships must be defined in the schema using `@relationship`. Relationship attributes are not included by default — use `select()` to include them.\n\n ```\n GET /Product/?brand.name=Microsoft&select(name,brand{name})\n ```\n\n11. **Query for null values**: Use `=null` as the value to match null or non-null records.\n ```\n GET /Product/?discount=null\n ```\n\n## Examples\n\n**Filter with comparison operators and select:**\n\n```\nGET /Product/?category=software&price=gt=100&price=lt=200&select(name,price)\n```\n\n**Paginate and sort:**\n\n```\nGET /Product/?rating=gt=3&inStock=true&select(rating,name)&limit(20)\nGET /Product/?rating=gt=3&limit(10,30)\nGET /Product/?rating=gt=3&sort(+name)\nGET /Product/?sort(+rating,-price)\n```\n\n**OR logic with grouping:**\n\n```\nGET /Product/?price=lt=100|[rating=5&[tag=fast|tag=scalable|tag=efficient]&inStock=true]\n```\n\n**Relationship join with nested select:**\n\nDefine the schema:\n\n```graphql\ntype Product @table @export {\n id: Long @primaryKey\n name: String\n brandId: Long @indexed\n brand: Brand @relationship(from: "brandId")\n}\ntype Brand @table @export {\n id: Long @primaryKey\n name: String\n products: [Product] @relationship(to: "brandId")\n}\n```\n\nQuery with join:\n\n```\nGET /Product/?brand.name=Microsoft&select(name,brand{name,id})\nGET /Brand/?products.name=Keyboard\n```\n\n**Many-to-many relationship:**\n\n```graphql\ntype Product @table @export {\n id: Long @primaryKey\n name: String\n resellerIds: [Long] @indexed\n resellers: [Reseller] @relationship(from: "resellerIds")\n}\n```\n\n```\nGET /Product/?resellers.name=Cool Shop&select(id,name,resellers{name,id})\n```\n\n**Access a specific property by record ID:**\n\n```\nGET /MyTable/123.propertyName\n```\n\n## Notes\n\n- Only indexed attributes can be used as the primary filter attribute; when combining multiple attributes, only one needs to be indexed.\n- Relationship attributes are excluded from responses by default. Always use `select(` to include them.\n- When selecting a related attribute without filtering on it, the behavior is a LEFT JOIN — the property is omitted if the foreign key is null or references a non-existent record.\n- The suffixes `.json`, `.cbor`, `.msgpack`, and `.csv` in URL paths are reserved as content-type selectors and take precedence over a property of the same name.\n- Square brackets are preferred over parentheses when building grouped queries programmatically, because `[` and `]` are safely URL-encoded by standard encoding functions while `(` is not.\n',"real-time-apps":`---
1925
+ `,"programmatic-table-requests":"---\nname: programmatic-table-requests\ndescription: How to interact with Harper tables programmatically using the `tables` object.\nmetadata:\n mode: generate\n sources:\n - reference/v5/database/api.md#`tables`\n - reference/v5/resources/resource-api.md#Query Object\n - 'reference/v5/database/api.md#`transaction(context?, callback)`'\n - >-\n reference/v5/resources/resource-api.md#`update(target: RequestTarget | Id,\n updates?: object): Promise<Resource>`\n - >-\n reference/v5/resources/resource-api.md#`addTo(property: string, value:\n number)`\n - reference/v5/components/javascript-environment.md#Module Formats\n sourceCommit: 9e6ecf87dd25bb488ad44dc2876ca6439ccd682e\n inputHash: f5629f73cde74764\n---\n\n# Programmatic Table Requests\n\nInstructions for the agent to interact with Harper tables programmatically using the `tables` object, the Query API, and transactions.\n\n## When to Use\n\nApply this rule when writing server-side Harper component code that reads from or writes to tables directly — for example, in HTTP handlers, background jobs, timers, or SSR render functions. Use it whenever you need to construct queries with `conditions`, `sort`, `select`, `limit`, or `offset`, or when you need explicit transaction control via `transaction()`.\n\n## How It Works\n\n1. **Import `tables` (and other APIs) from `harper`**: Access every table defined in `schema.graphql` as a named property of `tables`. Each property is the table class implementing the Resource API.\n\n ```javascript\n import { tables, transaction } from 'harper';\n const { Product } = tables;\n // equivalent to: databases.data.Product\n ```\n\n For standalone components, run `npm link harper` so imports resolve to the live runtime.\n\n2. **Define your schema with `@table`**: Tables must be declared in `schema.graphql`. Mark attributes you intend to sort or filter on with `@indexed`.\n\n ```graphql\n type Product @table {\n id: Long @primaryKey\n name: String\n price: Float\n }\n ```\n\n3. **Query records with `search(`**: Pass a Query object to `search(`. Iterate results with `for await`.\n\n ```javascript\n const query = {\n conditions: [{ attribute: 'price', comparator: 'less_than', value: 8.0 }],\n };\n for await (const record of Product.search(query)) {\n // process record\n }\n ```\n\n4. **Build `conditions`**: Each condition object supports these properties:\n\n | Property | Description |\n | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- |\n | `attribute` | Property name, or array for chained/joined properties (e.g. `['brand', 'name']`) |\n | `value` | The value to match |\n | `comparator` | `equals` (default), `greater_than`, `greater_than_equal`, `less_than`, `less_than_equal`, `starts_with`, `contains`, `ends_with`, `between`, `not_equal` |\n | `conditions` | Nested conditions array |\n | `operator` | `and` (default) or `or` for the nested `conditions` |\n\n5. **Control result shape with `select`**: Pass an array of property names, a single string, or nested objects for relationships.\n\n ```javascript\n // Scalar fields only\n Product.search({ select: ['name', 'price'] });\n\n // Partial related record\n Book.get({ id: 42, select: ['id', 'title', { name: 'author', select: ['name'] }] });\n ```\n\n Special `select` values: `$id`, `$updatedtime`, `$distance`.\n\n6. **Paginate with `limit` and `offset`**:\n\n ```javascript\n Product.search({ conditions: [...], limit: 20, offset: 40 });\n ```\n\n7. **Sort with `sort`**: The `sort` object accepts `attribute`, `descending` (default `false`), and `next` for tie-breaking. Harper uses an index for sort order — the sort `attribute` must be `@indexed`, **or** at least one entry in `conditions` must be present.\n\n Sorting by a non-indexed attribute with zero conditions raises:\n\n > `HdbError: <attribute> is not indexed and not combined with any other conditions`\n\n Note: `@primaryKey` alone is treated as not indexed for sort purposes. To scan the whole table in primary-key order, add an open-ended condition:\n\n ```javascript\n Product.search({\n conditions: [{ attribute: 'id', comparator: 'greater_than', value: '' }],\n sort: { attribute: 'id' },\n });\n ```\n\n Alternatively, pass `allowFullScan: true` to permit an unconditional ordered scan, or omit `sort` entirely to iterate without an index requirement.\n\n8. **Debug query planning with `explain` and `enforceExecutionOrder`**:\n - `explain: true` — returns conditions reordered as Harper will execute them.\n - `enforceExecutionOrder: true` — forces conditions to execute in the order supplied, disabling automatic re-ordering.\n\n9. **Use `addTo` for concurrent-safe numeric updates**: `addTo` uses CRDT incrementation, safe across threads and nodes.\n\n ```javascript\n const record = await Product.update(32);\n record.addTo('quantity', -1);\n ```\n\n10. **Wrap background work in `transaction()`**: HTTP handlers get a transaction automatically. Use `transaction()` explicitly for timers, background jobs, or any code outside a request context. Always `await` the call and `catch` errors.\n\n ```javascript\n await transaction(async (txn) => {\n for (let item of data) {\n await MyTable.put(item, txn);\n }\n });\n ```\n\n The `txn` object exposes:\n\n | Member | Description |\n | --------------------- | ------------------------------------------------------ |\n | `commit()` | Commits the current transaction |\n | `abort()` | Aborts and resets the transaction |\n | `resetReadSnapshot()` | Resets the read snapshot to the latest committed state |\n | `timestamp` | Timestamp associated with the current transaction |\n\n **Atomicity**: all tables in the same database share one transactional context — writes across multiple tables commit atomically. Tables in different databases each get their own transaction with no cross-database atomicity guarantee.\n\n If `transaction()` is called with a context that already has an active transaction, it reuses that transaction — safe to call defensively.\n\n11. **Keep `harper` external when bundling for SSR**: In `vite.config`, mark `harper` as external so it resolves to the runtime rather than being bundled.\n\n ```javascript\n // vite.config\n ssr: {\n external: ['harper'];\n }\n ```\n\n## Examples\n\n### Full CRUD sequence\n\n```javascript\nimport { tables } from 'harper';\nconst { Product } = tables;\n\n// Create\nconst created = await Product.create({ name: 'Shirt', price: 9.5 });\n\n// Patch\nawait Product.patch(created.id, { price: Math.round(created.price * 0.8 * 100) / 100 });\n\n// Retrieve by primary key\nconst record = await Product.get(created.id);\n\n// Query with conditions\nconst query = {\n conditions: [{ attribute: 'price', comparator: 'less_than', value: 8.0 }],\n};\nfor await (const record of Product.search(query)) {\n // process record\n}\n```\n\n### Nested conditions with `or`\n\n```javascript\nProduct.search({\n conditions: [\n { attribute: 'price', comparator: 'less_than', value: 100 },\n {\n operator: 'or',\n conditions: [\n { attribute: 'rating', comparator: 'greater_than', value: 4 },\n { attribute: 'featured', value: true },\n ],\n },\n ],\n});\n```\n\n### Chained attribute reference (join/relationship)\n\n```javascript\nProduct.search({ conditions: [{ attribute: ['brand', 'name'], value: 'Harper' }] });\n```\n\n### Background job with `transaction()`\n\n```javascript\nimport { isMainThread } from 'node:worker_threads';\nimport { tables, transaction } from 'harper';\nconst { MyTable } = tables;\n\nif (isMainThread) {\n let running = false;\n setInterval(async () => {\n if (running) return;\n running = true;\n try {\n let data = await (await fetch('https://example.com/data')).json();\n await transaction(async (txn) => {\n for (let item of data) {\n await MyTable.put(item, txn);\n }\n });\n } catch (error) {\n logger.error('hourly import failed', error);\n } finally {\n running = false;\n }\n }, 3600000);\n}\n```\n\n### SSR render with `tables`\n\n```typescript\nimport { tables } from 'harper';\n\nexport async function render(url: string): Promise<string> {\n const product = await tables.Product.get(idFromUrl(url));\n return renderToString(/* <App product={product} /> */);\n}\n```\n\n## Notes\n\n- `tables` and `databases` do **not** automatically apply role permissions — calls run in a trusted server-side context. Apply your own authorization controls before exposing results.\n- Destructive operations (`update`, `patch`, `delete`) act on live data and are not easily reversible. Scope them with specific `conditions` and validate the affected set before writing.\n- `tables` is the same live, process-wide object whether accessed as a global or via `import { tables } from 'harper'`. A record written through one component is immediately visible to every other.\n- Run `npm link harper` for components in their own directory to ensure typings match the running installation.\n","querying-rest-apis":'---\nname: querying-rest-apis\ndescription: \'How to use query parameters to filter, sort, and paginate Harper REST APIs.\'\nmetadata:\n mode: generate\n sources:\n - reference/v5/rest/querying.md\n sourceCommit: 677ad213d67822e109c83619e181ca23a59823db\n inputHash: 0f8efee293628a52\n---\n\n# Querying REST APIs\n\nInstructions for the agent to filter, sort, select, and paginate Harper REST API collections using URL query parameters.\n\n## When to Use\n\nApply this rule whenever building or modifying code that queries Harper REST collection endpoints. Use it when you need to filter records by attribute values, apply comparison operators, sort or paginate results, or join across related tables. See [automatic-apis.md](automatic-apis.md) for how Harper exposes tables as REST endpoints.\n\n## How It Works\n\n1. **Filter by attribute**: Add query parameters matching attribute names and values. The queried attribute must be indexed.\n\n ```\n GET /Product/?category=software\n GET /Product/?category=software&inStock=true\n ```\n\n2. **Apply comparison operators (FIQL syntax)**: Use FIQL operators in the query string for numeric, string, and date comparisons.\n\n | Operator | Meaning |\n | -------------------- | -------------------------------------- |\n | `==` | Equal |\n | `=lt=` | Less than |\n | `=le=` | Less than or equal |\n | `=gt=` | Greater than |\n | `=ge=` | Greater than or equal |\n | `=ne=`, `!=` | Not equal |\n | `=ct=` | Contains (strings) |\n | `=sw=`, `==<value>*` | Starts with (strings) |\n | `=ew=` | Ends with (strings) |\n | `=`, `===` | Strict equality (no type conversion) |\n | `!==` | Strict inequality (no type conversion) |\n\n ```\n GET /Product/?price=gt=100\n GET /Product/?price=le=20\n GET /Product/?name==Keyboard*\n GET /Product/?category=software&price=gt=100&price=lt=200\n ```\n\n For date fields, URL-encode colons as `%3A`:\n\n ```\n GET /Product/?listDate=gt=2017-03-08T09%3A30%3A00.000Z\n ```\n\n3. **Chain conditions for range queries**: Omit the attribute name on the second condition to apply it to the same attribute. Only `gt`/`ge` combined with `lt`/`le` is supported.\n\n ```\n GET /Product/?price=gt=100&lt=200\n ```\n\n4. **Apply type conversion**: For FIQL comparators, Harper converts values automatically. Use explicit prefixes to force a type.\n\n | Syntax | Behavior |\n | ----------------------------------------- | ------------------------------------------- |\n | `name==null` | Converts to `null` |\n | `name==123` | Converts to number if attribute is untyped |\n | `name==true` | Converts to boolean if attribute is untyped |\n | `name==number:123` | Explicit number conversion |\n | `name==boolean:true` | Explicit boolean conversion |\n | `name==string:some%20text` | Keep as string with URL decode |\n | `name==date:2024-01-05T20%3A07%3A27.955Z` | Explicit Date conversion |\n\n For strict operators (`=`, `===`, `!==`), no automatic type conversion is applied.\n\n5. **Combine conditions with OR logic**: Use `|` instead of `&`.\n\n ```\n GET /Product/?rating=5|featured=true\n ```\n\n6. **Group conditions**: Use parentheses or square brackets to control order of operations. Prefer square brackets when constructing queries from user input, since standard URI encoding safely encodes `[` and `]`.\n\n ```\n GET /Product/?rating=5|(price=gt=100&price=lt=200)\n GET /Product/?rating=5&[tag=fast|tag=scalable|tag=efficient]\n ```\n\n Construct from JavaScript:\n\n ```javascript\n let url = `/Product/?rating=5&[${tags.map(encodeURIComponent).join(\'|\')}]`;\n ```\n\n7. **Select specific properties with `select(`**: Append `select(...)` as a query function separated by `&`.\n\n | Syntax | Returns |\n | -------------------------------------- | ------------------------------------------- |\n | `?select(property)` | Values of a single property directly |\n | `?select(property1,property2)` | Objects with only the specified properties |\n | `?select([property1,property2])` | Arrays of property values |\n | `?select(property1,)` | Objects with a single specified property |\n | `?select(property{subProp1,subProp2})` | Nested objects with specific sub-properties |\n\n8. **Paginate with `limit(`**: Use `limit(end)` or `limit(start,end)` to control result count and offset.\n\n9. **Sort with `sort(`**: Use `sort(property)` or `sort(+property,-property,...)`. Prefix `+` or no prefix = ascending; `-` = descending.\n\n10. **Query across relationships**: Use dot-syntax to filter by related table attributes. Relationships must be defined in the schema using `@relationship`. Relationship attributes are not included by default — use `select()` to include them.\n\n ```\n GET /Product/?brand.name=Microsoft&select(name,brand{name})\n ```\n\n11. **Query for null values**: Use `=null` as the value to match null or non-null records.\n ```\n GET /Product/?discount=null\n ```\n\n## Examples\n\n**Filter with comparison operators and select:**\n\n```\nGET /Product/?category=software&price=gt=100&price=lt=200&select(name,price)\n```\n\n**Paginate and sort:**\n\n```\nGET /Product/?rating=gt=3&inStock=true&select(rating,name)&limit(20)\nGET /Product/?rating=gt=3&limit(10,30)\nGET /Product/?rating=gt=3&sort(+name)\nGET /Product/?sort(+rating,-price)\n```\n\n**OR logic with grouping:**\n\n```\nGET /Product/?price=lt=100|[rating=5&[tag=fast|tag=scalable|tag=efficient]&inStock=true]\n```\n\n**Relationship join with nested select:**\n\nDefine the schema:\n\n```graphql\ntype Product @table @export {\n id: Long @primaryKey\n name: String\n brandId: Long @indexed\n brand: Brand @relationship(from: "brandId")\n}\ntype Brand @table @export {\n id: Long @primaryKey\n name: String\n products: [Product] @relationship(to: "brandId")\n}\n```\n\nQuery with join:\n\n```\nGET /Product/?brand.name=Microsoft&select(name,brand{name,id})\nGET /Brand/?products.name=Keyboard\n```\n\n**Many-to-many relationship:**\n\n```graphql\ntype Product @table @export {\n id: Long @primaryKey\n name: String\n resellerIds: [Long] @indexed\n resellers: [Reseller] @relationship(from: "resellerIds")\n}\n```\n\n```\nGET /Product/?resellers.name=Cool Shop&select(id,name,resellers{name,id})\n```\n\n**Access a specific property by record ID:**\n\n```\nGET /MyTable/123.propertyName\n```\n\n## Notes\n\n- Only indexed attributes can be used as the primary filter attribute; when combining multiple attributes, only one needs to be indexed.\n- Relationship attributes are excluded from responses by default. Always use `select(` to include them.\n- When selecting a related attribute without filtering on it, the behavior is a LEFT JOIN — the property is omitted if the foreign key is null or references a non-existent record.\n- The suffixes `.json`, `.cbor`, `.msgpack`, and `.csv` in URL paths are reserved as content-type selectors and take precedence over a property of the same name.\n- Square brackets are preferred over parentheses when building grouped queries programmatically, because `[` and `]` are safely URL-encoded by standard encoding functions while `(` is not.\n',"real-time-apps":`---
1899
1926
  name: real-time-apps
1900
1927
  description: How to build real-time features in Harper using WebSockets and Pub/Sub.
1901
1928
  metadata:
@@ -2262,6 +2289,6 @@ let results = Document.search(
2262
2289
  - The correct parameter name is \`efConstruction\` (seeds the construction budget) and \`efConstructionSearch\` (controls search budget). The name \`efSearchConstruction\` is a previous documentation error.
2263
2290
  - When no \`ef\` is passed and \`efConstructionSearch\` (or \`efConstruction\`) is not explicitly set, the search budget auto-scales with index size.
2264
2291
  - \`cosine\` is the default distance function when \`distance\` is not specified.
2265
- `},wa={name:`readHarperSkill`,description:`Returns documentation for a Harper skill or best practice. Skills provide guidance on developing Harper applications.`,inputSchema:l({skill:v(Sa)})};async function Ta({input:{skill:e}}){return{success:!!Ca[e],message:Ca[e]||`No skill found with the name ${e}`}}var Ea={...wa,icon:it,execute:Ta},Da={name:`readLogs`,description:`Returns the matching logs from the server.`,inputSchema:l({log_name:v([`hdb.log`,`system.log`]).default(`hdb.log`),limit:y().or(g()).optional(),level:v([`notify`,`error`,`warn`,`info`,`debug`,`trace`,`undefined`]).or(g()).optional(),from:y().or(g()).optional(),until:y().or(g()).optional()})};async function Oa({input:e,instanceClientParams:t}){try{return{success:!0,data:await ze({...t,logFilters:e,replicated:t.entityType===`cluster`})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var ka={...Da,icon:ct,execute:Oa},Aa={name:`readTableRecords`,description:`Retrieves some or all table records from a database on the server.`,inputSchema:l({database:y().trim(),table:y().trim(),pageIndex:u().default(0),pageSize:u().default(10),primaryKey:y(),conditions:m(l({search_attribute:y(),search_type:v([`between`,`eq`,`equals`,`greater_than`,`greater_than_equal`,`less_than`,`less_than_equal`,`ne`,`not_equal`,`starts_with`]),search_value:i()})),sort:l({attribute:y(),descending:_()})})};async function ja({input:{database:e,table:t,conditions:n,primaryKey:r,...i},instanceClientParams:a}){try{if(!n.length){let{data:n}=await Me({...a,databaseName:e,tableName:t,onlyIfCached:!0,searchAttribute:r,...i});return{success:!0,data:n}}let{data:o}=await Oe({...a,databaseName:e,tableName:t,onlyIfCached:!0,conditions:n,...i});return{success:!0,data:o}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Ma={...Aa,icon:Ge,execute:ja},Na={name:`restartHTTPService`,description:`Restarts the HTTP service on the server to allow schema and resource changes to be applied.`,inputSchema:l({})};async function Pa({instanceClientParams:e,baseURL:t}){let n=se.loading(`Restarting HTTP service...`,{description:`This may take a bit.`,duration:3e5});try{await Qe({...e,operation:`restart_service`,replicated:e.entityType===`cluster`})}catch(e){return{success:!1,message:`Error: ${e}`}}return se.success(`Done!`,{description:`HTTP Service restarted!`,id:n,duration:5e3}),{success:!0,message:`HTTP Service restarted!`,webURL:t}}var Fa={...Na,icon:Ze,execute:Pa,requiresApproval:!0},Ia={name:`setComponentFile`,description:`Returns the contents of a component file by its full path (which was returned by getComponents)`,inputSchema:l({path:y().trim(),payload:y(),encoding:v([`utf8`,`ASCII`,`binary`,`hex`,`base64`,`utf16le`,`latin1`,`ucs2`])})};async function La({input:{path:e,encoding:t,payload:n},instanceClientParams:r}){try{let i=e.split(`/`),a=i.shift(),o=i.join(`/`),s=await be({...r,file:o,project:a,payload:n,encoding:t});return await Je.invalidateQueries({queryKey:[r.entityId,`get_component_file`,a,o]}),ke(`ReloadApplicationRootEntries`,!0),{success:!0,data:s}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Ra={...Ia,icon:st,execute:La,requiresApproval:!0},za={name:`updateTableRecords`,description:`Updates records in a particular table in a particular database on the server.`,inputSchema:l({database:y().trim(),table:y().trim(),records:m(i())})};async function Ba({input:{database:e,table:t,records:n},instanceClientParams:r,params:i}){try{let a=await Ve({...r,databaseName:e,tableName:t,records:n}),{databaseName:o,tableName:s}=i;return await Je.invalidateQueries({queryKey:[r.entityId,o,s]}),{success:!0,data:a}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Va={readHarperSkill:Ea,createApp:Wi,readLogs:ka,getAnalytics:$i,listAnalyticsMetrics:xa,restartHTTPService:Fa,collectFeedback:Vi,getUserContext:ma,getComponentFile:na,getComponents:aa,setComponentFile:Ra,dropComponentFile:Xi,getDescribeAll:ca,getDescribeTable:da,insertTableRecords:_a,readTableRecords:Ma,updateTableRecords:{...za,icon:rt,execute:Ba,requiresApproval:!0},deleteTableRecords:qi};function Ha(e){return Va[e]}function Ua(e){return e.state===`input-available`&&!!Ha(fi(e))?.requiresApproval}function Wa(e){let t=[];for(let[n,r]of(e??[]).entries()){if(q(r)){if(Ua(r)){t.push({kind:`part`,part:r,index:n});continue}let e=t.at(-1);e?.kind===`tool-group`?e.parts.push(r):t.push({kind:`tool-group`,parts:[r],index:n});continue}ci(r)&&r.text.length>0&&t.push({kind:`part`,part:r,index:n})}return t}function Ga({part:e,onApprove:t,onDeny:n,onAlwaysApprove:r,isApproving:i}){let[a,o]=(0,T.useState)(!1),[s,c]=(0,T.useState)(!1),l=fi(e),u=Ha(l),d=u?.icon||Ee,f=u?.requiresApproval,p=(0,T.useMemo)(()=>!e.input||typeof e.input==`object`&&Object.keys(e.input).length===0,[e.input]),m=(0,T.useMemo)(()=>{let t=JSON.stringify(e.input,null,` `);return{json:t,lines:t?t.split(`
2292
+ `},ao={name:`readHarperSkill`,description:`Returns documentation for a Harper skill or best practice. Skills provide guidance on developing Harper applications.`,inputSchema:l({skill:v(ro)})};async function oo({input:{skill:e}}){return{success:!!io[e],message:io[e]||`No skill found with the name ${e}`}}var so={...ao,icon:ot,execute:oo},co={name:`readLogs`,description:`Returns the matching logs from the server.`,inputSchema:l({log_name:v([`hdb.log`,`system.log`]).default(`hdb.log`),limit:y().or(g()).optional(),level:v([`notify`,`error`,`warn`,`info`,`debug`,`trace`,`undefined`]).or(g()).optional(),from:y().or(g()).optional(),until:y().or(g()).optional()})};async function lo({input:e,instanceClientParams:t}){try{return{success:!0,data:await ze({...t,logFilters:e,replicated:t.entityType===`cluster`})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var uo={...co,icon:mt,execute:lo},fo={name:`readTableRecords`,description:`Retrieves some or all table records from a database on the server.`,inputSchema:l({database:y().trim(),table:y().trim(),pageIndex:u().default(0),pageSize:u().default(10),primaryKey:y(),conditions:m(l({search_attribute:y(),search_type:v([`between`,`eq`,`equals`,`greater_than`,`greater_than_equal`,`less_than`,`less_than_equal`,`ne`,`not_equal`,`starts_with`]),search_value:i()})),sort:l({attribute:y(),descending:_()})})};async function po({input:{database:e,table:t,conditions:n,primaryKey:r,...i},instanceClientParams:a}){try{if(!n.length){let{data:n}=await Ae({...a,databaseName:e,tableName:t,onlyIfCached:!0,searchAttribute:r,...i});return{success:!0,data:n}}let{data:o}=await Ee({...a,databaseName:e,tableName:t,onlyIfCached:!0,conditions:n,...i});return{success:!0,data:o}}catch(e){return{success:!1,message:`Error: ${e}`}}}var mo={...fo,icon:Re,execute:po},ho={name:`restartHTTPService`,description:`Restarts the HTTP service on the server to allow schema and resource changes to be applied.`,inputSchema:l({})};async function go({instanceClientParams:e,baseURL:t}){let n=se.loading(`Restarting HTTP service...`,{description:`This may take a bit.`,duration:3e5});try{await Qe({...e,operation:`restart_service`,replicated:e.entityType===`cluster`})}catch(e){return{success:!1,message:`Error: ${e}`}}return se.success(`Done!`,{description:`HTTP Service restarted!`,id:n,duration:5e3}),{success:!0,message:`HTTP Service restarted!`,webURL:t}}var _o={...ho,icon:Ze,execute:go,requiresApproval:!0},vo={name:`setComponentFile`,description:`Returns the contents of a component file by its full path (which was returned by getComponents)`,inputSchema:l({path:y().trim(),payload:y(),encoding:v([`utf8`,`ASCII`,`binary`,`hex`,`base64`,`utf16le`,`latin1`,`ucs2`])})};async function yo({input:{path:e,encoding:t,payload:n},instanceClientParams:r}){try{let i=e.split(`/`),a=i.shift(),o=i.join(`/`),s=await ye({...r,file:o,project:a,payload:n,encoding:t});return await Be.invalidateQueries({queryKey:[r.entityId,`get_component_file`,a,o]}),De(`ReloadApplicationRootEntries`,!0),{success:!0,data:s}}catch(e){return{success:!1,message:`Error: ${e}`}}}var bo={...vo,icon:ft,execute:yo,requiresApproval:!0},xo={name:`updateTableRecords`,description:`Updates records in a particular table in a particular database on the server.`,inputSchema:l({database:y().trim(),table:y().trim(),records:m(i())})};async function So({input:{database:e,table:t,records:n},instanceClientParams:r,params:i}){try{let a=await Ve({...r,databaseName:e,tableName:t,records:n}),{databaseName:o,tableName:s}=i;return await Be.invalidateQueries({queryKey:[r.entityId,o,s]}),{success:!0,data:a}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Co={readHarperSkill:so,createApp:Ta,readLogs:uo,getAnalytics:Pa,listAnalyticsMetrics:no,restartHTTPService:_o,collectFeedback:Sa,getUserContext:Ya,getComponentFile:La,getComponents:Ba,setComponentFile:bo,dropComponentFile:ja,getDescribeAll:Ua,getDescribeTable:Ka,insertTableRecords:Qa,readTableRecords:mo,updateTableRecords:{...xo,icon:it,execute:So,requiresApproval:!0},deleteTableRecords:Oa};function wo(e){return Co[e]}function To(e){return e.state===`input-available`&&!!wo(Hi(e))?.requiresApproval}function Eo(e){let t=[];for(let[n,r]of(e??[]).entries()){if(q(r)){if(To(r)){t.push({kind:`part`,part:r,index:n});continue}let e=t.at(-1);e?.kind===`tool-group`?e.parts.push(r):t.push({kind:`tool-group`,parts:[r],index:n});continue}Ri(r)&&r.text.length>0&&t.push({kind:`part`,part:r,index:n})}return t}function Do({part:e,onApprove:t,onDeny:n,onAlwaysApprove:r,isApproving:i}){let[a,o]=(0,T.useState)(!1),[s,c]=(0,T.useState)(!1),l=Hi(e),u=wo(l),d=u?.icon||Ke,f=u?.requiresApproval,p=(0,T.useMemo)(()=>!e.input||typeof e.input==`object`&&Object.keys(e.input).length===0,[e.input]),m=(0,T.useMemo)(()=>{let t=JSON.stringify(e.input,null,` `);return{json:t,lines:t?t.split(`
2266
2293
  `).length:0}},[e.input]),h=(0,T.useMemo)(()=>{let t=JSON.stringify(e.output,null,` `);return{json:t,lines:t?t.split(`
2267
- `).length:0}},[e.output]);return(0,E.jsxs)(`div`,{className:`tool-invocation ${e.state}`,children:[(0,E.jsxs)(`div`,{className:`tool-info`,children:[(0,E.jsxs)(`div`,{className:`tool-name`,children:[(0,E.jsx)(d,{size:14}),(0,E.jsx)(`span`,{children:l})]}),(0,E.jsxs)(`div`,{className:`tool-status`,children:[e.state===`input-streaming`&&(0,E.jsx)(`span`,{children:`Thinking...`}),e.state===`input-available`&&(0,E.jsx)(`span`,{children:i?`Executing...`:f?`Awaiting Approval...`:`Executing...`}),e.state===`output-available`&&(e.output?.error?(0,E.jsx)(ot,{size:14,className:`text-destructive`}):(0,E.jsx)(le,{size:14}))]})]}),e.state!==`input-streaming`&&(0,E.jsxs)(`div`,{className:`tool-io`,children:[!p&&(0,E.jsxs)(`div`,{className:`tool-args`,children:[(0,E.jsxs)(`div`,{className:`flex items-center justify-between gap-2 mb-1`,children:[(0,E.jsx)(`strong`,{children:`Input:`}),m.lines>3&&(0,E.jsx)(C,{type:`button`,variant:`ghost`,size:`sm`,className:`h-6 px-2 text-[10px] uppercase tracking-wider text-muted-foreground hover:text-foreground`,onClick:()=>o(!a),children:a?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(ue,{size:12}),`Hide`]}):(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(ce,{size:12}),`Show`]})})]}),(0,E.jsx)(`div`,{className:a?`whitespace-pre-wrap`:`line-clamp-3 overflow-hidden whitespace-pre-wrap`,children:m.json})]}),e.state===`input-available`&&f&&(0,E.jsxs)(`div`,{className:`flex gap-2 mt-3 pt-3 border-t`,children:[(0,E.jsxs)(C,{size:`sm`,className:`h-8 text-xs bg-green-600 hover:bg-green-700 text-white`,onClick:()=>t?.(e.toolCallId),disabled:i,children:[i?(0,E.jsx)(Fe,{className:`mr-2 h-3 w-3 animate-spin`}):null,`Approve`]}),(0,E.jsx)(C,{type:`button`,size:`sm`,variant:`outline`,className:`h-8 text-xs approval-outline`,onClick:()=>r?.(e.toolCallId),disabled:i,children:`Always Approve`}),(0,E.jsx)(C,{type:`button`,size:`sm`,variant:`outline`,className:`h-8 text-xs approval-outline`,onClick:()=>n?.(e.toolCallId),disabled:i,children:`Deny`})]}),e.state===`output-available`&&(0,E.jsx)(E.Fragment,{children:u?.render?u.render(e):(0,E.jsxs)(`div`,{className:`tool-result`,children:[(0,E.jsxs)(`div`,{className:`flex items-center justify-between gap-2 mb-1`,children:[(0,E.jsx)(`strong`,{children:`Result:`}),h.lines>3&&(0,E.jsx)(C,{type:`button`,variant:`ghost`,size:`sm`,className:`h-6 px-2 text-[10px] uppercase tracking-wider text-muted-foreground hover:text-foreground`,onClick:()=>c(!s),children:s?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(ue,{size:12}),`Hide`]}):(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(ce,{size:12}),`Show`]})})]}),(0,E.jsx)(`div`,{className:s?`whitespace-pre-wrap`:`line-clamp-3 overflow-hidden whitespace-pre-wrap`,children:h.json})]})})]})]})}function Ka({parts:e,onApprove:t,onDeny:n,onAlwaysApprove:r,approvingToolCallIds:i}){let[a,o]=(0,T.useState)(!1),s=e.some(e=>e.state!==`output-available`&&e.state!==`output-error`),c=e.some(e=>e.state===`output-error`||e.state===`output-available`&&e.output?.error),l=e.length===1?fi(e[0]):void 0,u=l&&Ha(l)?.icon||dt,d=l??`${e.length} tools`;return(0,E.jsxs)(`div`,{className:`tool-group`,children:[(0,E.jsxs)(`button`,{type:`button`,className:`tool-group-summary`,"aria-expanded":a,onClick:()=>o(!a),children:[a?(0,E.jsx)(ce,{size:14}):(0,E.jsx)(Ae,{size:14}),(0,E.jsx)(u,{size:14}),(0,E.jsx)(`span`,{children:s?`Using ${d}...`:`Used ${d}`}),(0,E.jsx)(`span`,{className:`tool-group-status`,children:s?(0,E.jsx)(Fe,{size:14,className:`animate-spin`}):c?(0,E.jsx)(ot,{size:14,className:`text-destructive`}):(0,E.jsx)(le,{size:14})})]}),a&&e.map(e=>(0,E.jsx)(Ga,{part:e,onApprove:t,onDeny:n,onAlwaysApprove:r,isApproving:i?.has(e.toolCallId)},e.toolCallId))]})}function qa({message:e,onApprove:t,onDeny:n,onAlwaysApprove:r,approvingToolCallIds:i}){return e.parts?.some(e=>ci(e)&&e.text.length>0||q(e))?(0,E.jsxs)(tt.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:`message-bubble ${e.role===`user`?`user`:`assistant`}`,children:[(0,E.jsx)(`div`,{className:`avatar`,children:e.role===`user`?(0,E.jsx)(Be,{size:18}):(0,E.jsx)(et,{size:18})}),(0,E.jsx)(`div`,{className:`content`,children:Wa(e.parts).map(e=>{if(e.kind===`tool-group`)return(0,E.jsx)(Ka,{parts:e.parts,onApprove:t,onDeny:n,onAlwaysApprove:r,approvingToolCallIds:i},e.parts[0].toolCallId);let{part:a,index:o}=e;return ci(a)?(0,E.jsx)(`div`,{className:`text-block`,children:a.text},o):q(a)?(0,E.jsx)(Ga,{part:a,onApprove:t,onDeny:n,onAlwaysApprove:r,isApproving:i?.has(a.toolCallId)},o):null})})]},e.id):null}function Ja(e,t){if(e!==`submitted`&&e!==`streaming`)return!1;if(t?.role!==`assistant`)return!0;let n=t.parts?.at(-1);return n?ci(n)?n.state!==`streaming`||n.text.length===0:!q(n)||n.state===`output-available`||n.state===`output-error`:!0}function Ya(){return(0,E.jsxs)(tt.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.2},className:`message-bubble assistant`,children:[(0,E.jsx)(`div`,{className:`avatar`,children:(0,E.jsx)(et,{size:18})}),(0,E.jsxs)(`div`,{className:`content thinking-indicator`,role:`status`,"aria-label":`Harper Agent is thinking`,children:[(0,E.jsx)(`span`,{className:`thinking-dot`}),(0,E.jsx)(`span`,{className:`thinking-dot`}),(0,E.jsx)(`span`,{className:`thinking-dot`})]})]})}function Xa(e){return ne({queryKey:[`getMyUsage`,e],queryFn:async()=>{let{data:t}=await S.get(`/Chat/Usage/${e}`);return t}})}function Za(){let{organizationId:e}=re({strict:!1});return ae(Xa(e))}function Qa(){let{data:e,isLoading:t,error:n}=Za();if(t||n||!e)return null;let{usageUSD:r,monthlyLimitUSD:i,usageBarPercent:a}=e,o=e=>new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`}).format(e);return(0,E.jsxs)(`div`,{className:`usage-container`,children:[(0,E.jsxs)(`div`,{className:`usage-info`,children:[(0,E.jsx)(`span`,{children:`Monthly Org Usage`}),(0,E.jsxs)(`span`,{children:[o(r),` / `,o(i)]}),(0,E.jsxs)(`span`,{children:[Math.round(a),`%`]})]}),(0,E.jsx)(`div`,{className:`usage-bar-bg`,children:(0,E.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${a}%`}})})]})}function $a({autoFocus:e,closeChat:t}){let n=re({strict:!1}),{organizationId:r}=n,[i,a]=Pe(`ApplicationChat`,``),[o,s]=(0,T.useState)(!0),[c,l]=(0,T.useState)({}),[u,d]=(0,T.useState)(new Set),[f,p]=we(Ce.ChatAlwaysApprovedTools,[]),m=new Set(f),h=$e(),g=Te(),_=ie(),{messages:v,sendMessage:y,status:b,addToolOutput:x,setMessages:S}=Ii({transport:Si(r),generateId:j(),sendAutomaticallyWhen:xi,onFinish(){_.invalidateQueries({queryKey:[`getMyUsage`]})},async onToolCall({toolCall:e}){if(e.dynamic)return;let t=Ha(e.toolName);if(t){if(t.requiresApproval&&!m.has(e.toolName)){let t={type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.input};l(n=>({...n,[e.toolCallId]:t}));return}let r=await t.execute({input:e.input,instanceClientParams:g,baseURL:h,params:n});x({tool:e.toolName,toolCallId:e.toolCallId,output:r})}}}),C=(0,T.useCallback)(async e=>{let t=c[e];if(t){d(t=>{let n=new Set(t);return n.add(e),n});try{let r=Ha(t.toolName);if(r){let i=await r.execute({input:t.input,instanceClientParams:g,baseURL:h,params:n});x({tool:t.toolName,toolCallId:t.toolCallId,output:i}),l(t=>{let n={...t};return delete n[e],n})}}finally{d(t=>{let n=new Set(t);return n.delete(e),n})}}},[c,g,h,x,n]),ee=(0,T.useCallback)(e=>{let t=c[e];t&&(x({tool:t.toolName,toolCallId:t.toolCallId,output:{error:`User denied the tool execution.`}}),l(t=>{let n={...t};return delete n[e],n}))},[c,x]),te=(0,T.useCallback)(async e=>{let t=c[e];t&&(p(e=>je([...e,t.toolName])),await C(e))},[c,p,C]);(0,T.useEffect)(()=>{(async()=>{try{let e=await mt();Array.isArray(e)&&S(e)}catch(e){console.error(`Failed to fetch initial messages:`,e)}finally{s(!1)}})()},[S]);let ne=b===`streaming`||b===`submitted`,ae=(0,T.useRef)(null);return(0,T.useEffect)(()=>{ae.current?.scrollIntoView({behavior:`smooth`})},[v]),(0,E.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,E.jsxs)(`div`,{className:`flex items-start justify-between gap-6 px-4 py-2.5 border-b border-border bg-card`,children:[(0,E.jsxs)(`div`,{className:`flex flex-col gap-1 min-w-0 flex-1`,children:[(0,E.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,E.jsx)(et,{className:`text-primary`,size:20}),(0,E.jsx)(`span`,{className:`font-semibold text-foreground`,children:`Harper Agent`})]}),(0,E.jsx)(Qa,{})]}),(0,E.jsxs)(`div`,{className:`flex items-center gap-2 shrink-0`,children:[(0,E.jsx)(pt,{setMessages:S}),(0,E.jsx)(`button`,{onClick:t,className:`p-1 hover:bg-accent rounded-md transition-colors text-muted-foreground hover:text-foreground`,title:`Close chat`,children:(0,E.jsx)(Se,{size:20})})]})]}),(0,E.jsx)(`div`,{className:`flex-1 overflow-hidden`,children:(0,E.jsxs)(`div`,{className:`chat-interface h-full w-full`,children:[(0,E.jsxs)(`div`,{className:`messages-area`,children:[o&&(0,E.jsx)(Ri,{}),!o&&v.length===0&&(0,E.jsxs)(`div`,{className:`empty-state`,children:[(0,E.jsx)(et,{size:48}),(0,E.jsx)(`p`,{children:`Ask me to create a Harper app!`})]}),v.map(e=>(0,E.jsx)(qa,{message:e,onApprove:C,onDeny:ee,onAlwaysApprove:te,approvingToolCallIds:u},e.id)),Ja(b,v.at(-1))&&(0,E.jsx)(Ya,{}),(0,E.jsx)(`div`,{ref:ae})]}),(0,E.jsx)(Li,{input:i,setInput:a,onSubmit:e=>{e.preventDefault(),i.trim()&&!ne&&!o&&(y({text:i}),a(``))},disabled:o,autoFocus:e})]})})]})}export{$a as Chat};
2294
+ `).length:0}},[e.output]);return(0,E.jsxs)(`div`,{className:`tool-invocation ${e.state}`,children:[(0,E.jsxs)(`div`,{className:`tool-info`,children:[(0,E.jsxs)(`div`,{className:`tool-name`,children:[(0,E.jsx)(d,{size:14}),(0,E.jsx)(`span`,{children:l})]}),(0,E.jsxs)(`div`,{className:`tool-status`,children:[e.state===`input-streaming`&&(0,E.jsx)(`span`,{children:`Thinking...`}),e.state===`input-available`&&(0,E.jsx)(`span`,{children:i?`Executing...`:f?`Awaiting Approval...`:`Executing...`}),e.state===`output-available`&&(e.output?.error?(0,E.jsx)(ut,{size:14,className:`text-destructive`}):(0,E.jsx)(le,{size:14}))]})]}),e.state!==`input-streaming`&&(0,E.jsxs)(`div`,{className:`tool-io`,children:[!p&&(0,E.jsxs)(`div`,{className:`tool-args`,children:[(0,E.jsxs)(`div`,{className:`flex items-center justify-between gap-2 mb-1`,children:[(0,E.jsx)(`strong`,{children:`Input:`}),m.lines>3&&(0,E.jsx)(C,{type:`button`,variant:`ghost`,size:`sm`,className:`h-6 px-2 text-[10px] uppercase tracking-wider text-muted-foreground hover:text-foreground`,onClick:()=>o(!a),children:a?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(ue,{size:12}),`Hide`]}):(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(ce,{size:12}),`Show`]})})]}),(0,E.jsx)(`div`,{className:a?`whitespace-pre-wrap`:`line-clamp-3 overflow-hidden whitespace-pre-wrap`,children:m.json})]}),e.state===`input-available`&&f&&(0,E.jsxs)(`div`,{className:`flex gap-2 mt-3 pt-3 border-t`,children:[(0,E.jsxs)(C,{size:`sm`,className:`h-8 text-xs bg-green-600 hover:bg-green-700 text-white`,onClick:()=>t?.(e.toolCallId),disabled:i,children:[i?(0,E.jsx)(Te,{className:`mr-2 h-3 w-3 animate-spin`}):null,`Approve`]}),(0,E.jsx)(C,{type:`button`,size:`sm`,variant:`outline`,className:`h-8 text-xs approval-outline`,onClick:()=>r?.(e.toolCallId),disabled:i,children:`Always Approve`}),(0,E.jsx)(C,{type:`button`,size:`sm`,variant:`outline`,className:`h-8 text-xs approval-outline`,onClick:()=>n?.(e.toolCallId),disabled:i,children:`Deny`})]}),e.state===`output-available`&&(0,E.jsx)(E.Fragment,{children:u?.render?u.render(e):(0,E.jsxs)(`div`,{className:`tool-result`,children:[(0,E.jsxs)(`div`,{className:`flex items-center justify-between gap-2 mb-1`,children:[(0,E.jsx)(`strong`,{children:`Result:`}),h.lines>3&&(0,E.jsx)(C,{type:`button`,variant:`ghost`,size:`sm`,className:`h-6 px-2 text-[10px] uppercase tracking-wider text-muted-foreground hover:text-foreground`,onClick:()=>c(!s),children:s?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(ue,{size:12}),`Hide`]}):(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(ce,{size:12}),`Show`]})})]}),(0,E.jsx)(`div`,{className:s?`whitespace-pre-wrap`:`line-clamp-3 overflow-hidden whitespace-pre-wrap`,children:h.json})]})})]})]})}function Oo({parts:e,onApprove:t,onDeny:n,onAlwaysApprove:r,approvingToolCallIds:i}){let[a,o]=(0,T.useState)(!1),s=e.some(e=>e.state!==`output-available`&&e.state!==`output-error`),c=e.some(e=>e.state===`output-error`||e.state===`output-available`&&e.output?.error),l=e.length===1?Hi(e[0]):void 0,u=l&&wo(l)?.icon||bt,d=l??`${e.length} tools`;return(0,E.jsxs)(`div`,{className:`tool-group`,children:[(0,E.jsxs)(`button`,{type:`button`,className:`tool-group-summary`,"aria-expanded":a,onClick:()=>o(!a),children:[a?(0,E.jsx)(ce,{size:14}):(0,E.jsx)(Me,{size:14}),(0,E.jsx)(u,{size:14}),(0,E.jsx)(`span`,{children:s?`Using ${d}...`:`Used ${d}`}),(0,E.jsx)(`span`,{className:`tool-group-status`,children:s?(0,E.jsx)(Te,{size:14,className:`animate-spin`}):c?(0,E.jsx)(ut,{size:14,className:`text-destructive`}):(0,E.jsx)(le,{size:14})})]}),a&&e.map(e=>(0,E.jsx)(Do,{part:e,onApprove:t,onDeny:n,onAlwaysApprove:r,isApproving:i?.has(e.toolCallId)},e.toolCallId))]})}function ko({message:e,onApprove:t,onDeny:n,onAlwaysApprove:r,approvingToolCallIds:i}){return e.parts?.some(e=>Ri(e)&&e.text.length>0||q(e))?(0,E.jsxs)(tt.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:`message-bubble ${e.role===`user`?`user`:`assistant`}`,children:[(0,E.jsx)(`div`,{className:`avatar`,children:e.role===`user`?(0,E.jsx)(Ye,{size:18}):(0,E.jsx)(et,{size:18})}),(0,E.jsx)(`div`,{className:`content`,children:Eo(e.parts).map(e=>{if(e.kind===`tool-group`)return(0,E.jsx)(Oo,{parts:e.parts,onApprove:t,onDeny:n,onAlwaysApprove:r,approvingToolCallIds:i},e.parts[0].toolCallId);let{part:a,index:o}=e;return Ri(a)?(0,E.jsx)(`div`,{className:`text-block`,children:a.text},o):q(a)?(0,E.jsx)(Do,{part:a,onApprove:t,onDeny:n,onAlwaysApprove:r,isApproving:i?.has(a.toolCallId)},o):null})})]},e.id):null}function Ao(e,t){if(e!==`submitted`&&e!==`streaming`)return!1;if(t?.role!==`assistant`)return!0;let n=t.parts?.at(-1);return n?Ri(n)?n.state!==`streaming`||n.text.length===0:!q(n)||n.state===`output-available`||n.state===`output-error`:!0}function jo(){return(0,E.jsxs)(tt.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.2},className:`message-bubble assistant`,children:[(0,E.jsx)(`div`,{className:`avatar`,children:(0,E.jsx)(et,{size:18})}),(0,E.jsxs)(`div`,{className:`content thinking-indicator`,role:`status`,"aria-label":`Harper Agent is thinking`,children:[(0,E.jsx)(`span`,{className:`thinking-dot`}),(0,E.jsx)(`span`,{className:`thinking-dot`}),(0,E.jsx)(`span`,{className:`thinking-dot`})]})]})}function Mo(e){return re({queryKey:[`getMyUsage`,e],queryFn:async()=>{let{data:t}=await S.get(`/Chat/Usage/${e}`);return t}})}function No(){let{organizationId:e}=ie({strict:!1});return ae(Mo(e))}function Po(){let{data:e,isLoading:t,error:n}=No();if(t||n||!e)return null;let{usageUSD:r,monthlyLimitUSD:i,usageBarPercent:a}=e,o=e=>new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`}).format(e);return(0,E.jsxs)(`div`,{className:`usage-container`,children:[(0,E.jsxs)(`div`,{className:`usage-info`,children:[(0,E.jsx)(`span`,{children:`Monthly Org Usage`}),(0,E.jsxs)(`span`,{children:[o(r),` / `,o(i)]}),(0,E.jsxs)(`span`,{children:[Math.round(a),`%`]})]}),(0,E.jsx)(`div`,{className:`usage-bar-bg`,children:(0,E.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${a}%`}})})]})}function Fo({autoFocus:e,closeChat:t}){let n=ie({strict:!1}),{organizationId:r}=n,[i,a]=Ne(`ApplicationChat`,``),[o,s]=(0,T.useState)(!0),[c,l]=(0,T.useState)({}),[u,d]=(0,T.useState)(new Set),[f,p]=Ce(Se.ChatAlwaysApprovedTools,[]),m=new Set(f),h=$e(),g=Oe(),_=ne(),{messages:v,sendMessage:y,status:b,addToolOutput:x,setMessages:S}=_a({transport:ra(r),generateId:j(),sendAutomaticallyWhen:na,onFinish(){_.invalidateQueries({queryKey:[`getMyUsage`]})},async onToolCall({toolCall:e}){if(e.dynamic)return;let t=wo(e.toolName);if(t){if(t.requiresApproval&&!m.has(e.toolName)){let t={type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.input};l(n=>({...n,[e.toolCallId]:t}));return}let r=await t.execute({input:e.input,instanceClientParams:g,baseURL:h,params:n});x({tool:e.toolName,toolCallId:e.toolCallId,output:r})}}}),C=(0,T.useCallback)(async e=>{let t=c[e];if(t){d(t=>{let n=new Set(t);return n.add(e),n});try{let r=wo(t.toolName);if(r){let i=await r.execute({input:t.input,instanceClientParams:g,baseURL:h,params:n});x({tool:t.toolName,toolCallId:t.toolCallId,output:i}),l(t=>{let n={...t};return delete n[e],n})}}finally{d(t=>{let n=new Set(t);return n.delete(e),n})}}},[c,g,h,x,n]),ee=(0,T.useCallback)(e=>{let t=c[e];t&&(x({tool:t.toolName,toolCallId:t.toolCallId,output:{error:`User denied the tool execution.`}}),l(t=>{let n={...t};return delete n[e],n}))},[c,x]),te=(0,T.useCallback)(async e=>{let t=c[e];t&&(p(e=>ke([...e,t.toolName])),await C(e))},[c,p,C]);(0,T.useEffect)(()=>{(async()=>{try{let e=await Ct();Array.isArray(e)&&S(e)}catch(e){console.error(`Failed to fetch initial messages:`,e)}finally{s(!1)}})()},[S]);let re=b===`streaming`||b===`submitted`,ae=(0,T.useRef)(null);return(0,T.useEffect)(()=>{ae.current?.scrollIntoView({behavior:`smooth`})},[v]),(0,E.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,E.jsxs)(`div`,{className:`flex items-start justify-between gap-6 px-4 py-2.5 border-b border-border bg-card`,children:[(0,E.jsxs)(`div`,{className:`flex flex-col gap-1 min-w-0 flex-1`,children:[(0,E.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,E.jsx)(et,{className:`text-primary`,size:20}),(0,E.jsx)(`span`,{className:`font-semibold text-foreground`,children:`Harper Agent`})]}),(0,E.jsx)(Po,{})]}),(0,E.jsxs)(`div`,{className:`flex items-center gap-2 shrink-0`,children:[(0,E.jsx)(St,{setMessages:S}),(0,E.jsx)(`button`,{onClick:t,className:`p-1 hover:bg-accent rounded-md transition-colors text-muted-foreground hover:text-foreground`,title:`Close chat`,children:(0,E.jsx)(xe,{size:20})})]})]}),(0,E.jsx)(`div`,{className:`flex-1 overflow-hidden`,children:(0,E.jsxs)(`div`,{className:`chat-interface h-full w-full`,children:[(0,E.jsxs)(`div`,{className:`messages-area`,children:[o&&(0,E.jsx)(ya,{}),!o&&v.length===0&&(0,E.jsxs)(`div`,{className:`empty-state`,children:[(0,E.jsx)(et,{size:48}),(0,E.jsx)(`p`,{children:`Ask me to create a Harper app!`})]}),v.map(e=>(0,E.jsx)(ko,{message:e,onApprove:C,onDeny:ee,onAlwaysApprove:te,approvingToolCallIds:u},e.id)),Ao(b,v.at(-1))&&(0,E.jsx)(jo,{}),(0,E.jsx)(`div`,{ref:ae})]}),(0,E.jsx)(va,{input:i,setInput:a,onSubmit:e=>{e.preventDefault(),i.trim()&&!re&&!o&&(y({text:i}),a(``))},disabled:o,autoFocus:e})]})})]})}export{Fo as Chat};