@stackframe/stack-shared 2.8.8 → 2.8.10

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 (476) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/config/format.d.cts +39 -0
  3. package/dist/config/format.d.ts +14 -13
  4. package/dist/config/format.js +147 -206
  5. package/dist/config/format.js.map +1 -0
  6. package/dist/config/schema.d.cts +724 -0
  7. package/dist/config/schema.d.ts +51 -48
  8. package/dist/config/schema.js +230 -172
  9. package/dist/config/schema.js.map +1 -0
  10. package/dist/crud.d.cts +102 -0
  11. package/dist/crud.d.ts +15 -13
  12. package/dist/crud.js +83 -128
  13. package/dist/crud.js.map +1 -0
  14. package/dist/esm/config/format.js +135 -0
  15. package/dist/esm/config/format.js.map +1 -0
  16. package/dist/esm/config/schema.js +199 -0
  17. package/dist/esm/config/schema.js.map +1 -0
  18. package/dist/esm/crud.js +60 -0
  19. package/dist/esm/crud.js.map +1 -0
  20. package/dist/esm/global.d.js +1 -0
  21. package/dist/esm/global.d.js.map +1 -0
  22. package/dist/esm/helpers/password.js +17 -0
  23. package/dist/esm/helpers/password.js.map +1 -0
  24. package/dist/esm/helpers/production-mode.js +50 -0
  25. package/dist/esm/helpers/production-mode.js.map +1 -0
  26. package/dist/esm/hooks/use-async-callback.js +38 -0
  27. package/dist/esm/hooks/use-async-callback.js.map +1 -0
  28. package/dist/esm/hooks/use-async-external-store.js +23 -0
  29. package/dist/esm/hooks/use-async-external-store.js.map +1 -0
  30. package/dist/esm/hooks/use-hash.js +17 -0
  31. package/dist/esm/hooks/use-hash.js.map +1 -0
  32. package/dist/esm/hooks/use-strict-memo.js +61 -0
  33. package/dist/esm/hooks/use-strict-memo.js.map +1 -0
  34. package/dist/esm/index.js +22 -0
  35. package/dist/esm/index.js.map +1 -0
  36. package/dist/esm/interface/adminInterface.js +244 -0
  37. package/dist/esm/interface/adminInterface.js.map +1 -0
  38. package/dist/esm/interface/clientInterface.js +2041 -0
  39. package/dist/esm/interface/clientInterface.js.map +1 -0
  40. package/dist/esm/interface/crud/contact-channels.js +77 -0
  41. package/dist/esm/interface/crud/contact-channels.js.map +1 -0
  42. package/dist/esm/interface/crud/current-user.js +65 -0
  43. package/dist/esm/interface/crud/current-user.js.map +1 -0
  44. package/dist/esm/interface/crud/email-templates.js +52 -0
  45. package/dist/esm/interface/crud/email-templates.js.map +1 -0
  46. package/dist/esm/interface/crud/emails.js +20 -0
  47. package/dist/esm/interface/crud/emails.js.map +1 -0
  48. package/dist/esm/interface/crud/internal-api-keys.js +69 -0
  49. package/dist/esm/interface/crud/internal-api-keys.js.map +1 -0
  50. package/dist/esm/interface/crud/oauth.js +24 -0
  51. package/dist/esm/interface/crud/oauth.js.map +1 -0
  52. package/dist/esm/interface/crud/project-api-keys.js +93 -0
  53. package/dist/esm/interface/crud/project-api-keys.js.map +1 -0
  54. package/dist/esm/interface/crud/project-permissions.js +113 -0
  55. package/dist/esm/interface/crud/project-permissions.js.map +1 -0
  56. package/dist/esm/interface/crud/projects.js +188 -0
  57. package/dist/esm/interface/crud/projects.js.map +1 -0
  58. package/dist/esm/interface/crud/sessions.js +62 -0
  59. package/dist/esm/interface/crud/sessions.js.map +1 -0
  60. package/dist/esm/interface/crud/svix-token.js +22 -0
  61. package/dist/esm/interface/crud/svix-token.js.map +1 -0
  62. package/dist/esm/interface/crud/team-invitation-details.js +23 -0
  63. package/dist/esm/interface/crud/team-invitation-details.js.map +1 -0
  64. package/dist/esm/interface/crud/team-invitation.js +36 -0
  65. package/dist/esm/interface/crud/team-invitation.js.map +1 -0
  66. package/dist/esm/interface/crud/team-member-profiles.js +62 -0
  67. package/dist/esm/interface/crud/team-member-profiles.js.map +1 -0
  68. package/dist/esm/interface/crud/team-memberships.js +60 -0
  69. package/dist/esm/interface/crud/team-memberships.js.map +1 -0
  70. package/dist/esm/interface/crud/team-permissions.js +114 -0
  71. package/dist/esm/interface/crud/team-permissions.js.map +1 -0
  72. package/dist/esm/interface/crud/teams.js +143 -0
  73. package/dist/esm/interface/crud/teams.js.map +1 -0
  74. package/dist/esm/interface/crud/users.js +139 -0
  75. package/dist/esm/interface/crud/users.js.map +1 -0
  76. package/dist/esm/interface/serverInterface.js +485 -0
  77. package/dist/esm/interface/serverInterface.js.map +1 -0
  78. package/dist/esm/interface/webhooks.js +21 -0
  79. package/dist/esm/interface/webhooks.js.map +1 -0
  80. package/dist/esm/known-errors.js +1223 -0
  81. package/dist/esm/known-errors.js.map +1 -0
  82. package/dist/esm/schema-fields.js +484 -0
  83. package/dist/esm/schema-fields.js.map +1 -0
  84. package/dist/esm/sessions.js +168 -0
  85. package/dist/esm/sessions.js.map +1 -0
  86. package/dist/esm/utils/api-keys.js +79 -0
  87. package/dist/esm/utils/api-keys.js.map +1 -0
  88. package/dist/esm/utils/arrays.js +78 -0
  89. package/dist/esm/utils/arrays.js.map +1 -0
  90. package/dist/esm/utils/base64.js +18 -0
  91. package/dist/esm/utils/base64.js.map +1 -0
  92. package/dist/esm/utils/booleans.js +12 -0
  93. package/dist/esm/utils/booleans.js.map +1 -0
  94. package/dist/esm/utils/browser-compat.js +21 -0
  95. package/dist/esm/utils/browser-compat.js.map +1 -0
  96. package/dist/esm/utils/bytes.js +160 -0
  97. package/dist/esm/utils/bytes.js.map +1 -0
  98. package/dist/esm/utils/caches.js +167 -0
  99. package/dist/esm/utils/caches.js.map +1 -0
  100. package/dist/esm/utils/compile-time.js +11 -0
  101. package/dist/esm/utils/compile-time.js.map +1 -0
  102. package/dist/esm/utils/crypto.js +25 -0
  103. package/dist/esm/utils/crypto.js.map +1 -0
  104. package/dist/esm/utils/dates.js +64 -0
  105. package/dist/esm/utils/dates.js.map +1 -0
  106. package/dist/esm/utils/dom.js +11 -0
  107. package/dist/esm/utils/dom.js.map +1 -0
  108. package/dist/esm/utils/env.js +58 -0
  109. package/dist/esm/utils/env.js.map +1 -0
  110. package/dist/esm/utils/errors.js +174 -0
  111. package/dist/esm/utils/errors.js.map +1 -0
  112. package/dist/esm/utils/fs.js +37 -0
  113. package/dist/esm/utils/fs.js.map +1 -0
  114. package/dist/esm/utils/functions.js +12 -0
  115. package/dist/esm/utils/functions.js.map +1 -0
  116. package/dist/esm/utils/geo.js +15 -0
  117. package/dist/esm/utils/geo.js.map +1 -0
  118. package/dist/esm/utils/globals.js +18 -0
  119. package/dist/esm/utils/globals.js.map +1 -0
  120. package/dist/esm/utils/hashes.js +55 -0
  121. package/dist/esm/utils/hashes.js.map +1 -0
  122. package/dist/esm/utils/html.js +13 -0
  123. package/dist/esm/utils/html.js.map +1 -0
  124. package/dist/esm/utils/http.js +60 -0
  125. package/dist/esm/utils/http.js.map +1 -0
  126. package/dist/esm/utils/ips.js +15 -0
  127. package/dist/esm/utils/ips.js.map +1 -0
  128. package/dist/esm/utils/json.js +31 -0
  129. package/dist/esm/utils/json.js.map +1 -0
  130. package/dist/esm/utils/jwt.js +87 -0
  131. package/dist/esm/utils/jwt.js.map +1 -0
  132. package/dist/esm/utils/locks.js +57 -0
  133. package/dist/esm/utils/locks.js.map +1 -0
  134. package/dist/esm/utils/maps.js +181 -0
  135. package/dist/esm/utils/maps.js.map +1 -0
  136. package/dist/esm/utils/math.js +8 -0
  137. package/dist/esm/utils/math.js.map +1 -0
  138. package/dist/esm/utils/node-http.js +42 -0
  139. package/dist/esm/utils/node-http.js.map +1 -0
  140. package/dist/esm/utils/numbers.js +32 -0
  141. package/dist/esm/utils/numbers.js.map +1 -0
  142. package/dist/esm/utils/oauth.js +10 -0
  143. package/dist/esm/utils/oauth.js.map +1 -0
  144. package/dist/esm/utils/objects.js +153 -0
  145. package/dist/esm/utils/objects.js.map +1 -0
  146. package/dist/esm/utils/passkey.js +1 -0
  147. package/dist/esm/utils/passkey.js.map +1 -0
  148. package/dist/esm/utils/promises.js +233 -0
  149. package/dist/esm/utils/promises.js.map +1 -0
  150. package/dist/esm/utils/proxies.js +128 -0
  151. package/dist/esm/utils/proxies.js.map +1 -0
  152. package/dist/esm/utils/react.js +78 -0
  153. package/dist/esm/utils/react.js.map +1 -0
  154. package/dist/esm/utils/results.js +141 -0
  155. package/dist/esm/utils/results.js.map +1 -0
  156. package/dist/esm/utils/sentry.js +20 -0
  157. package/dist/esm/utils/sentry.js.map +1 -0
  158. package/dist/esm/utils/stores.js +195 -0
  159. package/dist/esm/utils/stores.js.map +1 -0
  160. package/dist/esm/utils/strings.js +294 -0
  161. package/dist/esm/utils/strings.js.map +1 -0
  162. package/dist/esm/utils/strings.nicify.test.js +222 -0
  163. package/dist/esm/utils/strings.nicify.test.js.map +1 -0
  164. package/dist/esm/utils/types.js +1 -0
  165. package/dist/esm/utils/types.js.map +1 -0
  166. package/dist/esm/utils/unicode.js +11 -0
  167. package/dist/esm/utils/unicode.js.map +1 -0
  168. package/dist/esm/utils/urls.js +53 -0
  169. package/dist/esm/utils/urls.js.map +1 -0
  170. package/dist/esm/utils/uuids.js +16 -0
  171. package/dist/esm/utils/uuids.js.map +1 -0
  172. package/dist/global.d.d.cts +1 -0
  173. package/dist/global.d.d.ts +1 -0
  174. package/dist/global.d.js +2 -0
  175. package/dist/global.d.js.map +1 -0
  176. package/dist/helpers/password.d.cts +11 -0
  177. package/dist/helpers/password.d.ts +11 -2
  178. package/dist/helpers/password.js +41 -11
  179. package/dist/helpers/password.js.map +1 -0
  180. package/dist/helpers/production-mode.d.cts +12 -0
  181. package/dist/helpers/production-mode.d.ts +9 -3
  182. package/dist/helpers/production-mode.js +72 -45
  183. package/dist/helpers/production-mode.js.map +1 -0
  184. package/dist/hooks/use-async-callback.d.cts +6 -0
  185. package/dist/hooks/use-async-callback.d.ts +6 -3
  186. package/dist/hooks/use-async-callback.js +72 -30
  187. package/dist/hooks/use-async-callback.js.map +1 -0
  188. package/dist/hooks/use-async-external-store.d.cts +7 -0
  189. package/dist/hooks/use-async-external-store.d.ts +5 -2
  190. package/dist/hooks/use-async-external-store.js +47 -19
  191. package/dist/hooks/use-async-external-store.js.map +1 -0
  192. package/dist/hooks/use-hash.d.cts +3 -0
  193. package/dist/hooks/use-hash.d.ts +3 -1
  194. package/dist/hooks/use-hash.js +41 -8
  195. package/dist/hooks/use-hash.js.map +1 -0
  196. package/dist/hooks/use-strict-memo.d.cts +8 -0
  197. package/dist/hooks/use-strict-memo.d.ts +3 -1
  198. package/dist/hooks/use-strict-memo.js +78 -131
  199. package/dist/hooks/use-strict-memo.js.map +1 -0
  200. package/dist/index.d.cts +30 -0
  201. package/dist/index.d.ts +30 -4
  202. package/dist/index.js +42 -4
  203. package/dist/index.js.map +1 -0
  204. package/dist/interface/adminInterface.d.cts +94 -0
  205. package/dist/interface/adminInterface.d.ts +38 -15
  206. package/dist/interface/adminInterface.js +269 -174
  207. package/dist/interface/adminInterface.js.map +1 -0
  208. package/dist/interface/clientInterface.d.cts +260 -0
  209. package/dist/interface/clientInterface.d.ts +25 -18
  210. package/dist/interface/clientInterface.js +2054 -995
  211. package/dist/interface/clientInterface.js.map +1 -0
  212. package/dist/interface/crud/contact-channels.d.cts +180 -0
  213. package/dist/interface/crud/contact-channels.d.ts +30 -25
  214. package/dist/interface/crud/contact-channels.js +101 -59
  215. package/dist/interface/crud/contact-channels.js.map +1 -0
  216. package/dist/interface/crud/current-user.d.cts +205 -0
  217. package/dist/interface/crud/current-user.d.ts +17 -12
  218. package/dist/interface/crud/current-user.js +86 -56
  219. package/dist/interface/crud/current-user.js.map +1 -0
  220. package/dist/interface/crud/email-templates.d.cts +84 -0
  221. package/dist/interface/crud/email-templates.d.ts +24 -19
  222. package/dist/interface/crud/email-templates.js +77 -37
  223. package/dist/interface/crud/email-templates.js.map +1 -0
  224. package/dist/interface/crud/emails.d.cts +69 -0
  225. package/dist/interface/crud/emails.d.ts +12 -7
  226. package/dist/interface/crud/emails.js +54 -12
  227. package/dist/interface/crud/emails.js.map +1 -0
  228. package/dist/interface/crud/internal-api-keys.d.cts +139 -0
  229. package/dist/interface/crud/internal-api-keys.d.ts +22 -17
  230. package/dist/interface/crud/internal-api-keys.js +92 -54
  231. package/dist/interface/crud/internal-api-keys.js.map +1 -0
  232. package/dist/interface/crud/oauth.d.cts +34 -0
  233. package/dist/interface/crud/oauth.d.ts +16 -11
  234. package/dist/interface/crud/oauth.js +48 -14
  235. package/dist/interface/crud/oauth.js.map +1 -0
  236. package/dist/interface/crud/project-api-keys.d.cts +196 -0
  237. package/dist/interface/crud/project-api-keys.d.ts +18 -10
  238. package/dist/interface/crud/project-api-keys.js +121 -74
  239. package/dist/interface/crud/project-api-keys.js.map +1 -0
  240. package/dist/interface/crud/project-permissions.d.cts +160 -0
  241. package/dist/interface/crud/project-permissions.d.ts +38 -33
  242. package/dist/interface/crud/project-permissions.js +148 -90
  243. package/dist/interface/crud/project-permissions.js.map +1 -0
  244. package/dist/interface/crud/projects.d.cts +640 -0
  245. package/dist/interface/crud/projects.d.ts +36 -31
  246. package/dist/interface/crud/projects.js +218 -156
  247. package/dist/interface/crud/projects.js.map +1 -0
  248. package/dist/interface/crud/sessions.d.cts +149 -0
  249. package/dist/interface/crud/sessions.d.ts +21 -16
  250. package/dist/interface/crud/sessions.js +86 -50
  251. package/dist/interface/crud/sessions.js.map +1 -0
  252. package/dist/interface/crud/svix-token.d.cts +26 -0
  253. package/dist/interface/crud/svix-token.d.ts +14 -9
  254. package/dist/interface/crud/svix-token.js +46 -12
  255. package/dist/interface/crud/svix-token.js.map +1 -0
  256. package/dist/interface/crud/team-invitation-details.d.cts +30 -0
  257. package/dist/interface/crud/team-invitation-details.d.ts +12 -7
  258. package/dist/interface/crud/team-invitation-details.js +57 -15
  259. package/dist/interface/crud/team-invitation-details.js.map +1 -0
  260. package/dist/interface/crud/team-invitation.d.cts +49 -0
  261. package/dist/interface/crud/team-invitation.d.ts +13 -8
  262. package/dist/interface/crud/team-invitation.js +69 -27
  263. package/dist/interface/crud/team-invitation.js.map +1 -0
  264. package/dist/interface/crud/team-member-profiles.d.cts +229 -0
  265. package/dist/interface/crud/team-member-profiles.d.ts +20 -15
  266. package/dist/interface/crud/team-member-profiles.js +95 -49
  267. package/dist/interface/crud/team-member-profiles.js.map +1 -0
  268. package/dist/interface/crud/team-memberships.d.cts +74 -0
  269. package/dist/interface/crud/team-memberships.d.ts +22 -17
  270. package/dist/interface/crud/team-memberships.js +85 -45
  271. package/dist/interface/crud/team-memberships.js.map +1 -0
  272. package/dist/interface/crud/team-permissions.d.cts +168 -0
  273. package/dist/interface/crud/team-permissions.d.ts +38 -33
  274. package/dist/interface/crud/team-permissions.js +149 -91
  275. package/dist/interface/crud/team-permissions.js.map +1 -0
  276. package/dist/interface/crud/teams.d.cts +298 -0
  277. package/dist/interface/crud/teams.d.ts +45 -40
  278. package/dist/interface/crud/teams.js +177 -119
  279. package/dist/interface/crud/teams.js.map +1 -0
  280. package/dist/interface/crud/users.d.cts +469 -0
  281. package/dist/interface/crud/users.d.ts +31 -26
  282. package/dist/interface/crud/users.js +172 -118
  283. package/dist/interface/crud/users.js.map +1 -0
  284. package/dist/interface/serverInterface.d.cts +128 -0
  285. package/dist/interface/serverInterface.d.ts +29 -17
  286. package/dist/interface/serverInterface.js +506 -339
  287. package/dist/interface/serverInterface.js.map +1 -0
  288. package/dist/interface/webhooks.d.cts +292 -0
  289. package/dist/interface/webhooks.d.ts +6 -3
  290. package/dist/interface/webhooks.js +45 -15
  291. package/dist/interface/webhooks.js.map +1 -0
  292. package/dist/known-errors.d.cts +444 -0
  293. package/dist/known-errors.d.ts +12 -9
  294. package/dist/known-errors.js +1088 -561
  295. package/dist/known-errors.js.map +1 -0
  296. package/dist/schema-fields.d.cts +163 -0
  297. package/dist/schema-fields.d.ts +116 -114
  298. package/dist/schema-fields.js +593 -427
  299. package/dist/schema-fields.js.map +1 -0
  300. package/dist/sessions.d.cts +109 -0
  301. package/dist/sessions.d.ts +6 -3
  302. package/dist/sessions.js +201 -172
  303. package/dist/sessions.js.map +1 -0
  304. package/dist/utils/api-keys.d.cts +24 -0
  305. package/dist/utils/api-keys.d.ts +5 -4
  306. package/dist/utils/api-keys.js +106 -66
  307. package/dist/utils/api-keys.js.map +1 -0
  308. package/dist/utils/arrays.d.cts +18 -0
  309. package/dist/utils/arrays.d.ts +15 -13
  310. package/dist/utils/arrays.js +101 -168
  311. package/dist/utils/arrays.js.map +1 -0
  312. package/dist/utils/base64.d.cts +4 -0
  313. package/dist/utils/base64.d.ts +4 -2
  314. package/dist/utils/base64.js +41 -20
  315. package/dist/utils/base64.js.map +1 -0
  316. package/dist/utils/booleans.d.cts +6 -0
  317. package/dist/utils/booleans.d.ts +6 -4
  318. package/dist/utils/booleans.js +35 -27
  319. package/dist/utils/booleans.js.map +1 -0
  320. package/dist/utils/browser-compat.d.cts +8 -0
  321. package/dist/utils/browser-compat.d.ts +3 -1
  322. package/dist/utils/browser-compat.js +45 -16
  323. package/dist/utils/browser-compat.js.map +1 -0
  324. package/dist/utils/bytes.d.cts +15 -0
  325. package/dist/utils/bytes.d.ts +15 -13
  326. package/dist/utils/bytes.js +182 -270
  327. package/dist/utils/bytes.js.map +1 -0
  328. package/dist/utils/caches.d.cts +98 -0
  329. package/dist/utils/caches.d.ts +17 -14
  330. package/dist/utils/caches.js +188 -193
  331. package/dist/utils/caches.js.map +1 -0
  332. package/dist/utils/compile-time.d.cts +8 -0
  333. package/dist/utils/compile-time.d.ts +3 -1
  334. package/dist/utils/compile-time.js +35 -10
  335. package/dist/utils/compile-time.js.map +1 -0
  336. package/dist/utils/crypto.d.cts +8 -0
  337. package/dist/utils/crypto.d.ts +4 -2
  338. package/dist/utils/crypto.js +49 -21
  339. package/dist/utils/crypto.js.map +1 -0
  340. package/dist/utils/dates.d.cts +15 -0
  341. package/dist/utils/dates.d.ts +6 -4
  342. package/dist/utils/dates.js +83 -105
  343. package/dist/utils/dates.js.map +1 -0
  344. package/dist/utils/dom.d.cts +3 -0
  345. package/dist/utils/dom.d.ts +3 -1
  346. package/dist/utils/dom.js +35 -7
  347. package/dist/utils/dom.js.map +1 -0
  348. package/dist/utils/env.d.cts +9 -0
  349. package/dist/utils/env.d.ts +6 -4
  350. package/dist/utils/env.js +70 -43
  351. package/dist/utils/env.js.map +1 -0
  352. package/dist/utils/errors.d.cts +223 -0
  353. package/dist/utils/errors.d.ts +14 -11
  354. package/dist/utils/errors.js +148 -126
  355. package/dist/utils/errors.js.map +1 -0
  356. package/dist/utils/fs.d.cts +7 -0
  357. package/dist/utils/fs.d.ts +5 -3
  358. package/dist/utils/fs.js +70 -27
  359. package/dist/utils/fs.js.map +1 -0
  360. package/dist/utils/functions.d.cts +4 -0
  361. package/dist/utils/functions.d.ts +4 -2
  362. package/dist/utils/functions.js +35 -18
  363. package/dist/utils/functions.js.map +1 -0
  364. package/dist/utils/geo.d.cts +22 -0
  365. package/dist/utils/geo.d.ts +6 -3
  366. package/dist/utils/geo.js +39 -9
  367. package/dist/utils/geo.js.map +1 -0
  368. package/dist/utils/globals.d.cts +5 -0
  369. package/dist/utils/globals.d.ts +4 -2
  370. package/dist/utils/globals.js +41 -14
  371. package/dist/utils/globals.js.map +1 -0
  372. package/dist/utils/hashes.d.cts +7 -0
  373. package/dist/utils/hashes.d.ts +7 -5
  374. package/dist/utils/hashes.js +87 -41
  375. package/dist/utils/hashes.js.map +1 -0
  376. package/dist/utils/html.d.cts +4 -0
  377. package/dist/utils/html.d.ts +4 -2
  378. package/dist/utils/html.js +36 -37
  379. package/dist/utils/html.js.map +1 -0
  380. package/dist/utils/http.d.cts +43 -0
  381. package/dist/utils/http.d.ts +6 -4
  382. package/dist/utils/http.js +83 -83
  383. package/dist/utils/http.js.map +1 -0
  384. package/dist/utils/ips.d.cts +6 -0
  385. package/dist/utils/ips.d.ts +6 -4
  386. package/dist/utils/ips.js +48 -35
  387. package/dist/utils/ips.js.map +1 -0
  388. package/dist/utils/json.d.cts +13 -0
  389. package/dist/utils/json.d.ts +9 -6
  390. package/dist/utils/json.js +54 -157
  391. package/dist/utils/json.js.map +1 -0
  392. package/dist/utils/jwt.d.cts +44 -0
  393. package/dist/utils/jwt.d.ts +14 -11
  394. package/dist/utils/jwt.js +119 -84
  395. package/dist/utils/jwt.js.map +1 -0
  396. package/dist/utils/locks.d.cts +15 -0
  397. package/dist/utils/locks.d.ts +3 -2
  398. package/dist/utils/locks.js +76 -56
  399. package/dist/utils/locks.js.map +1 -0
  400. package/dist/utils/maps.d.cts +59 -0
  401. package/dist/utils/maps.d.ts +6 -4
  402. package/dist/utils/maps.js +207 -343
  403. package/dist/utils/maps.js.map +1 -0
  404. package/dist/utils/math.d.cts +6 -0
  405. package/dist/utils/math.d.ts +3 -1
  406. package/dist/utils/math.js +31 -16
  407. package/dist/utils/math.js.map +1 -0
  408. package/dist/utils/node-http.d.cts +15 -0
  409. package/dist/utils/node-http.d.ts +5 -5
  410. package/dist/utils/node-http.js +65 -36
  411. package/dist/utils/node-http.js.map +1 -0
  412. package/dist/utils/numbers.d.cts +5 -0
  413. package/dist/utils/numbers.d.ts +5 -3
  414. package/dist/utils/numbers.js +53 -66
  415. package/dist/utils/numbers.js.map +1 -0
  416. package/dist/utils/oauth.d.cts +8 -0
  417. package/dist/utils/oauth.d.ts +8 -6
  418. package/dist/utils/oauth.js +37 -4
  419. package/dist/utils/oauth.js.map +1 -0
  420. package/dist/utils/objects.d.cts +65 -0
  421. package/dist/utils/objects.d.ts +31 -30
  422. package/dist/utils/objects.js +196 -374
  423. package/dist/utils/objects.js.map +1 -0
  424. package/dist/utils/passkey.d.cts +1 -0
  425. package/dist/utils/passkey.d.ts +1 -1
  426. package/dist/utils/passkey.js +19 -1
  427. package/dist/utils/passkey.js.map +1 -0
  428. package/dist/utils/promises.d.cts +74 -0
  429. package/dist/utils/promises.d.ts +20 -18
  430. package/dist/utils/promises.js +252 -393
  431. package/dist/utils/promises.js.map +1 -0
  432. package/dist/utils/proxies.d.cts +4 -0
  433. package/dist/utils/proxies.d.ts +4 -2
  434. package/dist/utils/proxies.js +150 -161
  435. package/dist/utils/proxies.js.map +1 -0
  436. package/dist/utils/react.d.cts +25 -0
  437. package/dist/utils/react.d.ts +9 -6
  438. package/dist/utils/react.js +88 -134
  439. package/dist/utils/react.js.map +1 -0
  440. package/dist/utils/results.d.cts +78 -0
  441. package/dist/utils/results.d.ts +10 -9
  442. package/dist/utils/results.js +143 -324
  443. package/dist/utils/results.js.map +1 -0
  444. package/dist/utils/sentry.d.cts +5 -0
  445. package/dist/utils/sentry.d.ts +5 -2
  446. package/dist/utils/sentry.js +44 -14
  447. package/dist/utils/sentry.js.map +1 -0
  448. package/dist/utils/stores.d.cts +102 -0
  449. package/dist/utils/stores.d.ts +12 -9
  450. package/dist/utils/stores.js +219 -189
  451. package/dist/utils/stores.js.map +1 -0
  452. package/dist/utils/strings.d.cts +72 -0
  453. package/dist/utils/strings.d.ts +22 -20
  454. package/dist/utils/strings.js +299 -580
  455. package/dist/utils/strings.js.map +1 -0
  456. package/dist/utils/strings.nicify.test.d.cts +2 -0
  457. package/dist/utils/strings.nicify.test.d.ts +2 -1
  458. package/dist/utils/strings.nicify.test.js +168 -158
  459. package/dist/utils/strings.nicify.test.js.map +1 -0
  460. package/dist/utils/types.d.cts +23 -0
  461. package/dist/utils/types.d.ts +8 -6
  462. package/dist/utils/types.js +19 -1
  463. package/dist/utils/types.js.map +1 -0
  464. package/dist/utils/unicode.d.cts +3 -0
  465. package/dist/utils/unicode.d.ts +3 -1
  466. package/dist/utils/unicode.js +34 -21
  467. package/dist/utils/unicode.js.map +1 -0
  468. package/dist/utils/urls.d.cts +20 -0
  469. package/dist/utils/urls.d.ts +10 -8
  470. package/dist/utils/urls.js +76 -165
  471. package/dist/utils/urls.js.map +1 -0
  472. package/dist/utils/uuids.d.cts +4 -0
  473. package/dist/utils/uuids.d.ts +4 -2
  474. package/dist/utils/uuids.js +39 -35
  475. package/dist/utils/uuids.js.map +1 -0
  476. package/package.json +5 -5
@@ -0,0 +1,2041 @@
1
+ // ../../node_modules/.pnpm/oauth4webapi@2.10.4/node_modules/oauth4webapi/build/index.js
2
+ var USER_AGENT;
3
+ if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
4
+ const NAME = "oauth4webapi";
5
+ const VERSION = "v2.10.4";
6
+ USER_AGENT = `${NAME}/${VERSION}`;
7
+ }
8
+ function looseInstanceOf(input, expected) {
9
+ if (input == null) {
10
+ return false;
11
+ }
12
+ try {
13
+ return input instanceof expected || Object.getPrototypeOf(input)[Symbol.toStringTag] === expected.prototype[Symbol.toStringTag];
14
+ } catch {
15
+ return false;
16
+ }
17
+ }
18
+ var clockSkew = Symbol();
19
+ var clockTolerance = Symbol();
20
+ var customFetch = Symbol();
21
+ var useMtlsAlias = Symbol();
22
+ var encoder = new TextEncoder();
23
+ var decoder = new TextDecoder();
24
+ function buf(input) {
25
+ if (typeof input === "string") {
26
+ return encoder.encode(input);
27
+ }
28
+ return decoder.decode(input);
29
+ }
30
+ var CHUNK_SIZE = 32768;
31
+ function encodeBase64Url(input) {
32
+ if (input instanceof ArrayBuffer) {
33
+ input = new Uint8Array(input);
34
+ }
35
+ const arr = [];
36
+ for (let i = 0; i < input.byteLength; i += CHUNK_SIZE) {
37
+ arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
38
+ }
39
+ return btoa(arr.join("")).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
40
+ }
41
+ function decodeBase64Url(input) {
42
+ try {
43
+ const binary = atob(input.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, ""));
44
+ const bytes = new Uint8Array(binary.length);
45
+ for (let i = 0; i < binary.length; i++) {
46
+ bytes[i] = binary.charCodeAt(i);
47
+ }
48
+ return bytes;
49
+ } catch (cause) {
50
+ throw new OPE("The input to be decoded is not correctly encoded.", { cause });
51
+ }
52
+ }
53
+ function b64u(input) {
54
+ if (typeof input === "string") {
55
+ return decodeBase64Url(input);
56
+ }
57
+ return encodeBase64Url(input);
58
+ }
59
+ var LRU = class {
60
+ constructor(maxSize) {
61
+ this.cache = /* @__PURE__ */ new Map();
62
+ this._cache = /* @__PURE__ */ new Map();
63
+ this.maxSize = maxSize;
64
+ }
65
+ get(key) {
66
+ let v = this.cache.get(key);
67
+ if (v) {
68
+ return v;
69
+ }
70
+ if (v = this._cache.get(key)) {
71
+ this.update(key, v);
72
+ return v;
73
+ }
74
+ return void 0;
75
+ }
76
+ has(key) {
77
+ return this.cache.has(key) || this._cache.has(key);
78
+ }
79
+ set(key, value) {
80
+ if (this.cache.has(key)) {
81
+ this.cache.set(key, value);
82
+ } else {
83
+ this.update(key, value);
84
+ }
85
+ return this;
86
+ }
87
+ delete(key) {
88
+ if (this.cache.has(key)) {
89
+ return this.cache.delete(key);
90
+ }
91
+ if (this._cache.has(key)) {
92
+ return this._cache.delete(key);
93
+ }
94
+ return false;
95
+ }
96
+ update(key, value) {
97
+ this.cache.set(key, value);
98
+ if (this.cache.size >= this.maxSize) {
99
+ this._cache = this.cache;
100
+ this.cache = /* @__PURE__ */ new Map();
101
+ }
102
+ }
103
+ };
104
+ var UnsupportedOperationError = class extends Error {
105
+ constructor(message) {
106
+ super(message ?? "operation not supported");
107
+ this.name = this.constructor.name;
108
+ Error.captureStackTrace?.(this, this.constructor);
109
+ }
110
+ };
111
+ var OperationProcessingError = class extends Error {
112
+ constructor(message, options) {
113
+ super(message, options);
114
+ this.name = this.constructor.name;
115
+ Error.captureStackTrace?.(this, this.constructor);
116
+ }
117
+ };
118
+ var OPE = OperationProcessingError;
119
+ var dpopNonces = new LRU(100);
120
+ function isCryptoKey(key) {
121
+ return key instanceof CryptoKey;
122
+ }
123
+ function isPrivateKey(key) {
124
+ return isCryptoKey(key) && key.type === "private";
125
+ }
126
+ function isPublicKey(key) {
127
+ return isCryptoKey(key) && key.type === "public";
128
+ }
129
+ function processDpopNonce(response) {
130
+ try {
131
+ const nonce = response.headers.get("dpop-nonce");
132
+ if (nonce) {
133
+ dpopNonces.set(new URL(response.url).origin, nonce);
134
+ }
135
+ } catch {
136
+ }
137
+ return response;
138
+ }
139
+ function isJsonObject(input) {
140
+ if (input === null || typeof input !== "object" || Array.isArray(input)) {
141
+ return false;
142
+ }
143
+ return true;
144
+ }
145
+ function prepareHeaders(input) {
146
+ if (looseInstanceOf(input, Headers)) {
147
+ input = Object.fromEntries(input.entries());
148
+ }
149
+ const headers = new Headers(input);
150
+ if (USER_AGENT && !headers.has("user-agent")) {
151
+ headers.set("user-agent", USER_AGENT);
152
+ }
153
+ if (headers.has("authorization")) {
154
+ throw new TypeError('"options.headers" must not include the "authorization" header name');
155
+ }
156
+ if (headers.has("dpop")) {
157
+ throw new TypeError('"options.headers" must not include the "dpop" header name');
158
+ }
159
+ return headers;
160
+ }
161
+ function signal(value) {
162
+ if (typeof value === "function") {
163
+ value = value();
164
+ }
165
+ if (!(value instanceof AbortSignal)) {
166
+ throw new TypeError('"options.signal" must return or be an instance of AbortSignal');
167
+ }
168
+ return value;
169
+ }
170
+ function validateString(input) {
171
+ return typeof input === "string" && input.length !== 0;
172
+ }
173
+ function randomBytes() {
174
+ return b64u(crypto.getRandomValues(new Uint8Array(32)));
175
+ }
176
+ function getKeyAndKid(input) {
177
+ if (input instanceof CryptoKey) {
178
+ return { key: input };
179
+ }
180
+ if (!(input?.key instanceof CryptoKey)) {
181
+ return {};
182
+ }
183
+ if (input.kid !== void 0 && !validateString(input.kid)) {
184
+ throw new TypeError('"kid" must be a non-empty string');
185
+ }
186
+ return { key: input.key, kid: input.kid };
187
+ }
188
+ function formUrlEncode(token) {
189
+ return encodeURIComponent(token).replace(/%20/g, "+");
190
+ }
191
+ function clientSecretBasic(clientId, clientSecret) {
192
+ const username = formUrlEncode(clientId);
193
+ const password = formUrlEncode(clientSecret);
194
+ const credentials = btoa(`${username}:${password}`);
195
+ return `Basic ${credentials}`;
196
+ }
197
+ function psAlg(key) {
198
+ switch (key.algorithm.hash.name) {
199
+ case "SHA-256":
200
+ return "PS256";
201
+ case "SHA-384":
202
+ return "PS384";
203
+ case "SHA-512":
204
+ return "PS512";
205
+ default:
206
+ throw new UnsupportedOperationError("unsupported RsaHashedKeyAlgorithm hash name");
207
+ }
208
+ }
209
+ function rsAlg(key) {
210
+ switch (key.algorithm.hash.name) {
211
+ case "SHA-256":
212
+ return "RS256";
213
+ case "SHA-384":
214
+ return "RS384";
215
+ case "SHA-512":
216
+ return "RS512";
217
+ default:
218
+ throw new UnsupportedOperationError("unsupported RsaHashedKeyAlgorithm hash name");
219
+ }
220
+ }
221
+ function esAlg(key) {
222
+ switch (key.algorithm.namedCurve) {
223
+ case "P-256":
224
+ return "ES256";
225
+ case "P-384":
226
+ return "ES384";
227
+ case "P-521":
228
+ return "ES512";
229
+ default:
230
+ throw new UnsupportedOperationError("unsupported EcKeyAlgorithm namedCurve");
231
+ }
232
+ }
233
+ function keyToJws(key) {
234
+ switch (key.algorithm.name) {
235
+ case "RSA-PSS":
236
+ return psAlg(key);
237
+ case "RSASSA-PKCS1-v1_5":
238
+ return rsAlg(key);
239
+ case "ECDSA":
240
+ return esAlg(key);
241
+ case "Ed25519":
242
+ case "Ed448":
243
+ return "EdDSA";
244
+ default:
245
+ throw new UnsupportedOperationError("unsupported CryptoKey algorithm name");
246
+ }
247
+ }
248
+ function getClockSkew(client) {
249
+ const skew = client?.[clockSkew];
250
+ return typeof skew === "number" && Number.isFinite(skew) ? skew : 0;
251
+ }
252
+ function getClockTolerance(client) {
253
+ const tolerance = client?.[clockTolerance];
254
+ return typeof tolerance === "number" && Number.isFinite(tolerance) && Math.sign(tolerance) !== -1 ? tolerance : 30;
255
+ }
256
+ function epochTime() {
257
+ return Math.floor(Date.now() / 1e3);
258
+ }
259
+ function clientAssertion(as, client) {
260
+ const now = epochTime() + getClockSkew(client);
261
+ return {
262
+ jti: randomBytes(),
263
+ aud: [as.issuer, as.token_endpoint],
264
+ exp: now + 60,
265
+ iat: now,
266
+ nbf: now,
267
+ iss: client.client_id,
268
+ sub: client.client_id
269
+ };
270
+ }
271
+ async function privateKeyJwt(as, client, key, kid) {
272
+ return jwt({
273
+ alg: keyToJws(key),
274
+ kid
275
+ }, clientAssertion(as, client), key);
276
+ }
277
+ function assertAs(as) {
278
+ if (typeof as !== "object" || as === null) {
279
+ throw new TypeError('"as" must be an object');
280
+ }
281
+ if (!validateString(as.issuer)) {
282
+ throw new TypeError('"as.issuer" property must be a non-empty string');
283
+ }
284
+ return true;
285
+ }
286
+ function assertClient(client) {
287
+ if (typeof client !== "object" || client === null) {
288
+ throw new TypeError('"client" must be an object');
289
+ }
290
+ if (!validateString(client.client_id)) {
291
+ throw new TypeError('"client.client_id" property must be a non-empty string');
292
+ }
293
+ return true;
294
+ }
295
+ function assertClientSecret(clientSecret) {
296
+ if (!validateString(clientSecret)) {
297
+ throw new TypeError('"client.client_secret" property must be a non-empty string');
298
+ }
299
+ return clientSecret;
300
+ }
301
+ function assertNoClientPrivateKey(clientAuthMethod, clientPrivateKey) {
302
+ if (clientPrivateKey !== void 0) {
303
+ throw new TypeError(`"options.clientPrivateKey" property must not be provided when ${clientAuthMethod} client authentication method is used.`);
304
+ }
305
+ }
306
+ function assertNoClientSecret(clientAuthMethod, clientSecret) {
307
+ if (clientSecret !== void 0) {
308
+ throw new TypeError(`"client.client_secret" property must not be provided when ${clientAuthMethod} client authentication method is used.`);
309
+ }
310
+ }
311
+ async function clientAuthentication(as, client, body, headers, clientPrivateKey) {
312
+ body.delete("client_secret");
313
+ body.delete("client_assertion_type");
314
+ body.delete("client_assertion");
315
+ switch (client.token_endpoint_auth_method) {
316
+ case void 0:
317
+ case "client_secret_basic": {
318
+ assertNoClientPrivateKey("client_secret_basic", clientPrivateKey);
319
+ headers.set("authorization", clientSecretBasic(client.client_id, assertClientSecret(client.client_secret)));
320
+ break;
321
+ }
322
+ case "client_secret_post": {
323
+ assertNoClientPrivateKey("client_secret_post", clientPrivateKey);
324
+ body.set("client_id", client.client_id);
325
+ body.set("client_secret", assertClientSecret(client.client_secret));
326
+ break;
327
+ }
328
+ case "private_key_jwt": {
329
+ assertNoClientSecret("private_key_jwt", client.client_secret);
330
+ if (clientPrivateKey === void 0) {
331
+ throw new TypeError('"options.clientPrivateKey" must be provided when "client.token_endpoint_auth_method" is "private_key_jwt"');
332
+ }
333
+ const { key, kid } = getKeyAndKid(clientPrivateKey);
334
+ if (!isPrivateKey(key)) {
335
+ throw new TypeError('"options.clientPrivateKey.key" must be a private CryptoKey');
336
+ }
337
+ body.set("client_id", client.client_id);
338
+ body.set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer");
339
+ body.set("client_assertion", await privateKeyJwt(as, client, key, kid));
340
+ break;
341
+ }
342
+ case "tls_client_auth":
343
+ case "self_signed_tls_client_auth":
344
+ case "none": {
345
+ assertNoClientSecret(client.token_endpoint_auth_method, client.client_secret);
346
+ assertNoClientPrivateKey(client.token_endpoint_auth_method, clientPrivateKey);
347
+ body.set("client_id", client.client_id);
348
+ break;
349
+ }
350
+ default:
351
+ throw new UnsupportedOperationError("unsupported client token_endpoint_auth_method");
352
+ }
353
+ }
354
+ async function jwt(header, claimsSet, key) {
355
+ if (!key.usages.includes("sign")) {
356
+ throw new TypeError('CryptoKey instances used for signing assertions must include "sign" in their "usages"');
357
+ }
358
+ const input = `${b64u(buf(JSON.stringify(header)))}.${b64u(buf(JSON.stringify(claimsSet)))}`;
359
+ const signature = b64u(await crypto.subtle.sign(keyToSubtle(key), key, buf(input)));
360
+ return `${input}.${signature}`;
361
+ }
362
+ async function dpopProofJwt(headers, options, url, htm, clockSkew2, accessToken) {
363
+ const { privateKey, publicKey, nonce = dpopNonces.get(url.origin) } = options;
364
+ if (!isPrivateKey(privateKey)) {
365
+ throw new TypeError('"DPoP.privateKey" must be a private CryptoKey');
366
+ }
367
+ if (!isPublicKey(publicKey)) {
368
+ throw new TypeError('"DPoP.publicKey" must be a public CryptoKey');
369
+ }
370
+ if (nonce !== void 0 && !validateString(nonce)) {
371
+ throw new TypeError('"DPoP.nonce" must be a non-empty string or undefined');
372
+ }
373
+ if (!publicKey.extractable) {
374
+ throw new TypeError('"DPoP.publicKey.extractable" must be true');
375
+ }
376
+ const now = epochTime() + clockSkew2;
377
+ const proof = await jwt({
378
+ alg: keyToJws(privateKey),
379
+ typ: "dpop+jwt",
380
+ jwk: await publicJwk(publicKey)
381
+ }, {
382
+ iat: now,
383
+ jti: randomBytes(),
384
+ htm,
385
+ nonce,
386
+ htu: `${url.origin}${url.pathname}`,
387
+ ath: accessToken ? b64u(await crypto.subtle.digest("SHA-256", buf(accessToken))) : void 0
388
+ }, privateKey);
389
+ headers.set("dpop", proof);
390
+ }
391
+ var jwkCache;
392
+ async function getSetPublicJwkCache(key) {
393
+ const { kty, e, n, x, y, crv } = await crypto.subtle.exportKey("jwk", key);
394
+ const jwk = { kty, e, n, x, y, crv };
395
+ jwkCache.set(key, jwk);
396
+ return jwk;
397
+ }
398
+ async function publicJwk(key) {
399
+ jwkCache || (jwkCache = /* @__PURE__ */ new WeakMap());
400
+ return jwkCache.get(key) || getSetPublicJwkCache(key);
401
+ }
402
+ function validateEndpoint(value, endpoint, options) {
403
+ if (typeof value !== "string") {
404
+ if (options?.[useMtlsAlias]) {
405
+ throw new TypeError(`"as.mtls_endpoint_aliases.${endpoint}" must be a string`);
406
+ }
407
+ throw new TypeError(`"as.${endpoint}" must be a string`);
408
+ }
409
+ return new URL(value);
410
+ }
411
+ function resolveEndpoint(as, endpoint, options) {
412
+ if (options?.[useMtlsAlias] && as.mtls_endpoint_aliases && endpoint in as.mtls_endpoint_aliases) {
413
+ return validateEndpoint(as.mtls_endpoint_aliases[endpoint], endpoint, options);
414
+ }
415
+ return validateEndpoint(as[endpoint], endpoint);
416
+ }
417
+ function isOAuth2Error(input) {
418
+ const value = input;
419
+ if (typeof value !== "object" || Array.isArray(value) || value === null) {
420
+ return false;
421
+ }
422
+ return value.error !== void 0;
423
+ }
424
+ var skipSubjectCheck = Symbol();
425
+ async function authenticatedRequest(as, client, method, url, body, headers, options) {
426
+ await clientAuthentication(as, client, body, headers, options?.clientPrivateKey);
427
+ headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
428
+ return (options?.[customFetch] || fetch)(url.href, {
429
+ body,
430
+ headers: Object.fromEntries(headers.entries()),
431
+ method,
432
+ redirect: "manual",
433
+ signal: options?.signal ? signal(options.signal) : null
434
+ }).then(processDpopNonce);
435
+ }
436
+ async function tokenEndpointRequest(as, client, grantType, parameters, options) {
437
+ const url = resolveEndpoint(as, "token_endpoint", options);
438
+ parameters.set("grant_type", grantType);
439
+ const headers = prepareHeaders(options?.headers);
440
+ headers.set("accept", "application/json");
441
+ if (options?.DPoP !== void 0) {
442
+ await dpopProofJwt(headers, options.DPoP, url, "POST", getClockSkew(client));
443
+ }
444
+ return authenticatedRequest(as, client, "POST", url, parameters, headers, options);
445
+ }
446
+ async function refreshTokenGrantRequest(as, client, refreshToken, options) {
447
+ assertAs(as);
448
+ assertClient(client);
449
+ if (!validateString(refreshToken)) {
450
+ throw new TypeError('"refreshToken" must be a non-empty string');
451
+ }
452
+ const parameters = new URLSearchParams(options?.additionalParameters);
453
+ parameters.set("refresh_token", refreshToken);
454
+ return tokenEndpointRequest(as, client, "refresh_token", parameters, options);
455
+ }
456
+ var idTokenClaims = /* @__PURE__ */ new WeakMap();
457
+ async function processGenericAccessTokenResponse(as, client, response, ignoreIdToken = false, ignoreRefreshToken = false) {
458
+ assertAs(as);
459
+ assertClient(client);
460
+ if (!looseInstanceOf(response, Response)) {
461
+ throw new TypeError('"response" must be an instance of Response');
462
+ }
463
+ if (response.status !== 200) {
464
+ let err;
465
+ if (err = await handleOAuthBodyError(response)) {
466
+ return err;
467
+ }
468
+ throw new OPE('"response" is not a conform Token Endpoint response');
469
+ }
470
+ assertReadableResponse(response);
471
+ let json;
472
+ try {
473
+ json = await response.json();
474
+ } catch (cause) {
475
+ throw new OPE('failed to parse "response" body as JSON', { cause });
476
+ }
477
+ if (!isJsonObject(json)) {
478
+ throw new OPE('"response" body must be a top level object');
479
+ }
480
+ if (!validateString(json.access_token)) {
481
+ throw new OPE('"response" body "access_token" property must be a non-empty string');
482
+ }
483
+ if (!validateString(json.token_type)) {
484
+ throw new OPE('"response" body "token_type" property must be a non-empty string');
485
+ }
486
+ json.token_type = json.token_type.toLowerCase();
487
+ if (json.token_type !== "dpop" && json.token_type !== "bearer") {
488
+ throw new UnsupportedOperationError("unsupported `token_type` value");
489
+ }
490
+ if (json.expires_in !== void 0 && (typeof json.expires_in !== "number" || json.expires_in <= 0)) {
491
+ throw new OPE('"response" body "expires_in" property must be a positive number');
492
+ }
493
+ if (!ignoreRefreshToken && json.refresh_token !== void 0 && !validateString(json.refresh_token)) {
494
+ throw new OPE('"response" body "refresh_token" property must be a non-empty string');
495
+ }
496
+ if (json.scope !== void 0 && typeof json.scope !== "string") {
497
+ throw new OPE('"response" body "scope" property must be a string');
498
+ }
499
+ if (!ignoreIdToken) {
500
+ if (json.id_token !== void 0 && !validateString(json.id_token)) {
501
+ throw new OPE('"response" body "id_token" property must be a non-empty string');
502
+ }
503
+ if (json.id_token) {
504
+ const { claims } = await validateJwt(json.id_token, checkSigningAlgorithm.bind(void 0, client.id_token_signed_response_alg, as.id_token_signing_alg_values_supported), noSignatureCheck, getClockSkew(client), getClockTolerance(client)).then(validatePresence.bind(void 0, ["aud", "exp", "iat", "iss", "sub"])).then(validateIssuer.bind(void 0, as.issuer)).then(validateAudience.bind(void 0, client.client_id));
505
+ if (Array.isArray(claims.aud) && claims.aud.length !== 1 && claims.azp !== client.client_id) {
506
+ throw new OPE('unexpected ID Token "azp" (authorized party) claim value');
507
+ }
508
+ if (client.require_auth_time && typeof claims.auth_time !== "number") {
509
+ throw new OPE('unexpected ID Token "auth_time" (authentication time) claim value');
510
+ }
511
+ idTokenClaims.set(json, claims);
512
+ }
513
+ }
514
+ return json;
515
+ }
516
+ async function processRefreshTokenResponse(as, client, response) {
517
+ return processGenericAccessTokenResponse(as, client, response);
518
+ }
519
+ function validateAudience(expected, result) {
520
+ if (Array.isArray(result.claims.aud)) {
521
+ if (!result.claims.aud.includes(expected)) {
522
+ throw new OPE('unexpected JWT "aud" (audience) claim value');
523
+ }
524
+ } else if (result.claims.aud !== expected) {
525
+ throw new OPE('unexpected JWT "aud" (audience) claim value');
526
+ }
527
+ return result;
528
+ }
529
+ function validateIssuer(expected, result) {
530
+ if (result.claims.iss !== expected) {
531
+ throw new OPE('unexpected JWT "iss" (issuer) claim value');
532
+ }
533
+ return result;
534
+ }
535
+ var branded = /* @__PURE__ */ new WeakSet();
536
+ function brand(searchParams) {
537
+ branded.add(searchParams);
538
+ return searchParams;
539
+ }
540
+ async function authorizationCodeGrantRequest(as, client, callbackParameters, redirectUri, codeVerifier, options) {
541
+ assertAs(as);
542
+ assertClient(client);
543
+ if (!branded.has(callbackParameters)) {
544
+ throw new TypeError('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()');
545
+ }
546
+ if (!validateString(redirectUri)) {
547
+ throw new TypeError('"redirectUri" must be a non-empty string');
548
+ }
549
+ if (!validateString(codeVerifier)) {
550
+ throw new TypeError('"codeVerifier" must be a non-empty string');
551
+ }
552
+ const code = getURLSearchParameter(callbackParameters, "code");
553
+ if (!code) {
554
+ throw new OPE('no authorization code in "callbackParameters"');
555
+ }
556
+ const parameters = new URLSearchParams(options?.additionalParameters);
557
+ parameters.set("redirect_uri", redirectUri);
558
+ parameters.set("code_verifier", codeVerifier);
559
+ parameters.set("code", code);
560
+ return tokenEndpointRequest(as, client, "authorization_code", parameters, options);
561
+ }
562
+ var jwtClaimNames = {
563
+ aud: "audience",
564
+ c_hash: "code hash",
565
+ client_id: "client id",
566
+ exp: "expiration time",
567
+ iat: "issued at",
568
+ iss: "issuer",
569
+ jti: "jwt id",
570
+ nonce: "nonce",
571
+ s_hash: "state hash",
572
+ sub: "subject",
573
+ ath: "access token hash",
574
+ htm: "http method",
575
+ htu: "http uri",
576
+ cnf: "confirmation"
577
+ };
578
+ function validatePresence(required, result) {
579
+ for (const claim of required) {
580
+ if (result.claims[claim] === void 0) {
581
+ throw new OPE(`JWT "${claim}" (${jwtClaimNames[claim]}) claim missing`);
582
+ }
583
+ }
584
+ return result;
585
+ }
586
+ var expectNoNonce = Symbol();
587
+ var skipAuthTimeCheck = Symbol();
588
+ async function processAuthorizationCodeOAuth2Response(as, client, response) {
589
+ const result = await processGenericAccessTokenResponse(as, client, response, true);
590
+ if (isOAuth2Error(result)) {
591
+ return result;
592
+ }
593
+ if (result.id_token !== void 0) {
594
+ if (typeof result.id_token === "string" && result.id_token.length) {
595
+ throw new OPE("Unexpected ID Token returned, use processAuthorizationCodeOpenIDResponse() for OpenID Connect callback processing");
596
+ }
597
+ delete result.id_token;
598
+ }
599
+ return result;
600
+ }
601
+ function assertReadableResponse(response) {
602
+ if (response.bodyUsed) {
603
+ throw new TypeError('"response" body has been used already');
604
+ }
605
+ }
606
+ async function handleOAuthBodyError(response) {
607
+ if (response.status > 399 && response.status < 500) {
608
+ assertReadableResponse(response);
609
+ try {
610
+ const json = await response.json();
611
+ if (isJsonObject(json) && typeof json.error === "string" && json.error.length) {
612
+ if (json.error_description !== void 0 && typeof json.error_description !== "string") {
613
+ delete json.error_description;
614
+ }
615
+ if (json.error_uri !== void 0 && typeof json.error_uri !== "string") {
616
+ delete json.error_uri;
617
+ }
618
+ if (json.algs !== void 0 && typeof json.algs !== "string") {
619
+ delete json.algs;
620
+ }
621
+ if (json.scope !== void 0 && typeof json.scope !== "string") {
622
+ delete json.scope;
623
+ }
624
+ return json;
625
+ }
626
+ } catch {
627
+ }
628
+ }
629
+ return void 0;
630
+ }
631
+ function checkRsaKeyAlgorithm(algorithm) {
632
+ if (typeof algorithm.modulusLength !== "number" || algorithm.modulusLength < 2048) {
633
+ throw new OPE(`${algorithm.name} modulusLength must be at least 2048 bits`);
634
+ }
635
+ }
636
+ function ecdsaHashName(namedCurve) {
637
+ switch (namedCurve) {
638
+ case "P-256":
639
+ return "SHA-256";
640
+ case "P-384":
641
+ return "SHA-384";
642
+ case "P-521":
643
+ return "SHA-512";
644
+ default:
645
+ throw new UnsupportedOperationError();
646
+ }
647
+ }
648
+ function keyToSubtle(key) {
649
+ switch (key.algorithm.name) {
650
+ case "ECDSA":
651
+ return {
652
+ name: key.algorithm.name,
653
+ hash: ecdsaHashName(key.algorithm.namedCurve)
654
+ };
655
+ case "RSA-PSS": {
656
+ checkRsaKeyAlgorithm(key.algorithm);
657
+ switch (key.algorithm.hash.name) {
658
+ case "SHA-256":
659
+ case "SHA-384":
660
+ case "SHA-512":
661
+ return {
662
+ name: key.algorithm.name,
663
+ saltLength: parseInt(key.algorithm.hash.name.slice(-3), 10) >> 3
664
+ };
665
+ default:
666
+ throw new UnsupportedOperationError();
667
+ }
668
+ }
669
+ case "RSASSA-PKCS1-v1_5":
670
+ checkRsaKeyAlgorithm(key.algorithm);
671
+ return key.algorithm.name;
672
+ case "Ed448":
673
+ case "Ed25519":
674
+ return key.algorithm.name;
675
+ }
676
+ throw new UnsupportedOperationError();
677
+ }
678
+ var noSignatureCheck = Symbol();
679
+ async function validateJwt(jws, checkAlg, getKey, clockSkew2, clockTolerance2) {
680
+ const { 0: protectedHeader, 1: payload, 2: encodedSignature, length } = jws.split(".");
681
+ if (length === 5) {
682
+ throw new UnsupportedOperationError("JWE structure JWTs are not supported");
683
+ }
684
+ if (length !== 3) {
685
+ throw new OPE("Invalid JWT");
686
+ }
687
+ let header;
688
+ try {
689
+ header = JSON.parse(buf(b64u(protectedHeader)));
690
+ } catch (cause) {
691
+ throw new OPE("failed to parse JWT Header body as base64url encoded JSON", { cause });
692
+ }
693
+ if (!isJsonObject(header)) {
694
+ throw new OPE("JWT Header must be a top level object");
695
+ }
696
+ checkAlg(header);
697
+ if (header.crit !== void 0) {
698
+ throw new OPE('unexpected JWT "crit" header parameter');
699
+ }
700
+ const signature = b64u(encodedSignature);
701
+ let key;
702
+ if (getKey !== noSignatureCheck) {
703
+ key = await getKey(header);
704
+ const input = `${protectedHeader}.${payload}`;
705
+ const verified = await crypto.subtle.verify(keyToSubtle(key), key, signature, buf(input));
706
+ if (!verified) {
707
+ throw new OPE("JWT signature verification failed");
708
+ }
709
+ }
710
+ let claims;
711
+ try {
712
+ claims = JSON.parse(buf(b64u(payload)));
713
+ } catch (cause) {
714
+ throw new OPE("failed to parse JWT Payload body as base64url encoded JSON", { cause });
715
+ }
716
+ if (!isJsonObject(claims)) {
717
+ throw new OPE("JWT Payload must be a top level object");
718
+ }
719
+ const now = epochTime() + clockSkew2;
720
+ if (claims.exp !== void 0) {
721
+ if (typeof claims.exp !== "number") {
722
+ throw new OPE('unexpected JWT "exp" (expiration time) claim type');
723
+ }
724
+ if (claims.exp <= now - clockTolerance2) {
725
+ throw new OPE('unexpected JWT "exp" (expiration time) claim value, timestamp is <= now()');
726
+ }
727
+ }
728
+ if (claims.iat !== void 0) {
729
+ if (typeof claims.iat !== "number") {
730
+ throw new OPE('unexpected JWT "iat" (issued at) claim type');
731
+ }
732
+ }
733
+ if (claims.iss !== void 0) {
734
+ if (typeof claims.iss !== "string") {
735
+ throw new OPE('unexpected JWT "iss" (issuer) claim type');
736
+ }
737
+ }
738
+ if (claims.nbf !== void 0) {
739
+ if (typeof claims.nbf !== "number") {
740
+ throw new OPE('unexpected JWT "nbf" (not before) claim type');
741
+ }
742
+ if (claims.nbf > now + clockTolerance2) {
743
+ throw new OPE('unexpected JWT "nbf" (not before) claim value, timestamp is > now()');
744
+ }
745
+ }
746
+ if (claims.aud !== void 0) {
747
+ if (typeof claims.aud !== "string" && !Array.isArray(claims.aud)) {
748
+ throw new OPE('unexpected JWT "aud" (audience) claim type');
749
+ }
750
+ }
751
+ return { header, claims, signature, key };
752
+ }
753
+ function checkSigningAlgorithm(client, issuer, header) {
754
+ if (client !== void 0) {
755
+ if (header.alg !== client) {
756
+ throw new OPE('unexpected JWT "alg" header parameter');
757
+ }
758
+ return;
759
+ }
760
+ if (Array.isArray(issuer)) {
761
+ if (!issuer.includes(header.alg)) {
762
+ throw new OPE('unexpected JWT "alg" header parameter');
763
+ }
764
+ return;
765
+ }
766
+ if (header.alg !== "RS256") {
767
+ throw new OPE('unexpected JWT "alg" header parameter');
768
+ }
769
+ }
770
+ function getURLSearchParameter(parameters, name) {
771
+ const { 0: value, length } = parameters.getAll(name);
772
+ if (length > 1) {
773
+ throw new OPE(`"${name}" parameter must be provided only once`);
774
+ }
775
+ return value;
776
+ }
777
+ var skipStateCheck = Symbol();
778
+ var expectNoState = Symbol();
779
+ function validateAuthResponse(as, client, parameters, expectedState) {
780
+ assertAs(as);
781
+ assertClient(client);
782
+ if (parameters instanceof URL) {
783
+ parameters = parameters.searchParams;
784
+ }
785
+ if (!(parameters instanceof URLSearchParams)) {
786
+ throw new TypeError('"parameters" must be an instance of URLSearchParams, or URL');
787
+ }
788
+ if (getURLSearchParameter(parameters, "response")) {
789
+ throw new OPE('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()');
790
+ }
791
+ const iss = getURLSearchParameter(parameters, "iss");
792
+ const state = getURLSearchParameter(parameters, "state");
793
+ if (!iss && as.authorization_response_iss_parameter_supported) {
794
+ throw new OPE('response parameter "iss" (issuer) missing');
795
+ }
796
+ if (iss && iss !== as.issuer) {
797
+ throw new OPE('unexpected "iss" (issuer) response parameter value');
798
+ }
799
+ switch (expectedState) {
800
+ case void 0:
801
+ case expectNoState:
802
+ if (state !== void 0) {
803
+ throw new OPE('unexpected "state" response parameter encountered');
804
+ }
805
+ break;
806
+ case skipStateCheck:
807
+ break;
808
+ default:
809
+ if (!validateString(expectedState)) {
810
+ throw new OPE('"expectedState" must be a non-empty string');
811
+ }
812
+ if (state === void 0) {
813
+ throw new OPE('response parameter "state" missing');
814
+ }
815
+ if (state !== expectedState) {
816
+ throw new OPE('unexpected "state" response parameter value');
817
+ }
818
+ }
819
+ const error = getURLSearchParameter(parameters, "error");
820
+ if (error) {
821
+ return {
822
+ error,
823
+ error_description: getURLSearchParameter(parameters, "error_description"),
824
+ error_uri: getURLSearchParameter(parameters, "error_uri")
825
+ };
826
+ }
827
+ const id_token = getURLSearchParameter(parameters, "id_token");
828
+ const token = getURLSearchParameter(parameters, "token");
829
+ if (id_token !== void 0 || token !== void 0) {
830
+ throw new UnsupportedOperationError("implicit and hybrid flows are not supported");
831
+ }
832
+ return brand(new URLSearchParams(parameters));
833
+ }
834
+
835
+ // src/interface/clientInterface.ts
836
+ import { KnownError, KnownErrors } from "../known-errors";
837
+ import { AccessToken, InternalSession } from "../sessions";
838
+ import { generateSecureRandomString } from "../utils/crypto";
839
+ import { StackAssertionError, throwErr } from "../utils/errors";
840
+ import { globalVar } from "../utils/globals";
841
+ import { HTTP_METHODS } from "../utils/http";
842
+ import { filterUndefined, filterUndefinedOrNull } from "../utils/objects";
843
+ import { wait } from "../utils/promises";
844
+ import { Result } from "../utils/results";
845
+ import { deindent } from "../utils/strings";
846
+ var StackClientInterface = class {
847
+ constructor(options) {
848
+ this.options = options;
849
+ }
850
+ get projectId() {
851
+ return this.options.projectId;
852
+ }
853
+ getApiUrl() {
854
+ return this.options.getBaseUrl() + "/api/v1";
855
+ }
856
+ async runNetworkDiagnostics(session, requestType) {
857
+ const tryRequest = async (cb) => {
858
+ try {
859
+ await cb();
860
+ return "OK";
861
+ } catch (e) {
862
+ return `${e}`;
863
+ }
864
+ };
865
+ const cfTrace = await tryRequest(async () => {
866
+ const res = await fetch("https://1.1.1.1/cdn-cgi/trace");
867
+ if (!res.ok) {
868
+ throw new Error(`${res.status} ${res.statusText}: ${await res.text()}`);
869
+ }
870
+ });
871
+ const apiRoot = session !== void 0 && requestType !== void 0 ? await tryRequest(async () => {
872
+ const res = await this.sendClientRequestInner("/", {}, session, requestType);
873
+ if (res.status === "error") {
874
+ throw res.error;
875
+ }
876
+ }) : "Not tested";
877
+ const baseUrlBackend = await tryRequest(async () => {
878
+ const res = await fetch(new URL("/health", this.getApiUrl()));
879
+ if (!res.ok) {
880
+ throw new Error(`${res.status} ${res.statusText}: ${await res.text()}`);
881
+ }
882
+ });
883
+ const prodDashboard = await tryRequest(async () => {
884
+ const res = await fetch("https://app.stack-auth.com/health");
885
+ if (!res.ok) {
886
+ throw new Error(`${res.status} ${res.statusText}: ${await res.text()}`);
887
+ }
888
+ });
889
+ const prodBackend = await tryRequest(async () => {
890
+ const res = await fetch("https://api.stack-auth.com/health");
891
+ if (!res.ok) {
892
+ throw new Error(`${res.status} ${res.statusText}: ${await res.text()}`);
893
+ }
894
+ });
895
+ return {
896
+ "navigator?.onLine": globalVar.navigator?.onLine,
897
+ cfTrace,
898
+ apiRoot,
899
+ baseUrlBackend,
900
+ prodDashboard,
901
+ prodBackend
902
+ };
903
+ }
904
+ async _createNetworkError(cause, session, requestType) {
905
+ return new Error(deindent`
906
+ Stack Auth is unable to connect to the server. Please check your internet connection and try again.
907
+
908
+ If the problem persists, please contact support and provide a screenshot of your entire browser console.
909
+
910
+ ${cause}
911
+
912
+ ${JSON.stringify(await this.runNetworkDiagnostics(session, requestType), null, 2)}
913
+ `, { cause });
914
+ }
915
+ async _networkRetry(cb, session, requestType) {
916
+ const retriedResult = await Result.retry(
917
+ cb,
918
+ 5,
919
+ { exponentialDelayBase: 1e3 }
920
+ );
921
+ if (retriedResult.status === "error") {
922
+ if (globalVar.navigator && !globalVar.navigator.onLine) {
923
+ throw new Error("Failed to send Stack network request. It seems like you are offline, please check your internet connection and try again. This is not an error with Stack Auth. (window.navigator.onLine is falsy)", { cause: retriedResult.error });
924
+ }
925
+ throw await this._createNetworkError(retriedResult.error, session, requestType);
926
+ }
927
+ return retriedResult.data;
928
+ }
929
+ async _networkRetryException(cb, session, requestType) {
930
+ return await this._networkRetry(async () => await Result.fromThrowingAsync(cb), session, requestType);
931
+ }
932
+ async fetchNewAccessToken(refreshToken) {
933
+ if (!("publishableClientKey" in this.options)) {
934
+ throw new Error("Admin session token is currently not supported for fetching new access token. Did you try to log in on a StackApp initiated with the admin session?");
935
+ }
936
+ const as = {
937
+ issuer: this.options.getBaseUrl(),
938
+ algorithm: "oauth2",
939
+ token_endpoint: this.getApiUrl() + "/auth/oauth/token"
940
+ };
941
+ const client = {
942
+ client_id: this.projectId,
943
+ client_secret: this.options.publishableClientKey,
944
+ token_endpoint_auth_method: "client_secret_post"
945
+ };
946
+ const rawResponse = await this._networkRetryException(
947
+ async () => await refreshTokenGrantRequest(
948
+ as,
949
+ client,
950
+ refreshToken.token
951
+ )
952
+ );
953
+ const response = await this._processResponse(rawResponse);
954
+ if (response.status === "error") {
955
+ const error = response.error;
956
+ if (error instanceof KnownErrors.RefreshTokenError) {
957
+ return null;
958
+ }
959
+ throw error;
960
+ }
961
+ if (!response.data.ok) {
962
+ const body = await response.data.text();
963
+ throw new Error(`Failed to send refresh token request: ${response.status} ${body}`);
964
+ }
965
+ const result = await processRefreshTokenResponse(as, client, response.data);
966
+ if (isOAuth2Error(result)) {
967
+ throw new StackAssertionError("OAuth error", { result });
968
+ }
969
+ if (!result.access_token) {
970
+ throw new StackAssertionError("Access token not found in token endpoint response, this is weird!");
971
+ }
972
+ return new AccessToken(result.access_token);
973
+ }
974
+ async sendClientRequest(path, requestOptions, session, requestType = "client") {
975
+ session ??= this.createSession({
976
+ refreshToken: null
977
+ });
978
+ return await this._networkRetry(
979
+ () => this.sendClientRequestInner(path, requestOptions, session, requestType),
980
+ session,
981
+ requestType
982
+ );
983
+ }
984
+ createSession(options) {
985
+ const session = new InternalSession({
986
+ refreshAccessTokenCallback: async (refreshToken) => await this.fetchNewAccessToken(refreshToken),
987
+ ...options
988
+ });
989
+ return session;
990
+ }
991
+ async sendClientRequestAndCatchKnownError(path, requestOptions, tokenStoreOrNull, errorsToCatch) {
992
+ try {
993
+ return Result.ok(await this.sendClientRequest(path, requestOptions, tokenStoreOrNull));
994
+ } catch (e) {
995
+ for (const errorType of errorsToCatch) {
996
+ if (e instanceof errorType) {
997
+ return Result.error(e);
998
+ }
999
+ }
1000
+ throw e;
1001
+ }
1002
+ }
1003
+ async sendClientRequestInner(path, options, session, requestType) {
1004
+ let tokenObj = await session.getOrFetchLikelyValidTokens(2e4);
1005
+ let adminSession = "projectOwnerSession" in this.options ? this.options.projectOwnerSession : null;
1006
+ let adminTokenObj = adminSession ? await adminSession.getOrFetchLikelyValidTokens(2e4) : null;
1007
+ await this.options.prepareRequest?.();
1008
+ let url = this.getApiUrl() + path;
1009
+ if (url.endsWith("/")) {
1010
+ url = url.slice(0, -1);
1011
+ }
1012
+ const params = {
1013
+ /**
1014
+ * This fetch may be cross-origin, in which case we don't want to send cookies of the
1015
+ * original origin (this is the default behavior of `credentials`).
1016
+ *
1017
+ * To help debugging, also omit cookies on same-origin, so we don't accidentally
1018
+ * implement reliance on cookies anywhere.
1019
+ *
1020
+ * However, Cloudflare Workers don't actually support `credentials`, so we only set it
1021
+ * if Cloudflare-exclusive globals are not detected. https://github.com/cloudflare/workers-sdk/issues/2514
1022
+ */
1023
+ ..."WebSocketPair" in globalVar ? {} : {
1024
+ credentials: "omit"
1025
+ },
1026
+ ...options,
1027
+ headers: {
1028
+ "X-Stack-Override-Error-Status": "true",
1029
+ "X-Stack-Project-Id": this.projectId,
1030
+ "X-Stack-Access-Type": requestType,
1031
+ "X-Stack-Client-Version": this.options.clientVersion,
1032
+ ...tokenObj ? {
1033
+ "X-Stack-Access-Token": tokenObj.accessToken.token
1034
+ } : {},
1035
+ ...tokenObj?.refreshToken ? {
1036
+ "X-Stack-Refresh-Token": tokenObj.refreshToken.token
1037
+ } : {},
1038
+ ..."publishableClientKey" in this.options ? {
1039
+ "X-Stack-Publishable-Client-Key": this.options.publishableClientKey
1040
+ } : {},
1041
+ ...adminTokenObj ? {
1042
+ "X-Stack-Admin-Access-Token": adminTokenObj.accessToken.token
1043
+ } : {},
1044
+ /**
1045
+ * Next.js until v15 would cache fetch requests by default, and forcefully disabling it was nearly impossible.
1046
+ *
1047
+ * This header is used to change the cache key and hence always disable it, because we do our own caching.
1048
+ *
1049
+ * When we drop support for Next.js <15, we may be able to remove this header, but please make sure that this is
1050
+ * the case (I haven't actually tested.)
1051
+ */
1052
+ "X-Stack-Random-Nonce": generateSecureRandomString(),
1053
+ ...this.options.extraRequestHeaders,
1054
+ ...options.headers
1055
+ },
1056
+ /**
1057
+ * Cloudflare Workers does not support cache, so don't pass it there
1058
+ */
1059
+ ..."WebSocketPair" in globalVar ? {} : {
1060
+ cache: "no-store"
1061
+ }
1062
+ };
1063
+ let rawRes;
1064
+ try {
1065
+ rawRes = await fetch(url, params);
1066
+ } catch (e) {
1067
+ if (e instanceof TypeError) {
1068
+ if (HTTP_METHODS[params.method ?? "GET"].idempotent) {
1069
+ return Result.error(e);
1070
+ } else {
1071
+ throw await this._createNetworkError(e, session, requestType);
1072
+ }
1073
+ }
1074
+ throw e;
1075
+ }
1076
+ const processedRes = await this._processResponse(rawRes);
1077
+ if (processedRes.status === "error") {
1078
+ if (processedRes.error instanceof KnownErrors.InvalidAccessToken) {
1079
+ if (!tokenObj) {
1080
+ throw new StackAssertionError("Received invalid access token, but session is not logged in", { tokenObj, processedRes });
1081
+ }
1082
+ session.markAccessTokenExpired(tokenObj.accessToken);
1083
+ return Result.error(processedRes.error);
1084
+ }
1085
+ if (adminSession && (processedRes.error instanceof KnownErrors.InvalidAdminAccessToken || processedRes.error instanceof KnownErrors.ApiKeyNotFound)) {
1086
+ if (!adminTokenObj) {
1087
+ throw new StackAssertionError("Received invalid admin access token, but admin session is not logged in", { adminTokenObj, processedRes });
1088
+ }
1089
+ adminSession.markAccessTokenExpired(adminTokenObj.accessToken);
1090
+ return Result.error(processedRes.error);
1091
+ }
1092
+ throw processedRes.error;
1093
+ }
1094
+ const res = Object.assign(processedRes.data, {
1095
+ usedTokens: tokenObj
1096
+ });
1097
+ if (res.ok) {
1098
+ return Result.ok(res);
1099
+ } else if (res.status === 429) {
1100
+ const retryAfter = res.headers.get("Retry-After");
1101
+ if (retryAfter !== null) {
1102
+ console.log(`Rate limited while sending request to ${url}. Will retry after ${retryAfter} seconds...`);
1103
+ await wait(Number(retryAfter) * 1e3);
1104
+ return Result.error(new Error(`Rate limited, retrying after ${retryAfter} seconds`));
1105
+ }
1106
+ console.log(`Rate limited while sending request to ${url}, no retry-after header received. Retrying...`);
1107
+ return Result.error(new Error("Rate limited, no retry-after header received"));
1108
+ } else {
1109
+ const error = await res.text();
1110
+ const errorObj = new StackAssertionError(`Failed to send request to ${url}: ${res.status} ${error}`, { request: params, res, path });
1111
+ if (res.status === 508 && error.includes("INFINITE_LOOP_DETECTED")) {
1112
+ return Result.error(errorObj);
1113
+ }
1114
+ throw errorObj;
1115
+ }
1116
+ }
1117
+ async _processResponse(rawRes) {
1118
+ let res = rawRes;
1119
+ if (rawRes.headers.has("x-stack-actual-status")) {
1120
+ const actualStatus = Number(rawRes.headers.get("x-stack-actual-status"));
1121
+ res = new Response(rawRes.body, {
1122
+ status: actualStatus,
1123
+ statusText: rawRes.statusText,
1124
+ headers: rawRes.headers
1125
+ });
1126
+ }
1127
+ if (res.headers.has("x-stack-known-error")) {
1128
+ const errorJson = await res.json();
1129
+ if (res.headers.get("x-stack-known-error") !== errorJson.code) {
1130
+ throw new StackAssertionError("Mismatch between x-stack-known-error header and error code in body; the server's response is invalid");
1131
+ }
1132
+ const error = KnownError.fromJson(errorJson);
1133
+ return Result.error(error);
1134
+ }
1135
+ return Result.ok(res);
1136
+ }
1137
+ async checkFeatureSupport(options) {
1138
+ const res = await this.sendClientRequest("/check-feature-support", {
1139
+ method: "POST",
1140
+ headers: {
1141
+ "Content-Type": "application/json"
1142
+ },
1143
+ body: JSON.stringify(options)
1144
+ }, null);
1145
+ throw new StackAssertionError(await res.text());
1146
+ }
1147
+ async sendForgotPasswordEmail(email, callbackUrl) {
1148
+ const res = await this.sendClientRequestAndCatchKnownError(
1149
+ "/auth/password/send-reset-code",
1150
+ {
1151
+ method: "POST",
1152
+ headers: {
1153
+ "Content-Type": "application/json"
1154
+ },
1155
+ body: JSON.stringify({
1156
+ email,
1157
+ callback_url: callbackUrl
1158
+ })
1159
+ },
1160
+ null,
1161
+ [KnownErrors.UserNotFound]
1162
+ );
1163
+ if (res.status === "error") {
1164
+ return Result.error(res.error);
1165
+ } else {
1166
+ return Result.ok(void 0);
1167
+ }
1168
+ }
1169
+ async sendVerificationEmail(email, callbackUrl, session) {
1170
+ const res = await this.sendClientRequestAndCatchKnownError(
1171
+ "/contact-channels/send-verification-code",
1172
+ {
1173
+ method: "POST",
1174
+ headers: {
1175
+ "Content-Type": "application/json"
1176
+ },
1177
+ body: JSON.stringify({
1178
+ email,
1179
+ callback_url: callbackUrl
1180
+ })
1181
+ },
1182
+ session,
1183
+ [KnownErrors.EmailAlreadyVerified]
1184
+ );
1185
+ if (res.status === "error") {
1186
+ return res.error;
1187
+ }
1188
+ }
1189
+ async sendMagicLinkEmail(email, callbackUrl) {
1190
+ const res = await this.sendClientRequestAndCatchKnownError(
1191
+ "/auth/otp/send-sign-in-code",
1192
+ {
1193
+ method: "POST",
1194
+ headers: {
1195
+ "Content-Type": "application/json"
1196
+ },
1197
+ body: JSON.stringify({
1198
+ email,
1199
+ callback_url: callbackUrl
1200
+ })
1201
+ },
1202
+ null,
1203
+ [KnownErrors.RedirectUrlNotWhitelisted]
1204
+ );
1205
+ if (res.status === "error") {
1206
+ return Result.error(res.error);
1207
+ } else {
1208
+ return Result.ok(await res.data.json());
1209
+ }
1210
+ }
1211
+ async resetPassword(options) {
1212
+ const res = await this.sendClientRequestAndCatchKnownError(
1213
+ "onlyVerifyCode" in options ? "/auth/password/reset/check-code" : "/auth/password/reset",
1214
+ {
1215
+ method: "POST",
1216
+ headers: {
1217
+ "Content-Type": "application/json"
1218
+ },
1219
+ body: JSON.stringify({
1220
+ code: options.code,
1221
+ ..."password" in options ? { password: options.password } : {}
1222
+ })
1223
+ },
1224
+ null,
1225
+ [KnownErrors.VerificationCodeError]
1226
+ );
1227
+ if (res.status === "error") {
1228
+ return Result.error(res.error);
1229
+ } else {
1230
+ return Result.ok(void 0);
1231
+ }
1232
+ }
1233
+ async updatePassword(options, session) {
1234
+ const res = await this.sendClientRequestAndCatchKnownError(
1235
+ "/auth/password/update",
1236
+ {
1237
+ method: "POST",
1238
+ headers: {
1239
+ "Content-Type": "application/json"
1240
+ },
1241
+ body: JSON.stringify({
1242
+ old_password: options.oldPassword,
1243
+ new_password: options.newPassword
1244
+ })
1245
+ },
1246
+ session,
1247
+ [KnownErrors.PasswordConfirmationMismatch, KnownErrors.PasswordRequirementsNotMet]
1248
+ );
1249
+ if (res.status === "error") {
1250
+ return res.error;
1251
+ }
1252
+ }
1253
+ async setPassword(options, session) {
1254
+ const res = await this.sendClientRequestAndCatchKnownError(
1255
+ "/auth/password/set",
1256
+ {
1257
+ method: "POST",
1258
+ headers: {
1259
+ "Content-Type": "application/json"
1260
+ },
1261
+ body: JSON.stringify(options)
1262
+ },
1263
+ session,
1264
+ [KnownErrors.PasswordRequirementsNotMet]
1265
+ );
1266
+ if (res.status === "error") {
1267
+ return res.error;
1268
+ }
1269
+ }
1270
+ async verifyPasswordResetCode(code) {
1271
+ const res = await this.resetPassword({ code, onlyVerifyCode: true });
1272
+ if (res.status === "error") {
1273
+ return Result.error(res.error);
1274
+ } else {
1275
+ return Result.ok(void 0);
1276
+ }
1277
+ }
1278
+ async verifyEmail(code) {
1279
+ const res = await this.sendClientRequestAndCatchKnownError(
1280
+ "/contact-channels/verify",
1281
+ {
1282
+ method: "POST",
1283
+ headers: {
1284
+ "Content-Type": "application/json"
1285
+ },
1286
+ body: JSON.stringify({
1287
+ code
1288
+ })
1289
+ },
1290
+ null,
1291
+ [KnownErrors.VerificationCodeError]
1292
+ );
1293
+ if (res.status === "error") {
1294
+ return Result.error(res.error);
1295
+ } else {
1296
+ return Result.ok(void 0);
1297
+ }
1298
+ }
1299
+ async initiatePasskeyRegistration(options, session) {
1300
+ const res = await this.sendClientRequestAndCatchKnownError(
1301
+ "/auth/passkey/initiate-passkey-registration",
1302
+ {
1303
+ method: "POST",
1304
+ headers: {
1305
+ "Content-Type": "application/json"
1306
+ },
1307
+ body: JSON.stringify(options)
1308
+ },
1309
+ session,
1310
+ []
1311
+ );
1312
+ if (res.status === "error") {
1313
+ return Result.error(res.error);
1314
+ }
1315
+ return Result.ok(await res.data.json());
1316
+ }
1317
+ async registerPasskey(options, session) {
1318
+ const res = await this.sendClientRequestAndCatchKnownError(
1319
+ "/auth/passkey/register",
1320
+ {
1321
+ method: "POST",
1322
+ headers: {
1323
+ "Content-Type": "application/json"
1324
+ },
1325
+ body: JSON.stringify(options)
1326
+ },
1327
+ session,
1328
+ [KnownErrors.PasskeyRegistrationFailed]
1329
+ );
1330
+ if (res.status === "error") {
1331
+ return Result.error(res.error);
1332
+ }
1333
+ return Result.ok(void 0);
1334
+ }
1335
+ async initiatePasskeyAuthentication(options, session) {
1336
+ const res = await this.sendClientRequestAndCatchKnownError(
1337
+ "/auth/passkey/initiate-passkey-authentication",
1338
+ {
1339
+ method: "POST",
1340
+ headers: {
1341
+ "Content-Type": "application/json"
1342
+ },
1343
+ body: JSON.stringify(options)
1344
+ },
1345
+ session,
1346
+ []
1347
+ );
1348
+ if (res.status === "error") {
1349
+ return Result.error(res.error);
1350
+ }
1351
+ return Result.ok(await res.data.json());
1352
+ }
1353
+ async sendTeamInvitation(options) {
1354
+ await this.sendClientRequest(
1355
+ "/team-invitations/send-code",
1356
+ {
1357
+ method: "POST",
1358
+ headers: {
1359
+ "Content-Type": "application/json"
1360
+ },
1361
+ body: JSON.stringify({
1362
+ email: options.email,
1363
+ team_id: options.teamId,
1364
+ callback_url: options.callbackUrl
1365
+ })
1366
+ },
1367
+ options.session
1368
+ );
1369
+ }
1370
+ async acceptTeamInvitation(options) {
1371
+ const res = await this.sendClientRequestAndCatchKnownError(
1372
+ options.type === "check" ? "/team-invitations/accept/check-code" : options.type === "details" ? "/team-invitations/accept/details" : "/team-invitations/accept",
1373
+ {
1374
+ method: "POST",
1375
+ headers: {
1376
+ "Content-Type": "application/json"
1377
+ },
1378
+ body: JSON.stringify({
1379
+ code: options.code
1380
+ })
1381
+ },
1382
+ options.session,
1383
+ [KnownErrors.VerificationCodeError]
1384
+ );
1385
+ if (res.status === "error") {
1386
+ return Result.error(res.error);
1387
+ } else {
1388
+ return Result.ok(await res.data.json());
1389
+ }
1390
+ }
1391
+ async totpMfa(attemptCode, totp, session) {
1392
+ const res = await this.sendClientRequest("/auth/mfa/sign-in", {
1393
+ method: "POST",
1394
+ headers: {
1395
+ "Content-Type": "application/json"
1396
+ },
1397
+ body: JSON.stringify({
1398
+ code: attemptCode,
1399
+ type: "totp",
1400
+ totp
1401
+ })
1402
+ }, session);
1403
+ const result = await res.json();
1404
+ return {
1405
+ accessToken: result.access_token,
1406
+ refreshToken: result.refresh_token,
1407
+ newUser: result.is_new_user
1408
+ };
1409
+ }
1410
+ async signInWithCredential(email, password, session) {
1411
+ const res = await this.sendClientRequestAndCatchKnownError(
1412
+ "/auth/password/sign-in",
1413
+ {
1414
+ method: "POST",
1415
+ headers: {
1416
+ "Content-Type": "application/json"
1417
+ },
1418
+ body: JSON.stringify({
1419
+ email,
1420
+ password
1421
+ })
1422
+ },
1423
+ session,
1424
+ [KnownErrors.EmailPasswordMismatch]
1425
+ );
1426
+ if (res.status === "error") {
1427
+ return Result.error(res.error);
1428
+ }
1429
+ const result = await res.data.json();
1430
+ return Result.ok({
1431
+ accessToken: result.access_token,
1432
+ refreshToken: result.refresh_token
1433
+ });
1434
+ }
1435
+ async signUpWithCredential(email, password, emailVerificationRedirectUrl, session) {
1436
+ const res = await this.sendClientRequestAndCatchKnownError(
1437
+ "/auth/password/sign-up",
1438
+ {
1439
+ headers: {
1440
+ "Content-Type": "application/json"
1441
+ },
1442
+ method: "POST",
1443
+ body: JSON.stringify({
1444
+ email,
1445
+ password,
1446
+ verification_callback_url: emailVerificationRedirectUrl
1447
+ })
1448
+ },
1449
+ session,
1450
+ [KnownErrors.UserWithEmailAlreadyExists, KnownErrors.PasswordRequirementsNotMet]
1451
+ );
1452
+ if (res.status === "error") {
1453
+ return Result.error(res.error);
1454
+ }
1455
+ const result = await res.data.json();
1456
+ return Result.ok({
1457
+ accessToken: result.access_token,
1458
+ refreshToken: result.refresh_token
1459
+ });
1460
+ }
1461
+ async signUpAnonymously(session) {
1462
+ const res = await this.sendClientRequestAndCatchKnownError(
1463
+ "/auth/anonymous/sign-up",
1464
+ {
1465
+ method: "POST"
1466
+ },
1467
+ session,
1468
+ []
1469
+ );
1470
+ if (res.status === "error") {
1471
+ return Result.error(res.error);
1472
+ }
1473
+ const result = await res.data.json();
1474
+ return Result.ok({
1475
+ accessToken: result.access_token,
1476
+ refreshToken: result.refresh_token
1477
+ });
1478
+ }
1479
+ async signInWithMagicLink(code) {
1480
+ const res = await this.sendClientRequestAndCatchKnownError(
1481
+ "/auth/otp/sign-in",
1482
+ {
1483
+ method: "POST",
1484
+ headers: {
1485
+ "Content-Type": "application/json"
1486
+ },
1487
+ body: JSON.stringify({
1488
+ code
1489
+ })
1490
+ },
1491
+ null,
1492
+ [KnownErrors.VerificationCodeError]
1493
+ );
1494
+ if (res.status === "error") {
1495
+ return Result.error(res.error);
1496
+ }
1497
+ const result = await res.data.json();
1498
+ return Result.ok({
1499
+ accessToken: result.access_token,
1500
+ refreshToken: result.refresh_token,
1501
+ newUser: result.is_new_user
1502
+ });
1503
+ }
1504
+ async signInWithPasskey(body) {
1505
+ const res = await this.sendClientRequestAndCatchKnownError(
1506
+ "/auth/passkey/sign-in",
1507
+ {
1508
+ method: "POST",
1509
+ headers: {
1510
+ "Content-Type": "application/json"
1511
+ },
1512
+ body: JSON.stringify(body)
1513
+ },
1514
+ null,
1515
+ [KnownErrors.PasskeyAuthenticationFailed]
1516
+ );
1517
+ if (res.status === "error") {
1518
+ return Result.error(res.error);
1519
+ }
1520
+ const result = await res.data.json();
1521
+ return Result.ok({
1522
+ accessToken: result.access_token,
1523
+ refreshToken: result.refresh_token
1524
+ });
1525
+ }
1526
+ async getOAuthUrl(options) {
1527
+ const updatedRedirectUrl = new URL(options.redirectUrl);
1528
+ for (const key of ["code", "state"]) {
1529
+ if (updatedRedirectUrl.searchParams.has(key)) {
1530
+ console.warn("Redirect URL already contains " + key + " parameter, removing it as it will be overwritten by the OAuth callback");
1531
+ }
1532
+ updatedRedirectUrl.searchParams.delete(key);
1533
+ }
1534
+ if (!("publishableClientKey" in this.options)) {
1535
+ throw new Error("Admin session token is currently not supported for OAuth");
1536
+ }
1537
+ const url = new URL(this.getApiUrl() + "/auth/oauth/authorize/" + options.provider.toLowerCase());
1538
+ url.searchParams.set("client_id", this.projectId);
1539
+ url.searchParams.set("client_secret", this.options.publishableClientKey);
1540
+ url.searchParams.set("redirect_uri", updatedRedirectUrl.toString());
1541
+ url.searchParams.set("scope", "legacy");
1542
+ url.searchParams.set("state", options.state);
1543
+ url.searchParams.set("grant_type", "authorization_code");
1544
+ url.searchParams.set("code_challenge", options.codeChallenge);
1545
+ url.searchParams.set("code_challenge_method", "S256");
1546
+ url.searchParams.set("response_type", "code");
1547
+ url.searchParams.set("type", options.type);
1548
+ url.searchParams.set("error_redirect_url", options.errorRedirectUrl);
1549
+ if (options.afterCallbackRedirectUrl) {
1550
+ url.searchParams.set("after_callback_redirect_url", options.afterCallbackRedirectUrl);
1551
+ }
1552
+ if (options.type === "link") {
1553
+ const tokens = await options.session.getOrFetchLikelyValidTokens(2e4);
1554
+ url.searchParams.set("token", tokens?.accessToken.token || "");
1555
+ if (options.providerScope) {
1556
+ url.searchParams.set("provider_scope", options.providerScope);
1557
+ }
1558
+ }
1559
+ return url.toString();
1560
+ }
1561
+ async callOAuthCallback(options) {
1562
+ if (!("publishableClientKey" in this.options)) {
1563
+ throw new Error("Admin session token is currently not supported for OAuth");
1564
+ }
1565
+ const as = {
1566
+ issuer: this.options.getBaseUrl(),
1567
+ algorithm: "oauth2",
1568
+ token_endpoint: this.getApiUrl() + "/auth/oauth/token"
1569
+ };
1570
+ const client = {
1571
+ client_id: this.projectId,
1572
+ client_secret: this.options.publishableClientKey,
1573
+ token_endpoint_auth_method: "client_secret_post"
1574
+ };
1575
+ const params = await this._networkRetryException(
1576
+ async () => validateAuthResponse(as, client, options.oauthParams, options.state)
1577
+ );
1578
+ if (isOAuth2Error(params)) {
1579
+ throw new StackAssertionError("Error validating outer OAuth response", { params });
1580
+ }
1581
+ const response = await authorizationCodeGrantRequest(
1582
+ as,
1583
+ client,
1584
+ params,
1585
+ options.redirectUri,
1586
+ options.codeVerifier
1587
+ );
1588
+ const result = await processAuthorizationCodeOAuth2Response(as, client, response);
1589
+ if (isOAuth2Error(result)) {
1590
+ if ("code" in result && result.code === "MULTI_FACTOR_AUTHENTICATION_REQUIRED") {
1591
+ throw new KnownErrors.MultiFactorAuthenticationRequired(result.details.attempt_code);
1592
+ }
1593
+ throw new StackAssertionError("Outer OAuth error during authorization code response", { result });
1594
+ }
1595
+ return {
1596
+ newUser: result.is_new_user,
1597
+ afterCallbackRedirectUrl: result.after_callback_redirect_url,
1598
+ accessToken: result.access_token,
1599
+ refreshToken: result.refresh_token ?? throwErr("Refresh token not found in outer OAuth response")
1600
+ };
1601
+ }
1602
+ async signOut(session) {
1603
+ const tokenObj = await session.getOrFetchLikelyValidTokens(2e4);
1604
+ if (tokenObj) {
1605
+ const resOrError = await this.sendClientRequestAndCatchKnownError(
1606
+ "/auth/sessions/current",
1607
+ {
1608
+ method: "DELETE",
1609
+ headers: {
1610
+ "Content-Type": "application/json"
1611
+ },
1612
+ body: JSON.stringify({})
1613
+ },
1614
+ session,
1615
+ [KnownErrors.RefreshTokenError]
1616
+ );
1617
+ if (resOrError.status === "error") {
1618
+ if (resOrError.error instanceof KnownErrors.RefreshTokenError) {
1619
+ } else {
1620
+ throw new StackAssertionError("Unexpected error", { error: resOrError.error });
1621
+ }
1622
+ } else {
1623
+ }
1624
+ }
1625
+ session.markInvalid();
1626
+ }
1627
+ async getClientUserByToken(session) {
1628
+ const responseOrError = await this.sendClientRequestAndCatchKnownError(
1629
+ "/users/me",
1630
+ {},
1631
+ session,
1632
+ [KnownErrors.CannotGetOwnUserWithoutUser]
1633
+ );
1634
+ if (responseOrError.status === "error") {
1635
+ if (responseOrError.error instanceof KnownErrors.CannotGetOwnUserWithoutUser) {
1636
+ return null;
1637
+ } else {
1638
+ throw new StackAssertionError("Unexpected uncaught error", { cause: responseOrError.error });
1639
+ }
1640
+ }
1641
+ const response = responseOrError.data;
1642
+ const user = await response.json();
1643
+ if (!user) throw new StackAssertionError("User endpoint returned null; this should never happen");
1644
+ return user;
1645
+ }
1646
+ async listTeamInvitations(options, session) {
1647
+ const response = await this.sendClientRequest(
1648
+ "/team-invitations?" + new URLSearchParams({ team_id: options.teamId }),
1649
+ {},
1650
+ session
1651
+ );
1652
+ const result = await response.json();
1653
+ return result.items;
1654
+ }
1655
+ async revokeTeamInvitation(invitationId, teamId, session) {
1656
+ await this.sendClientRequest(
1657
+ `/team-invitations/${invitationId}?team_id=${teamId}`,
1658
+ { method: "DELETE" },
1659
+ session
1660
+ );
1661
+ }
1662
+ async listTeamMemberProfiles(options, session) {
1663
+ const response = await this.sendClientRequest(
1664
+ "/team-member-profiles?" + new URLSearchParams(filterUndefined({
1665
+ team_id: options.teamId,
1666
+ user_id: options.userId
1667
+ })),
1668
+ {},
1669
+ session
1670
+ );
1671
+ const result = await response.json();
1672
+ return result.items;
1673
+ }
1674
+ async getTeamMemberProfile(options, session) {
1675
+ const response = await this.sendClientRequest(
1676
+ `/team-member-profiles/${options.teamId}/${options.userId}`,
1677
+ {},
1678
+ session
1679
+ );
1680
+ return await response.json();
1681
+ }
1682
+ async leaveTeam(teamId, session) {
1683
+ await this.sendClientRequest(
1684
+ `/team-memberships/${teamId}/me`,
1685
+ {
1686
+ method: "DELETE",
1687
+ headers: {
1688
+ "content-type": "application/json"
1689
+ },
1690
+ body: JSON.stringify({})
1691
+ },
1692
+ session
1693
+ );
1694
+ }
1695
+ async updateTeamMemberProfile(options, session) {
1696
+ await this.sendClientRequest(
1697
+ `/team-member-profiles/${options.teamId}/${options.userId}`,
1698
+ {
1699
+ method: "PATCH",
1700
+ headers: {
1701
+ "content-type": "application/json"
1702
+ },
1703
+ body: JSON.stringify(options.profile)
1704
+ },
1705
+ session
1706
+ );
1707
+ }
1708
+ async updateTeam(options, session) {
1709
+ await this.sendClientRequest(
1710
+ `/teams/${options.teamId}`,
1711
+ {
1712
+ method: "PATCH",
1713
+ headers: {
1714
+ "content-type": "application/json"
1715
+ },
1716
+ body: JSON.stringify(options.data)
1717
+ },
1718
+ session
1719
+ );
1720
+ }
1721
+ async listCurrentUserTeamPermissions(options, session) {
1722
+ const response = await this.sendClientRequest(
1723
+ `/team-permissions?team_id=${options.teamId}&user_id=me&recursive=${options.recursive}`,
1724
+ {},
1725
+ session
1726
+ );
1727
+ const result = await response.json();
1728
+ return result.items;
1729
+ }
1730
+ async listCurrentUserProjectPermissions(options, session) {
1731
+ const response = await this.sendClientRequest(
1732
+ `/project-permissions?user_id=me&recursive=${options.recursive}`,
1733
+ {},
1734
+ session
1735
+ );
1736
+ const result = await response.json();
1737
+ return result.items;
1738
+ }
1739
+ async listCurrentUserTeams(session) {
1740
+ const response = await this.sendClientRequest(
1741
+ "/teams?user_id=me",
1742
+ {},
1743
+ session
1744
+ );
1745
+ const result = await response.json();
1746
+ return result.items;
1747
+ }
1748
+ async getClientProject() {
1749
+ const responseOrError = await this.sendClientRequestAndCatchKnownError("/projects/current", {}, null, [KnownErrors.ProjectNotFound]);
1750
+ if (responseOrError.status === "error") {
1751
+ return Result.error(responseOrError.error);
1752
+ }
1753
+ const response = responseOrError.data;
1754
+ const project = await response.json();
1755
+ return Result.ok(project);
1756
+ }
1757
+ async updateClientUser(update, session) {
1758
+ await this.sendClientRequest(
1759
+ "/users/me",
1760
+ {
1761
+ method: "PATCH",
1762
+ headers: {
1763
+ "content-type": "application/json"
1764
+ },
1765
+ body: JSON.stringify(update)
1766
+ },
1767
+ session
1768
+ );
1769
+ }
1770
+ async listProjects(session) {
1771
+ const response = await this.sendClientRequest("/internal/projects", {}, session);
1772
+ if (!response.ok) {
1773
+ throw new Error("Failed to list projects: " + response.status + " " + await response.text());
1774
+ }
1775
+ const json = await response.json();
1776
+ return json.items;
1777
+ }
1778
+ async createProject(project, session) {
1779
+ const fetchResponse = await this.sendClientRequest(
1780
+ "/internal/projects",
1781
+ {
1782
+ method: "POST",
1783
+ headers: {
1784
+ "content-type": "application/json"
1785
+ },
1786
+ body: JSON.stringify(project)
1787
+ },
1788
+ session
1789
+ );
1790
+ if (!fetchResponse.ok) {
1791
+ throw new Error("Failed to create project: " + fetchResponse.status + " " + await fetchResponse.text());
1792
+ }
1793
+ const json = await fetchResponse.json();
1794
+ return json;
1795
+ }
1796
+ async createProviderAccessToken(provider, scope, session) {
1797
+ const response = await this.sendClientRequest(
1798
+ `/connected-accounts/me/${provider}/access-token`,
1799
+ {
1800
+ method: "POST",
1801
+ headers: {
1802
+ "content-type": "application/json"
1803
+ },
1804
+ body: JSON.stringify({ scope })
1805
+ },
1806
+ session
1807
+ );
1808
+ return await response.json();
1809
+ }
1810
+ async createClientTeam(data, session) {
1811
+ const response = await this.sendClientRequest(
1812
+ "/teams",
1813
+ {
1814
+ method: "POST",
1815
+ headers: {
1816
+ "content-type": "application/json"
1817
+ },
1818
+ body: JSON.stringify(data)
1819
+ },
1820
+ session
1821
+ );
1822
+ return await response.json();
1823
+ }
1824
+ async deleteTeam(teamId, session) {
1825
+ await this.sendClientRequest(
1826
+ `/teams/${teamId}`,
1827
+ {
1828
+ method: "DELETE"
1829
+ },
1830
+ session
1831
+ );
1832
+ }
1833
+ async deleteCurrentUser(session) {
1834
+ await this.sendClientRequest(
1835
+ "/users/me",
1836
+ {
1837
+ method: "DELETE"
1838
+ },
1839
+ session
1840
+ );
1841
+ }
1842
+ async createClientContactChannel(data, session) {
1843
+ const response = await this.sendClientRequest(
1844
+ "/contact-channels",
1845
+ {
1846
+ method: "POST",
1847
+ headers: {
1848
+ "content-type": "application/json"
1849
+ },
1850
+ body: JSON.stringify(data)
1851
+ },
1852
+ session
1853
+ );
1854
+ return await response.json();
1855
+ }
1856
+ async updateClientContactChannel(id, data, session) {
1857
+ const response = await this.sendClientRequest(
1858
+ `/contact-channels/me/${id}`,
1859
+ {
1860
+ method: "PATCH",
1861
+ headers: {
1862
+ "content-type": "application/json"
1863
+ },
1864
+ body: JSON.stringify(data)
1865
+ },
1866
+ session
1867
+ );
1868
+ return await response.json();
1869
+ }
1870
+ async deleteClientContactChannel(id, session) {
1871
+ await this.sendClientRequest(
1872
+ `/contact-channels/me/${id}`,
1873
+ {
1874
+ method: "DELETE"
1875
+ },
1876
+ session
1877
+ );
1878
+ }
1879
+ async deleteSession(sessionId, session) {
1880
+ await this.sendClientRequest(
1881
+ `/auth/sessions/${sessionId}?user_id=me`,
1882
+ {
1883
+ method: "DELETE"
1884
+ },
1885
+ session
1886
+ );
1887
+ }
1888
+ async listSessions(session) {
1889
+ const response = await this.sendClientRequest(
1890
+ "/auth/sessions?user_id=me",
1891
+ {
1892
+ method: "GET"
1893
+ },
1894
+ session
1895
+ );
1896
+ return await response.json();
1897
+ }
1898
+ async listClientContactChannels(session) {
1899
+ const response = await this.sendClientRequest(
1900
+ "/contact-channels?user_id=me",
1901
+ {
1902
+ method: "GET"
1903
+ },
1904
+ session
1905
+ );
1906
+ const json = await response.json();
1907
+ return json.items;
1908
+ }
1909
+ async sendCurrentUserContactChannelVerificationEmail(contactChannelId, callbackUrl, session) {
1910
+ const responseOrError = await this.sendClientRequestAndCatchKnownError(
1911
+ `/contact-channels/me/${contactChannelId}/send-verification-code`,
1912
+ {
1913
+ method: "POST",
1914
+ headers: {
1915
+ "content-type": "application/json"
1916
+ },
1917
+ body: JSON.stringify({ callback_url: callbackUrl })
1918
+ },
1919
+ session,
1920
+ [KnownErrors.EmailAlreadyVerified]
1921
+ );
1922
+ if (responseOrError.status === "error") {
1923
+ return Result.error(responseOrError.error);
1924
+ }
1925
+ return Result.ok(void 0);
1926
+ }
1927
+ async cliLogin(loginCode, refreshToken, session) {
1928
+ const responseOrError = await this.sendClientRequestAndCatchKnownError(
1929
+ "/auth/cli/complete",
1930
+ {
1931
+ method: "POST",
1932
+ headers: {
1933
+ "Content-Type": "application/json"
1934
+ },
1935
+ body: JSON.stringify({
1936
+ login_code: loginCode,
1937
+ refresh_token: refreshToken
1938
+ })
1939
+ },
1940
+ session,
1941
+ [KnownErrors.SchemaError]
1942
+ );
1943
+ if (responseOrError.status === "error") {
1944
+ return Result.error(responseOrError.error);
1945
+ }
1946
+ return Result.ok(void 0);
1947
+ }
1948
+ async _getApiKeyRequestInfo(options) {
1949
+ if ("user_id" in options && "team_id" in options) {
1950
+ throw new StackAssertionError("Cannot specify both user_id and team_id in _getApiKeyRequestInfo");
1951
+ }
1952
+ return {
1953
+ endpoint: "team_id" in options ? "/team-api-keys" : "/user-api-keys",
1954
+ queryParams: new URLSearchParams(filterUndefinedOrNull(options))
1955
+ };
1956
+ }
1957
+ async listProjectApiKeys(options, session, requestType) {
1958
+ const sendRequest = (requestType === "client" ? this.sendClientRequest : this.sendServerRequest).bind(this);
1959
+ const { endpoint, queryParams } = await this._getApiKeyRequestInfo(options);
1960
+ const response = await sendRequest(
1961
+ `${endpoint}?${queryParams.toString()}`,
1962
+ {
1963
+ method: "GET"
1964
+ },
1965
+ session,
1966
+ requestType
1967
+ );
1968
+ const json = await response.json();
1969
+ return json.items;
1970
+ }
1971
+ async createProjectApiKey(data, session, requestType) {
1972
+ const sendRequest = (requestType === "client" ? this.sendClientRequest : this.sendServerRequest).bind(this);
1973
+ const { endpoint } = await this._getApiKeyRequestInfo(data);
1974
+ const response = await sendRequest(
1975
+ `${endpoint}`,
1976
+ {
1977
+ method: "POST",
1978
+ headers: {
1979
+ "content-type": "application/json"
1980
+ },
1981
+ body: JSON.stringify(data)
1982
+ },
1983
+ session,
1984
+ requestType
1985
+ );
1986
+ return await response.json();
1987
+ }
1988
+ async getProjectApiKey(options, keyId, session, requestType) {
1989
+ const sendRequest = (requestType === "client" ? this.sendClientRequest : this.sendServerRequest).bind(this);
1990
+ const { endpoint, queryParams } = await this._getApiKeyRequestInfo(options);
1991
+ const response = await sendRequest(
1992
+ `${endpoint}/${keyId}?${queryParams.toString()}`,
1993
+ {
1994
+ method: "GET"
1995
+ },
1996
+ session,
1997
+ requestType
1998
+ );
1999
+ return await response.json();
2000
+ }
2001
+ async updateProjectApiKey(options, keyId, data, session, requestType) {
2002
+ const sendRequest = (requestType === "client" ? this.sendClientRequest : this.sendServerRequest).bind(this);
2003
+ const { endpoint, queryParams } = await this._getApiKeyRequestInfo(options);
2004
+ const response = await sendRequest(
2005
+ `${endpoint}/${keyId}?${queryParams.toString()}`,
2006
+ {
2007
+ method: "PATCH",
2008
+ headers: {
2009
+ "content-type": "application/json"
2010
+ },
2011
+ body: JSON.stringify(data)
2012
+ },
2013
+ session,
2014
+ requestType
2015
+ );
2016
+ return await response.json();
2017
+ }
2018
+ async checkProjectApiKey(type, apiKey, session, requestType) {
2019
+ const sendRequest = (requestType === "client" ? this.sendClientRequestAndCatchKnownError : this.sendServerRequestAndCatchKnownError).bind(this);
2020
+ const result = await sendRequest(
2021
+ `/${type}-api-keys/check`,
2022
+ {
2023
+ method: "POST",
2024
+ headers: {
2025
+ "content-type": "application/json"
2026
+ },
2027
+ body: JSON.stringify({ api_key: apiKey })
2028
+ },
2029
+ session,
2030
+ [KnownErrors.ApiKeyNotValid]
2031
+ );
2032
+ if (result.status === "error") {
2033
+ return null;
2034
+ }
2035
+ return await result.data.json();
2036
+ }
2037
+ };
2038
+ export {
2039
+ StackClientInterface
2040
+ };
2041
+ //# sourceMappingURL=clientInterface.js.map