@ai-development-environment/server 0.0.145 → 0.0.146

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 (330) hide show
  1. package/package.json +1 -1
  2. package/standalone/.next/BUILD_ID +1 -1
  3. package/standalone/.next/app-path-routes-manifest.json +2 -0
  4. package/standalone/.next/build-manifest.json +3 -3
  5. package/standalone/.next/prerender-manifest.json +3 -3
  6. package/standalone/.next/routes-manifest.json +12 -0
  7. package/standalone/.next/server/app/.well-known/[...path]/route.js.nft.json +1 -1
  8. package/standalone/.next/server/app/[locale]/(auth)/register/page.js.nft.json +1 -1
  9. package/standalone/.next/server/app/[locale]/(auth)/register/page_client-reference-manifest.js +1 -1
  10. package/standalone/.next/server/app/[locale]/(auth)/sign-in/page.js.nft.json +1 -1
  11. package/standalone/.next/server/app/[locale]/(auth)/sign-in/page_client-reference-manifest.js +1 -1
  12. package/standalone/.next/server/app/[locale]/(dashboard)/ai/costs/page.js.nft.json +1 -1
  13. package/standalone/.next/server/app/[locale]/(dashboard)/ai/costs/page_client-reference-manifest.js +1 -1
  14. package/standalone/.next/server/app/[locale]/(dashboard)/ai/drafts/new/page.js.nft.json +1 -1
  15. package/standalone/.next/server/app/[locale]/(dashboard)/ai/drafts/new/page_client-reference-manifest.js +1 -1
  16. package/standalone/.next/server/app/[locale]/(dashboard)/ai/drafts/page.js.nft.json +1 -1
  17. package/standalone/.next/server/app/[locale]/(dashboard)/ai/drafts/page_client-reference-manifest.js +1 -1
  18. package/standalone/.next/server/app/[locale]/(dashboard)/ai/plans/[runId]/page.js.nft.json +1 -1
  19. package/standalone/.next/server/app/[locale]/(dashboard)/ai/plans/[runId]/page_client-reference-manifest.js +1 -1
  20. package/standalone/.next/server/app/[locale]/(dashboard)/ai/plans/page.js.nft.json +1 -1
  21. package/standalone/.next/server/app/[locale]/(dashboard)/ai/plans/page_client-reference-manifest.js +1 -1
  22. package/standalone/.next/server/app/[locale]/(dashboard)/ai/sessions/[runId]/page.js.nft.json +1 -1
  23. package/standalone/.next/server/app/[locale]/(dashboard)/ai/sessions/[runId]/page_client-reference-manifest.js +1 -1
  24. package/standalone/.next/server/app/[locale]/(dashboard)/ai/sessions/page.js.nft.json +1 -1
  25. package/standalone/.next/server/app/[locale]/(dashboard)/ai/sessions/page_client-reference-manifest.js +1 -1
  26. package/standalone/.next/server/app/[locale]/(dashboard)/ai/skills/[skillId]/page.js.nft.json +1 -1
  27. package/standalone/.next/server/app/[locale]/(dashboard)/ai/skills/[skillId]/page_client-reference-manifest.js +1 -1
  28. package/standalone/.next/server/app/[locale]/(dashboard)/ai/skills/groups/[groupId]/page.js.nft.json +1 -1
  29. package/standalone/.next/server/app/[locale]/(dashboard)/ai/skills/groups/[groupId]/page_client-reference-manifest.js +1 -1
  30. package/standalone/.next/server/app/[locale]/(dashboard)/ai/skills/groups/page.js.nft.json +1 -1
  31. package/standalone/.next/server/app/[locale]/(dashboard)/ai/skills/groups/page_client-reference-manifest.js +1 -1
  32. package/standalone/.next/server/app/[locale]/(dashboard)/ai/skills/page.js.nft.json +1 -1
  33. package/standalone/.next/server/app/[locale]/(dashboard)/ai/skills/page_client-reference-manifest.js +1 -1
  34. package/standalone/.next/server/app/[locale]/(dashboard)/ai/skills/sync/[runId]/page.js.nft.json +1 -1
  35. package/standalone/.next/server/app/[locale]/(dashboard)/ai/skills/sync/[runId]/page_client-reference-manifest.js +1 -1
  36. package/standalone/.next/server/app/[locale]/(dashboard)/ai/usage/page.js.nft.json +1 -1
  37. package/standalone/.next/server/app/[locale]/(dashboard)/ai/usage/page_client-reference-manifest.js +1 -1
  38. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/action-center/page.js.nft.json +1 -1
  39. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/action-center/page_client-reference-manifest.js +1 -1
  40. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/agents/[id]/page.js.nft.json +1 -1
  41. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/agents/[id]/page_client-reference-manifest.js +1 -1
  42. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/agents/page.js.nft.json +1 -1
  43. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/agents/page_client-reference-manifest.js +1 -1
  44. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/apps/[appId]/page.js.nft.json +1 -1
  45. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/apps/[appId]/page_client-reference-manifest.js +1 -1
  46. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/apps/page.js.nft.json +1 -1
  47. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/apps/page_client-reference-manifest.js +1 -1
  48. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/builds/[buildId]/coverage/page.js.nft.json +1 -1
  49. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/builds/[buildId]/coverage/page_client-reference-manifest.js +1 -1
  50. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/builds/[buildId]/output/route.js.nft.json +1 -1
  51. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/builds/[buildId]/page.js.nft.json +1 -1
  52. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/builds/[buildId]/page_client-reference-manifest.js +1 -1
  53. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/builds/configurations/[configurationId]/page.js.nft.json +1 -1
  54. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/builds/configurations/[configurationId]/page_client-reference-manifest.js +1 -1
  55. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/builds/page.js.nft.json +1 -1
  56. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/builds/page_client-reference-manifest.js +1 -1
  57. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/changes/page.js.nft.json +1 -1
  58. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/changes/page_client-reference-manifest.js +1 -1
  59. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/codebases/[codebaseId]/page.js.nft.json +1 -1
  60. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/codebases/[codebaseId]/page_client-reference-manifest.js +1 -1
  61. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/codebases/page.js.nft.json +1 -1
  62. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/codebases/page_client-reference-manifest.js +1 -1
  63. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/codebases/repositories/[repositoryId]/page.js.nft.json +1 -1
  64. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/codebases/repositories/[repositoryId]/page_client-reference-manifest.js +1 -1
  65. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/commands/[commandId]/edit/page.js.nft.json +1 -1
  66. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/commands/[commandId]/edit/page_client-reference-manifest.js +1 -1
  67. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/commands/new/page.js.nft.json +1 -1
  68. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/commands/new/page_client-reference-manifest.js +1 -1
  69. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/commands/page.js.nft.json +1 -1
  70. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/commands/page_client-reference-manifest.js +1 -1
  71. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/commands/runs/[runId]/output/route.js.nft.json +1 -1
  72. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/commands/runs/[runId]/page.js.nft.json +1 -1
  73. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/commands/runs/[runId]/page_client-reference-manifest.js +1 -1
  74. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/jobs/[jobId]/page.js.nft.json +1 -1
  75. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/jobs/[jobId]/page_client-reference-manifest.js +1 -1
  76. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/notifications/page.js.nft.json +1 -1
  77. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/notifications/page_client-reference-manifest.js +1 -1
  78. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/workflows/[workflowId]/edit/page.js.nft.json +1 -1
  79. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/workflows/[workflowId]/edit/page_client-reference-manifest.js +1 -1
  80. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/workflows/[workflowId]/page.js.nft.json +1 -1
  81. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/workflows/[workflowId]/page_client-reference-manifest.js +1 -1
  82. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/workflows/new/page.js.nft.json +1 -1
  83. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/workflows/new/page_client-reference-manifest.js +1 -1
  84. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/workflows/page.js.nft.json +1 -1
  85. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/workflows/page_client-reference-manifest.js +1 -1
  86. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/workflows/runs/[runId]/page.js.nft.json +1 -1
  87. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/workflows/runs/[runId]/page_client-reference-manifest.js +1 -1
  88. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/worktrees/[worktreeId]/page.js.nft.json +1 -1
  89. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/worktrees/[worktreeId]/page_client-reference-manifest.js +1 -1
  90. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/worktrees/page.js.nft.json +1 -1
  91. package/standalone/.next/server/app/[locale]/(dashboard)/dashboard/worktrees/page_client-reference-manifest.js +1 -1
  92. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/analytics-events/page.js.nft.json +1 -1
  93. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/analytics-events/page_client-reference-manifest.js +1 -1
  94. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/console-logs/page.js.nft.json +1 -1
  95. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/console-logs/page_client-reference-manifest.js +1 -1
  96. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/crashes/[crashId]/page.js.nft.json +1 -1
  97. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/crashes/[crashId]/page_client-reference-manifest.js +1 -1
  98. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/crashes/dsyms/[dsymId]/page.js.nft.json +1 -1
  99. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/crashes/dsyms/[dsymId]/page_client-reference-manifest.js +1 -1
  100. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/crashes/dsyms/page.js.nft.json +1 -1
  101. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/crashes/dsyms/page_client-reference-manifest.js +1 -1
  102. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/crashes/page.js.nft.json +1 -1
  103. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/crashes/page_client-reference-manifest.js +1 -1
  104. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/push-notifications/page.js.nft.json +1 -1
  105. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/push-notifications/page_client-reference-manifest.js +1 -1
  106. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/[endpointId]/mocks/page.js.nft.json +1 -1
  107. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/[endpointId]/mocks/page_client-reference-manifest.js +1 -1
  108. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/[endpointId]/page.js.nft.json +1 -1
  109. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/[endpointId]/page_client-reference-manifest.js +1 -1
  110. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/breakpoints/page.js.nft.json +1 -1
  111. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/breakpoints/page_client-reference-manifest.js +1 -1
  112. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/history/[requestId]/page.js.nft.json +1 -1
  113. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/history/[requestId]/page_client-reference-manifest.js +1 -1
  114. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/history/page.js.nft.json +1 -1
  115. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/history/page_client-reference-manifest.js +1 -1
  116. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/new/page.js.nft.json +1 -1
  117. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/new/page_client-reference-manifest.js +1 -1
  118. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/page.js.nft.json +1 -1
  119. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/page_client-reference-manifest.js +1 -1
  120. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/storage/page.js.nft.json +1 -1
  121. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/sse/storage/page_client-reference-manifest.js +1 -1
  122. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/unified-events/page.js.nft.json +1 -1
  123. package/standalone/.next/server/app/[locale]/(dashboard)/debugging/unified-events/page_client-reference-manifest.js +1 -1
  124. package/standalone/.next/server/app/[locale]/(dashboard)/github/actions/page.js.nft.json +1 -1
  125. package/standalone/.next/server/app/[locale]/(dashboard)/github/actions/page_client-reference-manifest.js +1 -1
  126. package/standalone/.next/server/app/[locale]/(dashboard)/github/actions-cache/page.js.nft.json +1 -1
  127. package/standalone/.next/server/app/[locale]/(dashboard)/github/actions-cache/page_client-reference-manifest.js +1 -1
  128. package/standalone/.next/server/app/[locale]/(dashboard)/github/cache/entries/[id]/page.js.nft.json +1 -1
  129. package/standalone/.next/server/app/[locale]/(dashboard)/github/cache/entries/[id]/page_client-reference-manifest.js +1 -1
  130. package/standalone/.next/server/app/[locale]/(dashboard)/github/cache/page.js.nft.json +1 -1
  131. package/standalone/.next/server/app/[locale]/(dashboard)/github/cache/page_client-reference-manifest.js +1 -1
  132. package/standalone/.next/server/app/[locale]/(dashboard)/github/comments/page.js.nft.json +1 -1
  133. package/standalone/.next/server/app/[locale]/(dashboard)/github/comments/page_client-reference-manifest.js +1 -1
  134. package/standalone/.next/server/app/[locale]/(dashboard)/github/pull-requests/[owner]/[repository]/[number]/page.js.nft.json +1 -1
  135. package/standalone/.next/server/app/[locale]/(dashboard)/github/pull-requests/[owner]/[repository]/[number]/page_client-reference-manifest.js +1 -1
  136. package/standalone/.next/server/app/[locale]/(dashboard)/github/pull-requests/page.js.nft.json +1 -1
  137. package/standalone/.next/server/app/[locale]/(dashboard)/github/pull-requests/page_client-reference-manifest.js +1 -1
  138. package/standalone/.next/server/app/[locale]/(dashboard)/github/webhooks/page.js.nft.json +1 -1
  139. package/standalone/.next/server/app/[locale]/(dashboard)/github/webhooks/page_client-reference-manifest.js +1 -1
  140. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/cache/page.js.nft.json +1 -1
  141. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/cache/page_client-reference-manifest.js +1 -1
  142. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/comments/page.js.nft.json +1 -1
  143. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/comments/page_client-reference-manifest.js +1 -1
  144. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/merge-requests/[projectId]/[iid]/page.js.nft.json +1 -1
  145. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/merge-requests/[projectId]/[iid]/page_client-reference-manifest.js +1 -1
  146. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/merge-requests/page.js.nft.json +1 -1
  147. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/merge-requests/page_client-reference-manifest.js +1 -1
  148. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/pipelines/page.js.nft.json +1 -1
  149. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/pipelines/page_client-reference-manifest.js +1 -1
  150. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/webhooks/page.js.nft.json +1 -1
  151. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/webhooks/page_client-reference-manifest.js +1 -1
  152. package/standalone/.next/server/app/[locale]/(dashboard)/jira/cache/page.js.nft.json +1 -1
  153. package/standalone/.next/server/app/[locale]/(dashboard)/jira/cache/page_client-reference-manifest.js +1 -1
  154. package/standalone/.next/server/app/[locale]/(dashboard)/jira/cache/tickets/[issueKey]/page.js.nft.json +1 -1
  155. package/standalone/.next/server/app/[locale]/(dashboard)/jira/cache/tickets/[issueKey]/page_client-reference-manifest.js +1 -1
  156. package/standalone/.next/server/app/[locale]/(dashboard)/jira/tickets/[issueKey]/page.js.nft.json +1 -1
  157. package/standalone/.next/server/app/[locale]/(dashboard)/jira/tickets/[issueKey]/page_client-reference-manifest.js +1 -1
  158. package/standalone/.next/server/app/[locale]/(dashboard)/jira/tickets/page.js.nft.json +1 -1
  159. package/standalone/.next/server/app/[locale]/(dashboard)/jira/tickets/page_client-reference-manifest.js +1 -1
  160. package/standalone/.next/server/app/[locale]/(dashboard)/jira/webhooks/page.js.nft.json +1 -1
  161. package/standalone/.next/server/app/[locale]/(dashboard)/jira/webhooks/page_client-reference-manifest.js +1 -1
  162. package/standalone/.next/server/app/[locale]/(dashboard)/system/api-keys/page.js.nft.json +1 -1
  163. package/standalone/.next/server/app/[locale]/(dashboard)/system/api-keys/page_client-reference-manifest.js +1 -1
  164. package/standalone/.next/server/app/[locale]/(dashboard)/system/build-data/page.js.nft.json +1 -1
  165. package/standalone/.next/server/app/[locale]/(dashboard)/system/build-data/page_client-reference-manifest.js +1 -1
  166. package/standalone/.next/server/app/[locale]/(dashboard)/system/connected-applications/page.js.nft.json +1 -1
  167. package/standalone/.next/server/app/[locale]/(dashboard)/system/connected-applications/page_client-reference-manifest.js +1 -1
  168. package/standalone/.next/server/app/[locale]/(dashboard)/system/credentials/page.js.nft.json +1 -1
  169. package/standalone/.next/server/app/[locale]/(dashboard)/system/credentials/page_client-reference-manifest.js +1 -1
  170. package/standalone/.next/server/app/[locale]/(dashboard)/system/devices/[id]/page.js.nft.json +1 -1
  171. package/standalone/.next/server/app/[locale]/(dashboard)/system/devices/[id]/page_client-reference-manifest.js +1 -1
  172. package/standalone/.next/server/app/[locale]/(dashboard)/system/devices/enroll/page.js.nft.json +1 -1
  173. package/standalone/.next/server/app/[locale]/(dashboard)/system/devices/enroll/page_client-reference-manifest.js +1 -1
  174. package/standalone/.next/server/app/[locale]/(dashboard)/system/devices/page.js.nft.json +1 -1
  175. package/standalone/.next/server/app/[locale]/(dashboard)/system/devices/page_client-reference-manifest.js +1 -1
  176. package/standalone/.next/server/app/[locale]/(dashboard)/system/polling/page.js.nft.json +1 -1
  177. package/standalone/.next/server/app/[locale]/(dashboard)/system/polling/page_client-reference-manifest.js +1 -1
  178. package/standalone/.next/server/app/[locale]/(dashboard)/system/prepare/page.js.nft.json +1 -1
  179. package/standalone/.next/server/app/[locale]/(dashboard)/system/prepare/page_client-reference-manifest.js +1 -1
  180. package/standalone/.next/server/app/[locale]/(dashboard)/system/provisioning-profiles/[profileId]/page.js.nft.json +1 -1
  181. package/standalone/.next/server/app/[locale]/(dashboard)/system/provisioning-profiles/[profileId]/page_client-reference-manifest.js +1 -1
  182. package/standalone/.next/server/app/[locale]/(dashboard)/system/provisioning-profiles/page.js.nft.json +1 -1
  183. package/standalone/.next/server/app/[locale]/(dashboard)/system/provisioning-profiles/page_client-reference-manifest.js +1 -1
  184. package/standalone/.next/server/app/[locale]/(dashboard)/system/settings/page.js.nft.json +1 -1
  185. package/standalone/.next/server/app/[locale]/(dashboard)/system/settings/page_client-reference-manifest.js +1 -1
  186. package/standalone/.next/server/app/[locale]/(dashboard)/system/status/page.js.nft.json +1 -1
  187. package/standalone/.next/server/app/[locale]/(dashboard)/system/status/page_client-reference-manifest.js +1 -1
  188. package/standalone/.next/server/app/[locale]/(dashboard)/system/tailscale/page.js.nft.json +1 -1
  189. package/standalone/.next/server/app/[locale]/(dashboard)/system/tailscale/page_client-reference-manifest.js +1 -1
  190. package/standalone/.next/server/app/[locale]/(dashboard)/system/tools/page.js.nft.json +1 -1
  191. package/standalone/.next/server/app/[locale]/(dashboard)/system/tools/page_client-reference-manifest.js +1 -1
  192. package/standalone/.next/server/app/[locale]/(dashboard)/system/users/page.js.nft.json +1 -1
  193. package/standalone/.next/server/app/[locale]/(dashboard)/system/users/page_client-reference-manifest.js +1 -1
  194. package/standalone/.next/server/app/[locale]/(mcp)/mcp/consent/page.js.nft.json +1 -1
  195. package/standalone/.next/server/app/[locale]/(mcp)/mcp/consent/page_client-reference-manifest.js +1 -1
  196. package/standalone/.next/server/app/[locale]/(mcp)/mcp/sign-in/page.js.nft.json +1 -1
  197. package/standalone/.next/server/app/[locale]/(mcp)/mcp/sign-in/page_client-reference-manifest.js +1 -1
  198. package/standalone/.next/server/app/[locale]/page.js.nft.json +1 -1
  199. package/standalone/.next/server/app/[locale]/page_client-reference-manifest.js +1 -1
  200. package/standalone/.next/server/app/_global-error.html +1 -1
  201. package/standalone/.next/server/app/_global-error.rsc +1 -1
  202. package/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  203. package/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  204. package/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  205. package/standalone/.next/server/app/_not-found.html +1 -1
  206. package/standalone/.next/server/app/_not-found.rsc +1 -1
  207. package/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  208. package/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  209. package/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  210. package/standalone/.next/server/app/api/agent/build-artifact-transfers/[transferId]/complete/route.js.nft.json +1 -1
  211. package/standalone/.next/server/app/api/agent/build-artifact-transfers/[transferId]/download/route.js.nft.json +1 -1
  212. package/standalone/.next/server/app/api/agent/build-artifact-transfers/[transferId]/route.js.nft.json +1 -1
  213. package/standalone/.next/server/app/api/agent/build-artifact-transfers/[transferId]/upload/route.js.nft.json +1 -1
  214. package/standalone/.next/server/app/api/agent/dsyms/[dsymId]/dwarf/route.js.nft.json +1 -1
  215. package/standalone/.next/server/app/api/agent/run-attachments/[attachmentId]/route.js.nft.json +1 -1
  216. package/standalone/.next/server/app/api/auth/[...all]/route.js.nft.json +1 -1
  217. package/standalone/.next/server/app/api/auth/config/route.js.nft.json +1 -1
  218. package/standalone/.next/server/app/api/auth/management/api-keys/[keyId]/route.js.nft.json +1 -1
  219. package/standalone/.next/server/app/api/auth/management/api-keys/route.js.nft.json +1 -1
  220. package/standalone/.next/server/app/api/auth/management/registration/route.js.nft.json +1 -1
  221. package/standalone/.next/server/app/api/auth/management/sessions/[sessionId]/route.js.nft.json +1 -1
  222. package/standalone/.next/server/app/api/auth/management/users/[userId]/route.js.nft.json +1 -1
  223. package/standalone/.next/server/app/api/auth/management/users/route.js.nft.json +1 -1
  224. package/standalone/.next/server/app/api/auth/mcp-connections/route.js.nft.json +1 -1
  225. package/standalone/.next/server/app/api/auth/mobile/complete/route/app-paths-manifest.json +3 -0
  226. package/standalone/.next/server/app/api/auth/mobile/complete/route/build-manifest.json +12 -0
  227. package/standalone/.next/server/app/api/auth/mobile/complete/route/server-reference-manifest.json +4 -0
  228. package/standalone/.next/server/app/api/auth/mobile/complete/route.js +27 -0
  229. package/standalone/.next/server/app/api/auth/mobile/complete/route.js.map +5 -0
  230. package/standalone/.next/server/app/api/auth/mobile/complete/route.js.nft.json +1 -0
  231. package/standalone/.next/server/app/api/auth/mobile/complete/route_client-reference-manifest.js +3 -0
  232. package/standalone/.next/server/app/api/auth/mobile/oauth/complete/route.js +7 -7
  233. package/standalone/.next/server/app/api/auth/mobile/oauth/complete/route.js.nft.json +1 -1
  234. package/standalone/.next/server/app/api/auth/mobile/oauth/start/route.js +7 -7
  235. package/standalone/.next/server/app/api/auth/mobile/oauth/start/route.js.nft.json +1 -1
  236. package/standalone/.next/server/app/api/auth/mobile/redeem/route.js +8 -8
  237. package/standalone/.next/server/app/api/auth/mobile/redeem/route.js.nft.json +1 -1
  238. package/standalone/.next/server/app/api/auth/mobile/start/route/app-paths-manifest.json +3 -0
  239. package/standalone/.next/server/app/api/auth/mobile/start/route/build-manifest.json +12 -0
  240. package/standalone/.next/server/app/api/auth/mobile/start/route/server-reference-manifest.json +4 -0
  241. package/standalone/.next/server/app/api/auth/mobile/start/route.js +27 -0
  242. package/standalone/.next/server/app/api/auth/mobile/start/route.js.map +5 -0
  243. package/standalone/.next/server/app/api/auth/mobile/start/route.js.nft.json +1 -0
  244. package/standalone/.next/server/app/api/auth/mobile/start/route_client-reference-manifest.js +3 -0
  245. package/standalone/.next/server/app/api/build-artifact-uploads/[uploadId]/route.js.nft.json +1 -1
  246. package/standalone/.next/server/app/api/codebases/by-path/route.js.nft.json +1 -1
  247. package/standalone/.next/server/app/api/codebases/route.js.nft.json +1 -1
  248. package/standalone/.next/server/app/api/crash-files/dsyms/[dsymId]/route.js.nft.json +1 -1
  249. package/standalone/.next/server/app/api/crash-files/reports/[crashId]/route.js.nft.json +1 -1
  250. package/standalone/.next/server/app/api/dsyms/route.js.nft.json +1 -1
  251. package/standalone/.next/server/app/api/dsyms/uploads/[uploadId]/complete/route.js.nft.json +1 -1
  252. package/standalone/.next/server/app/api/dsyms/uploads/[uploadId]/route.js.nft.json +1 -1
  253. package/standalone/.next/server/app/api/dsyms/uploads/route.js.nft.json +1 -1
  254. package/standalone/.next/server/app/api/graphql/route.js.nft.json +1 -1
  255. package/standalone/.next/server/app/api/ios/apns-devices/route.js.nft.json +1 -1
  256. package/standalone/.next/server/app/api/ios/devices/export.tsv/route.js.nft.json +1 -1
  257. package/standalone/.next/server/app/api/ios/enrollment/start/route.js.nft.json +1 -1
  258. package/standalone/.next/server/app/api/ios/notification-devices/route.js.nft.json +1 -1
  259. package/standalone/.next/server/app/api/mcp/route.js.nft.json +1 -1
  260. package/standalone/.next/server/app/api/public/builds/[buildId]/artifacts/[artifactId]/manifest.plist/route.js.nft.json +1 -1
  261. package/standalone/.next/server/app/api/public/builds/[buildId]/artifacts/[artifactId]/route.js.nft.json +1 -1
  262. package/standalone/.next/server/app/api/public/crashes/route.js.nft.json +1 -1
  263. package/standalone/.next/server/app/api/public/github/webhook/route.js.nft.json +1 -1
  264. package/standalone/.next/server/app/api/public/gitlab/webhook/route.js.nft.json +1 -1
  265. package/standalone/.next/server/app/api/public/ios/enrollment-profile/route.js.nft.json +1 -1
  266. package/standalone/.next/server/app/api/public/ios/profile-response/route.js.nft.json +1 -1
  267. package/standalone/.next/server/app/api/public/jira/webhook/route.js.nft.json +1 -1
  268. package/standalone/.next/server/app/api/public/sse/[token]/route.js.nft.json +1 -1
  269. package/standalone/.next/server/app/api/run-attachments/[attachmentId]/route.js.nft.json +1 -1
  270. package/standalone/.next/server/app/api/run-attachments/route.js.nft.json +1 -1
  271. package/standalone/.next/server/app/api/sse/history/export/route.js.nft.json +1 -1
  272. package/standalone/.next/server/app/api/telemetry/analytics-events/route.js.nft.json +1 -1
  273. package/standalone/.next/server/app/api/telemetry/console-logs/route.js.nft.json +1 -1
  274. package/standalone/.next/server/app/api/telemetry/export/route.js.nft.json +1 -1
  275. package/standalone/.next/server/app/api/tools/call/route.js.nft.json +1 -1
  276. package/standalone/.next/server/app/api/tools/catalog/route.js.nft.json +1 -1
  277. package/standalone/.next/server/app/api/worktrees/[worktreeId]/diff-image/route.js.nft.json +1 -1
  278. package/standalone/.next/server/app-paths-manifest.json +2 -0
  279. package/standalone/.next/server/chunks/[root-of-the-server]__08_7puebrvq1u._.js +3 -0
  280. package/standalone/.next/server/chunks/[root-of-the-server]__0q53u1lz9zcel._.js +3 -0
  281. package/standalone/.next/server/chunks/[root-of-the-server]__0w_fiath2ph0r._.js +3 -0
  282. package/standalone/.next/server/chunks/{[root-of-the-server]__0ju8rf-41j6tg._.js → [root-of-the-server]__0wklpoczsamtz._.js} +1 -1
  283. package/standalone/.next/server/chunks/[root-of-the-server]__1p6yaef-nnj9f._.js +3 -0
  284. package/standalone/.next/server/chunks/[root-of-the-server]__1yi2awtahh06l._.js +3 -0
  285. package/standalone/.next/server/chunks/_00gwh-xp3pnpi._.js +1 -1
  286. package/standalone/.next/server/chunks/_01xn06357g7fo._.js +1 -1
  287. package/standalone/.next/server/chunks/_02howx6vajt3x._.js +1 -1
  288. package/standalone/.next/server/chunks/_07bdynyr-ww6v._.js +1 -1
  289. package/standalone/.next/server/chunks/_0_6e6kxry26k1._.js +1 -1
  290. package/standalone/.next/server/chunks/_0a8wo5-9_cv91._.js +1 -1
  291. package/standalone/.next/server/chunks/_0c6k8a0d2f3tn._.js +3 -0
  292. package/standalone/.next/server/chunks/_0gaxgdz7o4e15._.js +1 -1
  293. package/standalone/.next/server/chunks/_0m2wnzdzbny6g._.js +1 -1
  294. package/standalone/.next/server/chunks/_0naxf7ngn48-a._.js +1 -1
  295. package/standalone/.next/server/chunks/_0vlhouch-s4pc._.js +1 -1
  296. package/standalone/.next/server/chunks/_0yuq4ngrjch9x._.js +12 -12
  297. package/standalone/.next/server/chunks/_13lj4necdms38._.js +3 -0
  298. package/standalone/.next/server/chunks/_15xfyrp3ns4se._.js +1 -1
  299. package/standalone/.next/server/chunks/_1cexgfaro_78_._.js +1 -1
  300. package/standalone/.next/server/chunks/_1ftldg0qwxhfp._.js +12 -12
  301. package/standalone/.next/server/chunks/_1rfrstxzen60k._.js +12 -12
  302. package/standalone/.next/server/chunks/_1x3jv-sohpxg7._.js +12 -12
  303. package/standalone/.next/server/chunks/_1yawotm_tvy7h._.js +12 -12
  304. package/standalone/.next/server/chunks/_next-internal_server_app_api_auth_mobile_complete_route_actions_1iv1ncqhts5t2.js +3 -0
  305. package/standalone/.next/server/chunks/_next-internal_server_app_api_auth_mobile_start_route_actions_1n1uwu0lm0vgh.js +3 -0
  306. package/standalone/.next/server/chunks/src_app_api_auth_mobile_pkce_ts_0yvx0rhy5xij_._.js +3 -0
  307. package/standalone/.next/server/chunks/src_services_auth_054qv1_ze5hs6._.js +1 -1
  308. package/standalone/.next/server/chunks/src_services_auth_mcp-oauth_ts_0u9lgdhxzq5oy._.js +1 -1
  309. package/standalone/.next/server/chunks/ssr/{_0i3_5985sl3t6._.js → _0i28drefwqlu4._.js} +1 -1
  310. package/standalone/.next/server/chunks/ssr/{_20vs1czk-ajfp._.js → _0xvm24-eb9_vn._.js} +1 -1
  311. package/standalone/.next/server/chunks/ssr/{node_modules_@xterm_1gr72n7t9__g9._.js → node_modules_@xterm_15gm8vmx8nfth._.js} +1 -1
  312. package/standalone/.next/server/chunks/ssr/src_components_app-shell_tsx_0e1q-gvlrd7c8._.js +10 -10
  313. package/standalone/.next/server/chunks/ssr/src_components_auth_auth-form_tsx_1qbcqfp1650nl._.js +1 -1
  314. package/standalone/.next/server/chunks/ssr/src_services_auth_auth_ts_1zu3fo64zql9-._.js +2 -2
  315. package/standalone/.next/server/middleware-build-manifest.js +3 -3
  316. package/standalone/.next/server/pages/404.html +1 -1
  317. package/standalone/.next/server/pages/500.html +1 -1
  318. package/standalone/.next/server/preview-props.json +3 -3
  319. package/standalone/.next/server/server-reference-manifest.js +1 -1
  320. package/standalone/.next/server/server-reference-manifest.json +1 -1
  321. package/standalone/.next/static/chunks/{2aosjxs--k-i6.js → 07vm24tcai0yl.js} +10 -10
  322. package/standalone/.next/static/chunks/27ctd15f1bo-u.js +1 -0
  323. package/standalone/.next/static/chunks/{0nyv6hb43lli8.css → 2mh1ywtaqbgzw.css} +1 -1
  324. package/standalone/.next/server/chunks/[root-of-the-server]__0mh8vw5y7dcse._.js +0 -3
  325. package/standalone/.next/server/chunks/[root-of-the-server]__0sz_ys90gtn-r._.js +0 -3
  326. package/standalone/.next/server/chunks/[root-of-the-server]__1wa8r7gv5fbny._.js +0 -3
  327. package/standalone/.next/static/chunks/2qfttxgi_zspw.js +0 -1
  328. /package/standalone/.next/static/{dabvyPp7MJv8L1G5zvDel → gBLSSraJl0DtgK3pbYety}/_buildManifest.js +0 -0
  329. /package/standalone/.next/static/{dabvyPp7MJv8L1G5zvDel → gBLSSraJl0DtgK3pbYety}/_clientMiddlewareManifest.js +0 -0
  330. /package/standalone/.next/static/{dabvyPp7MJv8L1G5zvDel → gBLSSraJl0DtgK3pbYety}/_ssgManifest.js +0 -0
@@ -818,7 +818,7 @@ To resolve this, you can:
818
818
  1. Use only one of the conflicting plugins
819
819
  2. Configure the plugins to use different paths (if supported)
820
820
  3. Ensure plugins use different HTTP methods for the same path
821
- `)}}(e={...e,secret:r,baseURL:u?e.baseURL:h?new URL(h).origin:"",basePath:e.basePath||"/api/auth",plugins:o.concat(l)},d);let w=e.advanced?.ipAddress?.trustedProxies;if(w&&w.length>0){let A=(0,c.p)(w);A.length>0&&d.warn(`Ignoring invalid \`advanced.ipAddress.trustedProxies\` entries: ${A.join(", ")}. Each entry must be an IP address or CIDR range.`)}let y=(0,A4.e)(e),Q=(0,Ay.R)(e),B=(await Promise.all(Object.entries(e.socialProviders||{}).map(async([A,e])=>{let t="function"==typeof e?await e():e;if(null==t||!1===t.enabled)return null;t.clientId||d.warn(`Social provider ${A} is missing clientId or clientSecret`);let r=t7[A](t);return r.disableImplicitSignUp=t.disableImplicitSignUp,r}))).filter(A=>null!==A),D=({model:A,size:t})=>{if("function"==typeof e.advanced?.generateId)return e.advanced.generateId({model:A,size:t});let r=e?.advanced?.database?.generateId;return"function"==typeof r?r({model:A,size:t}):"uuid"===r?crypto.randomUUID():"serial"!==r&&!1!==r&&(0,E.f)(t)},{publish:k}=await it(e,{adapter:A.id,database:"function"==typeof e.database?"adapter":t(e.database)}),S=new Set(e.plugins.map(A=>A.id)),b=await ec(e),M=await eh(e),O={appName:e.appName||"Better Auth",baseURL:h||"",version:(0,rJ.I)(),socialProviders:B,options:e,oauthConfig:{storeStateStrategy:e.account?.storeStateStrategy||(s?"database":"cookie"),skipStateCookieCheck:!!e.account?.skipStateCookieCheck},tables:Q,trustedOrigins:b,trustedProviders:M,isTrustedOrigin(A,e){return this.trustedOrigins.some(t=>AZ(A,t,e))},sessionConfig:{updateAge:e.session?.updateAge!==void 0?e.session.updateAge:86400,expiresIn:e.session?.expiresIn||604800,freshAge:e.session?.freshAge===void 0?86400:e.session.freshAge,cookieRefreshCache:(n=e.session?.cookieCache?.refreshCache,a=e.session?.cookieCache?.maxAge||300,s&&n?(d.warn("[better-auth] `session.cookieCache.refreshCache` is enabled while `database` or `secondaryStorage` is configured. `refreshCache` is meant for stateless (DB-less) setups. Disabling `refreshCache` — remove it from your config to silence this warning."),!1):!1!==n&&void 0!==n&&(!0===n?{enabled:!0,updateAge:Math.floor(.2*a)}:{enabled:!0,updateAge:void 0!==n.updateAge?n.updateAge:Math.floor(.2*a)}))},secret:r,secretConfig:i,rateLimit:{...e.rateLimit,enabled:e.rateLimit?.enabled??ea.C,window:e.rateLimit?.window||10,max:e.rateLimit?.max||100,storage:e.rateLimit?.storage||(e.secondaryStorage?"secondary-storage":"memory")},authCookies:y,logger:d,generateId:D,session:null,secondaryStorage:e.secondaryStorage,password:{hash:e.emailAndPassword?.password?.hash||A1.Z,verify:e.emailAndPassword?.password?.verify||A1.B,config:{minPasswordLength:e.emailAndPassword?.minPasswordLength||8,maxPasswordLength:e.emailAndPassword?.maxPasswordLength||128},checkPassword:eE},setNewSession(A){this.newSession=A},newSession:null,adapter:A,internalAdapter:en(A,{options:e,logger:d,hooks:e.databaseHooks?[{source:"user",hooks:e.databaseHooks}]:[],generateId:D}),createAuthCookie:(0,A4.g)(e),async runMigrations(){throw new g.p("runMigrations will be set by the specific init implementation")},publishTelemetry:k,skipCSRFCheck:!!e.advanced?.disableCSRFCheck,skipOriginCheck:e.advanced?.disableOriginCheck!==void 0?e.advanced.disableOriginCheck:!!(0,ea.s)(),runInBackground:e.advanced?.backgroundTasks?.handler??(A=>{A.catch(()=>{})}),async runInBackgroundOrAwait(A){try{e.advanced?.backgroundTasks?.handler?A instanceof Promise&&e.advanced.backgroundTasks.handler(A.catch(A=>{d.error("Failed to run background task:",A)})):await A}catch(A){d.error("Failed to run background task:",A)}},getPlugin:A=>e.plugins.find(e=>e.id===A)??null,hasPlugin:A=>S.has(A)},v=el(O);return(0,A0.f)(v)&&await v,O.checkSchema=(0,Af.f)(O.adapter),O.explicitSchemaCheck=(0,Af.j)(O.adapter),O}let ii=async A=>{let e=await AD(A),t=await ir(e,A,A=>(0,AS.getKyselyDatabaseType)(A)||"unknown");return t.runMigrations=async function(){if(!A.database||"updateMany"in A.database)throw new g.p("Database is not provided or it's an adapter. Migrations are only supported with a database instance.");let{runMigrations:e}=await AJ(A);await e()},t};var ia=A.i(779198),is=A.i(595544);let io=()=>i??=A.A(162916).catch(A=>{throw i=void 0,A}),il=(0,D.y)({user:["create","list","set-role","ban","impersonate","impersonate-admins","delete","set-password","set-email","set-phone","get","update"],session:["list","revoke","delete"]}),ic={admin:il.newRole({user:["create","list","set-role","ban","impersonate","delete","set-password","set-email","set-phone","get","update"],session:["list","revoke","delete"]}),user:il.newRole({user:[],session:[]})},id=(0,s.f)({FAILED_TO_CREATE_USER:"Failed to create user",USER_ALREADY_EXISTS:"User already exists.",USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:"User already exists. Use another email.",YOU_CANNOT_BAN_YOURSELF:"You cannot ban yourself",YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE:"You are not allowed to change users role",YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS:"You are not allowed to create users",YOU_ARE_NOT_ALLOWED_TO_LIST_USERS:"You are not allowed to list users",YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS:"You are not allowed to list users sessions",YOU_ARE_NOT_ALLOWED_TO_BAN_USERS:"You are not allowed to ban users",YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS:"You are not allowed to impersonate users",YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS:"You are not allowed to revoke users sessions",YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS:"You are not allowed to delete users",YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD:"You are not allowed to set users password",BANNED_USER:"You have been banned from this application",YOU_ARE_NOT_ALLOWED_TO_GET_USER:"You are not allowed to get user",NO_DATA_TO_UPDATE:"No data to update",YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS:"You are not allowed to update users",YOU_CANNOT_REMOVE_YOURSELF:"You cannot remove yourself",YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE:"You are not allowed to set a non-existent role value",YOU_CANNOT_IMPERSONATE_ADMINS:"You cannot impersonate admins",INVALID_ROLE_TYPE:"Invalid role type",YOU_ARE_NOT_ALLOWED_TO_SET_USERS_EMAIL:"You are not allowed to update users email",YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PHONE_NUMBER:"You are not allowed to update users phone number",PASSWORD_CANNOT_BE_UPDATED_VIA_UPDATE_USER:"Password cannot be updated through update-user. Use the set-user-password endpoint instead",USER_ID_CANNOT_BE_UPDATED:"User id cannot be updated"}),iu=async A=>{let e=A.context.returned;return e?e instanceof Response?200!==e.status?null:await e.clone().json():(0,ew.f)(e)?null:e:null},ig=A=>{if(A.userId&&A.options?.adminUserIds?.includes(A.userId))return!0;if(!A.permissions)return!1;let e=(A.role||A.options?.defaultRole||"user").split(","),t=A.options?.roles||ic;for(let r of e)if(t[r]?.authorize(A.permissions)?.success)return!0;return!1};var ih=A.i(752067);let iI=(0,l.a)(async A=>{let e=await (0,h.M)(A);if(!e)throw g.E.fromStatus("UNAUTHORIZED");return{session:e}});function ip(A){return Array.isArray(A)?A.join(","):A}let iC=y.object({userId:Q.f.string().meta({description:"The user id"}),role:y.union([y.string().meta({description:"The role to set. `admin` or `user` by default"}),y.array(y.string().meta({description:"The roles to set. `admin` or `user` by default"}))]).meta({description:"The role to set, this can be a string or an array of strings. Eg: `admin` or `[admin, user]`"})}),im=y.object({id:y.string().meta({description:"The id of the User"})}),iE=y.object({email:y.string().meta({description:"The email of the user"}),password:y.string().optional().meta({description:"The password of the user. If not provided, the user will be created without a credential account (useful for magic link or social login only users)."}),name:y.string().meta({description:"The name of the user"}),role:y.union([y.string().meta({description:"The role of the user"}),y.array(y.string().meta({description:"The roles of user"}))]).optional().meta({description:'A string or array of strings representing the roles to apply to the new user. Eg: "user"'}),data:y.record(y.string(),y.any()).optional().meta({description:"Extra fields for the user. Including custom additional fields."})}),iw=y.object({userId:Q.f.string().meta({description:"The user id"}),data:y.record(y.any(),y.any()).meta({description:"The user data to update"})}),iy=y.object({searchValue:y.string().optional().meta({description:'The value to search for. Eg: "some name"'}),searchField:y.enum(["email","name"]).meta({description:'The field to search in, defaults to email. Can be `email` or `name`. Eg: "name"'}).optional(),searchOperator:y.enum(["contains","starts_with","ends_with"]).meta({description:'The operator to use for the search. Can be `contains`, `starts_with` or `ends_with`. Eg: "contains"'}).optional(),limit:y.string().meta({description:"The number of users to return"}).or(y.number()).optional(),offset:y.string().meta({description:"The offset to start from"}).or(y.number()).optional(),sortBy:y.string().meta({description:"The field to sort by"}).optional(),sortDirection:y.enum(["asc","desc"]).meta({description:"The direction to sort by"}).optional(),filterField:y.string().meta({description:"The field to filter by"}).optional(),filterValue:y.string().meta({description:"The value to filter by"}).or(y.number()).or(y.boolean()).or(y.array(y.string())).or(y.array(y.number())).optional(),filterOperator:y.enum(ih.f).meta({description:"The operator to use for the filter"}).optional()}),iQ=y.object({userId:Q.f.string().meta({description:"The user id"})}),iB=y.object({userId:Q.f.string().meta({description:"The user id"})}),iD=y.object({userId:Q.f.string().meta({description:"The user id"}),banReason:y.string().meta({description:"The reason for the ban"}).optional(),banExpiresIn:y.number().meta({description:"The number of seconds until the ban expires"}).optional()}),ik=y.object({userId:Q.f.string().meta({description:"The user id"})}),iS=y.object({sessionToken:y.string().meta({description:"The session token"})}),ib=y.object({userId:Q.f.string().meta({description:"The user id"})}),iM=y.object({userId:Q.f.string().meta({description:"The user id"})}),iO=y.object({newPassword:y.string().nonempty("newPassword cannot be empty").meta({description:"The new password"}),userId:Q.f.string().nonempty("userId cannot be empty").meta({description:"The user id"})}),iv=y.object({userId:Q.f.string().optional().meta({description:'The user id. Eg: "user-id"'}),role:y.string().optional().meta({description:'The role to check permission for. Eg: "admin"'})}).and(y.xor([y.object({permission:y.record(y.string(),y.array(y.string()))}),y.object({permissions:y.record(y.string(),y.array(y.string()))})])),iR={user:{fields:{role:{type:"string",required:!1,input:!1},banned:{type:"boolean",defaultValue:!1,required:!1,input:!1},banReason:{type:"string",required:!1,input:!1},banExpires:{type:"date",required:!1,input:!1}}},session:{fields:{impersonatedBy:{type:"string",required:!1,input:!1}}}};var iH=A.i(259968),iN=A.i(976394);function iT(A){try{return decodeURIComponent(A)}catch{return A}}let iL=(0,s.f)({INVALID_OAUTH_CONFIGURATION:"Invalid OAuth configuration",TOKEN_URL_NOT_FOUND:"Invalid OAuth configuration. Token URL not found."}),iU=A=>{try{return(0,tj.f)(A)}catch{return null}};async function i_(A,e,t){let r=await (0,tz.f)(A,{method:"GET",headers:e,signal:t?AbortSignal.timeout(t):void 0});if(r.error||!r.data)return null;if(r.data.issuer)try{new URL(r.data.issuer)}catch{return null}return r.data}async function iP(A,e,t){if(A.idToken){let e=t??iU(A.idToken);if(e?.sub&&e?.email)return{id:e.sub,emailVerified:e1(e.email_verified),image:e.picture,...e}}if(!e||!A.accessToken)return null;let r=await (0,tz.f)(e,{method:"GET",headers:{Authorization:`Bearer ${A.accessToken}`}});return r.error||!r.data?null:{...r.data,email:r.data.email,emailVerified:e1(r.data.email_verified),image:r.data.picture,name:r.data.name}}let iG=async A=>{let e=await (0,u.f)("SHA-256").digest(new TextEncoder().encode(A));return d.W.encode(new Uint8Array(e),{padding:!1})},ix=y.object({token:y.string().meta({description:'The token to verify. Eg: "some-token"'})});var iJ=A.i(270133),ij=A.i(135475),iY=A.i(768843);function iF(A,e){return A[e]?.trim()||void 0}function iz(A,e){let t=iF(A,e);if(!t)throw Error(`${e} is required for AUTH_MODE.`);return t}function iq(A=process.env){let e=function(A){let e=iF(A,"AUTH_MODE")??"password";if("password"!==e&&"oidc"!==e&&"both"!==e)throw Error('AUTH_MODE must be "password", "oidc", or "both".');return e}(A),t=(0,iJ.U)(A);return{secret:(0,iY.h)(A).authSecret,origins:t,baseURL:t.canonical,trustProxyHeaders:function(A){let e=iF(A,"TRUST_PROXY_HEADERS")?.toLowerCase();if(!e||"false"===e||"0"===e)return!1;if("true"===e||"1"===e)return!0;throw Error("TRUST_PROXY_HEADERS must be true, false, 1, or 0.")}(A),mode:e,provider:function(A,e){if("password"===e)return null;let t=iF(A,"AUTH_OAUTH_DISCOVERY_URL"),r=iF(A,"AUTH_OAUTH_AUTHORIZATION_URL"),i=iF(A,"AUTH_OAUTH_TOKEN_URL"),n=iF(A,"AUTH_OAUTH_USER_INFO_URL"),a=iF(A,"AUTH_OAUTH_ISSUER"),s=!!(r||i||n),o=r&&i&&n;if(t&&s)throw Error("OIDC configuration must use either discovery or explicit endpoints, not both.");if(!t&&!o)throw Error("OIDC authentication requires AUTH_OAUTH_DISCOVERY_URL or all of AUTH_OAUTH_AUTHORIZATION_URL, AUTH_OAUTH_TOKEN_URL, and AUTH_OAUTH_USER_INFO_URL.");if(s&&!o)throw Error("Explicit OAuth configuration must include authorization, token, and user-info URLs.");if(o&&!a)throw Error("AUTH_OAUTH_ISSUER is required with explicit OAuth endpoints.");let l=iz(A,"AUTH_OAUTH_SCOPES").split(",").map(A=>A.trim()).filter(Boolean);if(0===l.length)throw Error("AUTH_OAUTH_SCOPES must contain at least one scope.");return{providerId:iz(A,"AUTH_OAUTH_PROVIDER_ID"),displayName:iz(A,"AUTH_OAUTH_PROVIDER_NAME"),clientId:iz(A,"AUTH_OAUTH_CLIENT_ID"),clientSecret:iz(A,"AUTH_OAUTH_CLIENT_SECRET"),scopes:l,requireIssuerValidation:function(A){let e=iF(A,"AUTH_OAUTH_REQUIRE_ISSUER_VALIDATION")?.toLowerCase();if(!e||"false"===e||"0"===e)return!1;if("true"===e||"1"===e)return!0;throw Error("AUTH_OAUTH_REQUIRE_ISSUER_VALIDATION must be true, false, 1, or 0.")}(A),discoveryUrl:t,issuer:a,authorizationUrl:r,tokenUrl:i,userInfoUrl:n}}(A,e)}}function iV(A){return"password"===A||"both"===A}function iK(A){return"oidc"===A||"both"===A}A.s(["L",0,iq,"_",0,iK,"Z",0,iV],658978);var iW=A.i(812057);let i$=RegExp(String.raw`((?:"?(?:authorization|password|access[_-]?token|refresh[_-]?token|id[_-]?token|session[_-]?token|client[_-]?secret|client_assertion|code_verifier|code|token|secret|privateKey)"?)\s*:\s*)(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^,\n}\]]+)`,"gi");function iZ(A){return A.replace(i$,'$1"[REDACTED]"').replace(/\b(Bearer|DPoP)\s+[A-Za-z0-9._~+\/-]+/gi,"$1 [REDACTED]").replace(/([?&](?:access_token|refresh_token|client_secret|code|code_verifier)=)[^&\s]+/gi,"$1[REDACTED]")}function iX(A,e,...t){let r=[`${new Date().toISOString()} ${A.toUpperCase()} [Better Auth]: ${e}`,...t.map(A=>"string"==typeof A?A:(0,iW.inspect)(A,{depth:6,breakLength:120}))].map(iZ);"error"===A?console.error(...r):"warn"===A?console.warn(...r):console.log(...r)}function i0(A){return"string"==typeof A&&A.length>0?A:void 0}async function i1(A,e){try{return await fetch(A,{headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${e}`,"User-Agent":"AI-Development-Environment"}})}catch{return null}}async function i4(A,e){let t,r=await i1(A,e);if(!r?.ok)return null;let i=await r.json(),n=i0(i.email),a=await i1(((t=new URL(A)).pathname=`${t.pathname.replace(/\/$/,"")}/emails`,t.toString()),e),s=a?.ok?await a.json():[],o=Array.isArray(s)?s:[],l=o.find(A=>!0===A.primary)??o[0],c=n??i0(l?.email),d=o.find(A=>i0(A.email)===c);return{...i,email:c,emailVerified:d?.verified===!0,image:i0(i.avatar_url),name:i0(i.name)??i0(i.login)??""}}var i8=A.i(666680);let i5="default";async function i2(){let A=await (0,ij.U)();return await A.authSettings.findUnique({where:{id:i5}})??await A.authSettings.upsert({where:{id:i5},create:{id:i5},update:{}})}async function i9({allowWhenRegistrationClosed:A=!1}={}){let e=await (0,ij.U)(),t=await i2();if(t.bootstrapCompleted){if(!t.registrationEnabled&&!A)throw new g.E("FORBIDDEN",{message:"Account registration is disabled."});return}if(await e.user.count()>0){if(await e.authSettings.update({where:{id:i5},data:{bootstrapCompleted:!0,registrationEnabled:!1,bootstrapClaimId:null,bootstrapClaimedAt:null}}),A)return;throw new g.E("FORBIDDEN",{message:"Account registration is disabled."})}let r=new Date(Date.now()-18e4),i=(0,i8.randomUUID)();if(1!==(await e.authSettings.updateMany({where:{id:i5,bootstrapCompleted:!1,OR:[{bootstrapClaimedAt:null},{bootstrapClaimedAt:{lt:r}}]},data:{bootstrapClaimId:i,bootstrapClaimedAt:new Date}})).count)throw new g.E("CONFLICT",{message:"The initial account is already being created. Try again shortly."})}async function i6(){let A=await (0,ij.U)();await A.authSettings.updateMany({where:{id:i5,bootstrapCompleted:!1},data:{bootstrapCompleted:!0,registrationEnabled:!1,bootstrapClaimId:null,bootstrapClaimedAt:null}})}let i3={user:{create:{before:async(A,e)=>(await i9({allowWhenRegistrationClosed:e?.path?.includes("/admin/create-user")??!1}),{data:{...A,role:"user",banned:!1,banReason:null,banExpires:null}}),after:async()=>{await i6()}},update:{before:async A=>({data:{...A,role:"user",banned:!1,banReason:null,banExpires:null}})},delete:{before:async()=>{throw new g.E("BAD_REQUEST",{message:"Accounts must be deleted through the management API."})}}}};A.s(["f",0,i3],525796);var i7=A.i(160501),nA=A.i(375013),nA=nA,ne=A.i(747029),ne=ne,nt=ne,nr=ne,ni=ne,nn=A.i(880272),na=A.i(776578),ns=A.i(656998);let no=/\/(?:\.|%2e)(?:\.|%2e)?(?:\/|$|#|\?)/i,nl=new Set(["client_secret_post","client_secret_basic","client_secret_jwt"]);function nc(A){let e;try{e=new URL(A)}catch{return!1}return"https:"===e.protocol}let nd=/^application\/(?:[-\w.]+\+)?json\s*(?:;|$)/i,nu="Failed to fetch metadata document (network error or redirect blocked)",ng="cimd";function nh(A){return new nn.E("BAD_REQUEST",{error:"invalid_client",error_description:A})}function nI(){return nh("Metadata document exceeds 5KB size limit")}async function np(A,e,t){let r,i=A.body?.getReader();if(!i){let t=await A.text();if(new TextEncoder().encode(t).byteLength>e)throw nI();return t}let n=[],a=0,s=new Promise((A,e)=>{r=e}),o=()=>{r?.(Error("Metadata document body read aborted")),i.cancel().catch(()=>{})};t.aborted?o():t.addEventListener("abort",o,{once:!0});try{for(;;){let{done:A,value:t}=await Promise.race([i.read(),s]);if(A)break;if((a+=t.byteLength)>e)throw await i.cancel(),nI();n.push(t)}}finally{t.removeEventListener("abort",o),i.releaseLock()}let l=new Uint8Array(a),c=0;for(let A of n)l.set(A,c),c+=A.byteLength;return new TextDecoder().decode(l)}async function nC(A,e,t,r){let i,n=function(A){let e;if(no.test(A))return"client_id URL MUST NOT contain dot segments";if(A.includes("#"))return"client_id URL MUST NOT contain a fragment";try{e=new URL(A)}catch{return"client_id is not a valid URL"}if("https:"!==e.protocol)return"client_id URL must use HTTPS";let t=/^https:\/\//i.exec(A);if(!t||A.includes("\\"))return"client_id URL MUST use an explicit HTTPS authority form";let r=A.slice(t[0].length),i=r.search(/[/?#]/);return 0===i?"client_id URL MUST use an explicit HTTPS authority form":i<0||"/"!==r[i]?"client_id URL MUST contain an explicit path component":e.username||e.password?"client_id URL MUST NOT contain credentials":(0,eo.$)(e.hostname)?null:"client_id URL must not target a private or reserved address"}(e);if(n)throw nh(n);if(t.isMetadataDocumentUrlAllowed&&!await t.isMetadataDocumentUrlAllowed(e,A))throw nh("client_id URL is not permitted by the server's fetch policy");let a=new Headers({Accept:"application/json"});r?.etag&&a.set("If-None-Match",r.etag),r?.lastModified&&a.set("If-Modified-Since",r.lastModified);let s=new AbortController,o=!1,l=setTimeout(()=>{o=!0,s.abort()},5e3);try{var c;let n,l;try{i=await t.fetchClientMetadataResource(e,{headers:a,redirect:"error",signal:s.signal})}catch{throw nh(o?"Metadata document fetch timed out after 5000ms":nu)}if(i.redirected)throw nh("Metadata document fetch must not follow redirects");let d={cacheControl:(c=i.headers).get("cache-control")??void 0,vary:c.get("vary")??void 0,expires:c.get("expires")??void 0,date:c.get("date")??void 0,age:c.get("age")??void 0,etag:c.get("etag")??void 0,lastModified:c.get("last-modified")??void 0};if(304===i.status){if(!r?.etag&&!r?.lastModified)throw nh("Metadata document returned 304 without a conditional validator");return{status:"not-modified",cacheHeaders:d}}if(200!==i.status)throw nh(`Metadata document fetch returned HTTP ${i.status}`);let u=i.headers.get("content-type")??"";if(!nd.test(u))throw nh(`Metadata document must be JSON (got Content-Type "${u||"(none)"}")`);try{let A=i.headers.get("content-length");if(A){let e=Number.parseInt(A,10);if(Number.isFinite(e)&&e>5120)throw await i.body?.cancel(),nI()}n=await np(i,5120,s.signal)}catch(A){if(o)throw nh("Metadata document fetch timed out after 5000ms");if(A instanceof nn.E)throw A;throw nh(nu)}try{l=JSON.parse(n)}catch{throw nh("Metadata document is not valid JSON")}let g=function(A,e,t={}){let r;if(!e||"object"!=typeof e)return{valid:!1,error:"metadata document is not a JSON object"};for(let A of Object.keys(e))if((0,nt.c)(A))return{valid:!1,error:`metadata document MUST NOT contain "${A}"`};let i=ne.b.strip().safeParse(e);if(!i.success){let A=i.error.issues[0];return{valid:!1,error:`${A?.path.join(".")||"metadata document"}: ${A?.message??"invalid client metadata"}`}}let n=i.data,a=[];if(n.client_id!==A)return{valid:!1,error:`client_id "${String(n.client_id)}" does not match the metadata document URL`};if("mcp-2026-07-28"===t.metadataProfile&&!n.client_name?.trim())return{valid:!1,error:"client_name must be a non-empty string"};for(let A of["backchannel_logout_uri","backchannel_logout_session_required"])if(void 0!==n[A])return{valid:!1,error:`metadata document MUST NOT contain "${A}"`};let s=new Set(["none","private_key_jwt"]);if("string"==typeof n.token_endpoint_auth_method){if(nl.has(n.token_endpoint_auth_method))return{valid:!1,error:`symmetric auth method "${n.token_endpoint_auth_method}" is prohibited for Client ID Metadata Document clients`};if(!s.has(n.token_endpoint_auth_method))return{valid:!1,error:'token_endpoint_auth_method must be "none" or "private_key_jwt" for Client ID Metadata Document clients'};if("private_key_jwt"===n.token_endpoint_auth_method&&!n.jwks&&!n.jwks_uri)return{valid:!1,error:"private_key_jwt requires either jwks or jwks_uri in the metadata document"}}if(n.jwks&&!(0,ni.l)(n.jwks).valid)return{valid:!1,error:"jwks must contain only structurally valid public keys"};if(n.jwks_uri)try{let A=new URL(n.jwks_uri);if(A.username||A.password)return{valid:!1,error:"jwks_uri must not contain credentials"};if(n.jwks_uri.includes("#"))return{valid:!1,error:"jwks_uri must not contain a fragment"}}catch{return{valid:!1,error:"jwks_uri must be a valid URL"}}if("mcp-2026-07-28"===t.metadataProfile&&!n.redirect_uris||n.redirect_uris&&!n.redirect_uris.every(A=>(function(A){try{let e=new URL(A);return"http:"===e.protocol||"https:"===e.protocol||(0,na.Y)(e)}catch{return!1}})(A)))return{valid:!1,error:"redirect_uris must be a non-empty array of absolute HTTP(S) or private-use URIs"};for(let A of["client_uri","logo_uri","tos_uri","policy_uri"]){if(void 0!==n[A]&&"string"!=typeof n[A])return{valid:!1,error:`${A} must be a string`};if("string"==typeof n[A])try{let e=new URL(n[A]);if("https:"!==e.protocol&&"http:"!==e.protocol)return{valid:!1,error:`${A} must use HTTP(S)`};if(e.username||e.password)return{valid:!1,error:`${A} must not contain credentials`};if(!(0,eo.$)(e.hostname))return{valid:!1,error:`${A} must not point to a private or reserved address`}}catch{return{valid:!1,error:`${A} is not a valid URL`}}}let o=t.originBoundFields??["post_logout_redirect_uris","client_uri"];try{r=new URL(A).origin}catch{return{valid:!1,error:"client_id is not a valid URL"}}for(let A of o){let e,t=n[A];if(void 0!==t){if("string"==typeof t)e=[t];else{if(!Array.isArray(t)||!t.every(A=>"string"==typeof A))return{valid:!1,error:`${A} must be a string or an array of strings`};e=t}for(let t of e){let e;try{e=new URL(t)}catch{return{valid:!1,error:`${A} contains an invalid URL: "${t}"`}}let i="redirect_uris"===A||"post_logout_redirect_uris"===A,n=i&&(0,na.Y)(e);if("https:"!==e.protocol&&"http:"!==e.protocol&&!n)return{valid:!1,error:`all values for ${A} must use HTTP(S) or a private-use scheme`};if(n&&("redirect_uris"===A||(0,na.a)(e)))continue;let a=i&&("http:"===e.protocol||"https:"===e.protocol)&&(0,eo.g)(e.hostname);if(e.origin!==r&&!a)return{valid:!1,error:`${A} value "${t}" must have the same origin as client_id (${r})`}}}}return a.push(...function(A){let e=[];try{let t=new URL(A);"/"===t.pathname&&e.push("client_id URL path / is NOT RECOMMENDED (§3)"),t.search&&e.push("client_id URL SHOULD NOT contain a query string (§3)")}catch{}return e}(A)),{valid:!0,metadata:{...n,token_endpoint_auth_method:n.token_endpoint_auth_method??"none"},...a.length>0?{warnings:a}:{}}}(e,l,{originBoundFields:t.originBoundFields,metadataProfile:t.metadataProfile});if(!g.valid)throw nh(g.error);for(let e of g.warnings??[])A.context.logger.warn(`cimd metadata document warning: ${e}`);return{status:"modified",metadata:g.metadata,cacheHeaders:d}}finally{clearTimeout(l)}}async function nf(A,e,t,r,i,n){let a=n?{...n}:void 0,s=await (0,nr.a)(A,i,{clientId:e,clientDiscoveryId:ng,metadata:{...t,client_id:t.client_id,redirect_uris:t.redirect_uris??[]},existingClient:n});if(s.created)try{await r.onClientCreated?.({client:s.client,clientMetadataDocument:t,context:A})}catch(e){A.context.logger.error("cimd onClientCreated notification failed",e)}else try{a&&await r.onClientRefreshed?.({client:s.client,previousClient:a,clientMetadataDocument:t,context:A})}catch(e){A.context.logger.error("cimd onClientRefreshed notification failed",e)}return s.client}function nm(A){return new nn.E("TOO_MANY_REQUESTS",{error:"temporarily_unavailable",error_description:A})}function nE(A,e){if(!Number.isInteger(A)||A<1)throw new g.p(`cimd metadataFetchPolicy.${e} must be a positive integer`);return A}function nw(A,e){let t=e-6e4,r=0;for(;r<A.length&&A[r]<=t;)r+=1;r>0&&A.splice(0,r)}function ny(A){if("string"!=typeof A||!/^\d+$/.test(A))return null;let e=Number(A);return Number.isSafeInteger(e)?e:null}var nQ=A.i(300794),nB=A.i(743698),nD=A.i(761095),nk=A.i(81111);let nS=new Set([204,205,304]),nb=async(A,e)=>{let t=new Request(A,e),r=new URL(t.url);if("https:"!==r.protocol)throw TypeError("CIMD Node transport requires an HTTPS URL");if("GET"!==t.method&&"HEAD"!==t.method)throw TypeError("CIMD Node transport supports only GET and HEAD");let i=await (0,nQ.lookup)(r.hostname,{all:!0,verbatim:!0});if(0===i.length)throw TypeError("metadata hostname returned no DNS addresses");for(let A of i)if(!(0,eo.$)(A.address))throw TypeError("metadata hostname must resolve only to public-routable addresses");let n=i[0],a=Object.fromEntries(t.headers.entries());a.host=r.host;let s=e?.signal??(A instanceof Request?A.signal:t.signal);return new Promise((A,e)=>{let i=(0,nB.request)(r,{agent:!1,headers:a,method:t.method,servername:0===(0,nD.isIP)(r.hostname.replace(/^\[|\]$/g,""))?r.hostname:void 0,signal:s,lookup:(A,e,t)=>{e.all?t(null,[n]):t(null,n.address,n.family)}},r=>{let i=r.statusCode??500,n="HEAD"===t.method||nS.has(i)?null:nk.Readable.toWeb(r);try{A(new Response(n,{headers:function(A){let e=new Headers;for(let[t,r]of Object.entries(A))if(Array.isArray(r))for(let A of r)e.append(t,A);else void 0!==r&&e.append(t,r);return e}(r.headers),status:i,statusText:r.statusMessage}))}catch(A){r.destroy(),e(A)}});i.once("error",e),i.end()})};var nM=A.i(480416),nO=ne,nv=ne,nR=ne;let nH="/.well-known/oauth-protected-resource",nN=new Set(["openid","profile","email","phone","address","offline_access"]),nT=A=>"string"==typeof A?A:A.identifier;var nL=A.i(394110),nU=A.i(656057),n_=A.i(36616),nP=A.i(969068);function nG(A){let e=A.context.options.baseURL;return"string"==typeof e?e||"better-auth:session-cache":A.context.baseURL||"better-auth:session-cache"}async function nx(A,e,t){let r=(0,tX.f)(e).kid;if(!r)return A.context.logger.debug("Cookie-cache JWT missing kid in header"),null;let i=await (0,nL.i)(A.context.adapter,t).getAllKeys(A);if(!i?.length)return A.context.logger.debug("No JWKS keys available for cookie-cache JWT"),null;let n=i.find(A=>A.id===r);if(!n)return A.context.logger.debug(`No JWKS key found for cookie-cache JWT kid: ${r}`),null;let a=n.alg??(0,nL.V)(t);return{alg:a,publicKey:await (0,tY.g)(JSON.parse(n.publicKey),a)}}async function nJ(A,e,t,r){let i=await (0,nU.L)(A,r);if(!i)throw new g.p("`jwt({ sessionCookieCache: true })` requires locally managed JWT plugin keys and does not support `jwt.sign`.");return await new nP.f({...e,sid:e.session.token}).setProtectedHeader({alg:i.alg,kid:i.kid,typ:n_.Y}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).setIssuer(nG(A)).setAudience(n_.H).setSubject(e.user.id).sign(i.privateKey)}async function nj(A,e,t){try{if("better-auth.session-cache+jwt"!==(0,tX.f)(e).typ)return null;let r=await nx(A,e,t);if(!r)return null;let{payload:i}=await (0,e6.f)(e,r.publicKey,{...(0,n_.V)({issuer:nG(A)}),algorithms:[r.alg]}),n=(0,n_.R)(i);if(!n)return null;return{payload:n,expiresAt:n.exp?1e3*n.exp:Date.now()}}catch(e){return A.context.logger.debug("Cookie-cache JWT verification failed",e),null}}let nY={jwks:{fields:{publicKey:{type:"string",required:!0},privateKey:{type:"string",required:!0},createdAt:{type:"date",required:!0},expiresAt:{type:"date",required:!1},alg:{type:"string",required:!1},crv:{type:"string",required:!1}}}};async function nF(A,e){let t=(0,eA.g)();try{let r=A.split(".");if(3!==r.length)return null;let i=new TextDecoder().decode(d.t.decode(r[0])),n=JSON.parse(i).kid;if(!n)return t.context.logger.debug("JWT missing kid in header"),null;let a=await (0,nL.i)(t.context.adapter,e).getAllKeys(t);if(!a||0===a.length)return t.context.logger.debug("No JWKS keys available"),null;let s=a.find(A=>A.id===n);if(!s)return t.context.logger.debug(`No JWKS key found for kid: ${n}`),null;let o=JSON.parse(s.publicKey),l=s.alg??(0,nL.V)(e),c=await (0,tY.g)(o,l),u="string"==typeof t.context.options.baseURL?t.context.options.baseURL:void 0,g=e?.jwt?.issuer??u,h=e?.jwt?.audience??u;g&&h||t.context.logger.warn("[better-auth] The JWT plugin is verifying a JWT without checking its issuer or audience because no base URL was resolved for this call. Set `baseURL`, or `jwt.issuer` and `jwt.audience` in the JWT plugin options.");let{payload:I}=await (0,e6.f)(A,c,{issuer:g,audience:h,algorithms:[l]});if(!I.sub||!I.aud)return null;return I}catch(A){return t.context.logger.debug("JWT verification failed",A),null}}let nz=y.object({payload:y.record(y.string(),y.any()),overrideOptions:y.record(y.string(),y.any()).optional()}),nq=y.object({token:y.string(),issuer:y.string().optional()});var nV=A.i(358307);function nK(){throw new g.E("BAD_REQUEST",{error:"invalid_grant",error_description:"The MCP authorization is inactive. Authorize this application again."})}function nW(A,e){return async t=>{let r;try{r=JSON.parse(t.value)}catch{return}if(r?.type!=="authorization_code")return;let i=r.resource??r.query?.resource;(Array.isArray(i)?i.includes(e.resource):i===e.resource)||nK(),("string"!=typeof r.userId||"string"!=typeof r.query?.client_id)&&nK();let n=await A.oauthClient.findUnique({where:{clientId:r.query.client_id}}),a=await A.mcpAuthorization.create({data:{id:(0,i8.randomUUID)(),authorizationCodeId:t.identifier,userId:r.userId,clientId:r.query.client_id,clientName:n?.name??r.query.client_id,scopes:r.query.scope??""}});return{data:{...t,value:JSON.stringify({...r,referenceId:a.id})}}}}function n$(A,e){var t;let r,i,n=[...nV.n,"offline_access"];return[(A=>{if(A?.jwt?.sign&&!A.jwks?.remoteUrl)throw new g.p("options.jwks.remoteUrl must be set when using options.jwt.sign");if(A?.jwks?.remoteUrl&&!A.jwks?.keyPairConfig?.alg)throw new g.p("options.jwks.keyPairConfig.alg must be specified when options.jwks.remoteUrl is used for OpenID metadata");let e=A?.jwks?.jwksPath??"/jwks";if("string"!=typeof e||0===e.length||!e.startsWith("/")||e.includes(".."))throw new g.p("options.jwks.jwksPath must be a non-empty string starting with '/' and not contain '..'");return{id:"jwt",version:is.f,options:A,init(e){if(!A?.sessionCookieCache)return;if(e.options.session?.cookieCache?.strategy!=="jwt")throw new g.p('`jwt({ sessionCookieCache: true })` requires `session.cookieCache.strategy = "jwt"`.');if(A.jwt?.sign)throw new g.p("`jwt({ sessionCookieCache: true })` requires locally managed JWT plugin keys and does not support `jwt.sign`.");let t=A.jwks?.gracePeriod,r=e.options.session.cookieCache.maxAge||300;return void 0!==t&&r>t&&e.logger.warn(`[better-auth] \`session.cookieCache.maxAge\` (${r}s) exceeds the JWT plugin JWKS grace period (${t}s). Rotated keys may stop verifying cookie-cache JWTs before the cookie expires.`),{context:{sessionConfig:{...e.sessionConfig,cookieCacheSigner:{sign:(e,t,r)=>nJ(e,t,r,A),verify:(e,t)=>nj(e,t,A)}}}}},endpoints:{getJwks:(0,l.g)(e,{method:"GET",metadata:{openapi:{operationId:"getJSONWebKeySet",description:"Get the JSON Web Key Set",responses:{200:{description:"JSON Web Key Set retrieved successfully",content:{"application/json":{schema:{type:"object",properties:{keys:{type:"array",description:"Array of public JSON Web Keys",items:{type:"object",properties:{kid:{type:"string",description:"Key ID uniquely identifying the key, corresponds to the 'id' from the stored Jwk"},kty:{type:"string",description:"Key type (e.g., 'RSA', 'EC', 'OKP')"},alg:{type:"string",description:"Algorithm intended for use with the key (e.g., 'EdDSA', 'RS256')"},use:{type:"string",description:"Intended use of the public key (e.g., 'sig' for signature)",enum:["sig"],nullable:!0},n:{type:"string",description:"Modulus for RSA keys (base64url-encoded)",nullable:!0},e:{type:"string",description:"Exponent for RSA keys (base64url-encoded)",nullable:!0},crv:{type:"string",description:"Curve name for elliptic curve keys (e.g., 'Ed25519', 'P-256')",nullable:!0},x:{type:"string",description:"X coordinate for elliptic curve keys (base64url-encoded)",nullable:!0},y:{type:"string",description:"Y coordinate for elliptic curve keys (base64url-encoded)",nullable:!0}},required:["kid","kty","alg"]}}},required:["keys"]}}}}}}}},async e=>{if(A?.jwks?.remoteUrl)throw new g.E("NOT_FOUND");let t=(0,nL.i)(e.context.adapter,A),r=await t.getAllKeys(e);if(r&&r?.length!==0||(await (0,ns.K)(e,A),r=await t.getAllKeys(e)),!r?.length)throw new g.p("No key sets found. Make sure you have a key in your database.");let i=Date.now(),n=(A?.jwks?.gracePeriod??2592e3)*1e3,a=r.filter(A=>!A.expiresAt||A.expiresAt.getTime()+n>i),s=A?.jwks?.keyPairConfig,o=s&&"crv"in s?s.crv:void 0;return e.json({keys:a.map(e=>({alg:e.alg??(0,nL.V)(A),crv:e.crv??o,...JSON.parse(e.publicKey),kid:e.id}))})}),getToken:(0,l.g)("/token",{method:"GET",requireHeaders:!0,use:[h.Z],metadata:{openapi:{operationId:"getJSONWebToken",description:"Get a JWT token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{let t=await (0,nU.d)(e,A);return e.json({token:t})}),signJWT:l.g.serverOnly({method:"POST",metadata:{$Infer:{body:{}}},body:nz},async e=>{let t=await (0,nU.X)(e,{options:{...A,...e.body.overrideOptions},payload:e.body.payload});return e.json({token:t})}),verifyJWT:l.g.serverOnly({method:"POST",metadata:{$Infer:{body:{},response:{}}},body:nq},async e=>{let t=e.body.issuer?{...A,jwt:{...A?.jwt,issuer:e.body.issuer}}:A,r=await nF(e.body.token,t);return e.json({payload:r})})},hooks:{after:[{matcher:A=>"/get-session"===A.path,handler:(0,l.a)(async e=>{if(A?.disableSettingJwtHeader)return;let t=e.context.session||e.context.newSession;if(t&&t.session){let t=await (0,nU.d)(e,A),r=new Set((e.context.responseHeaders?.get("access-control-expose-headers")||"").split(",").map(A=>A.trim()).filter(Boolean));r.add("set-auth-jwt"),e.setHeader("set-auth-jwt",t),e.setHeader("Access-Control-Expose-Headers",Array.from(r).join(", "))}})}]},schema:(0,m.C)(nY,A?.schema)}})({jwt:{issuer:e.issuer,audience:e.resource}}),(A=>{var e;let t,r,{resource:i,refreshTokenReuseInterval:n=30,...a}=A,s=function(A){var e;let t,r,i;if("string"!=typeof A)throw TypeError("MCP resource must be a single URL string");try{t=new URL(A)}catch{throw TypeError("MCP resource must be an absolute URL")}if(t.username||t.password)throw TypeError("MCP resource URL must not contain credentials");if(A.includes("#"))throw TypeError("MCP resource URL must not contain a fragment");if(A.includes("?"))throw TypeError("MCP resource URL must not contain a query; to protect a query-carrying resource, verify tokens with verifyAccessTokenRequest and build challenges with createResourceServerChallenge");if("https:"!==t.protocol&&!("http:"===t.protocol&&(i=4===(r=(e=t.hostname).split(".")).length&&"127"===r[0]&&r.every(A=>/^\d+$/.test(A)&&255>=Number(A)),"localhost"===e||"[::1]"===e||i)))throw TypeError("MCP resource URL must use HTTPS, except for localhost or loopback IP development URLs");return A}(i),o=(0,nR.i)({refreshTokenReuseInterval:n,...a,resources:(e=a.resources,(t=e??[]).some(A=>nT(A)===s)?t:[...t,s]),clientRegistrationDefaultResources:(r=a.clientRegistrationDefaultResources,r?.includes(s)?r:[...r??[],s])}),l=o.onRequest;return{...o,onRequest:async(A,e)=>{var t;let r,i,n,o,c=await l?.(A,e);if(c)return c;let d=new URL(A.url).pathname,u=e.options.advanced?.skipTrailingSlashes?d.replace(/\/+$/,"")||"/":d,g="";try{g=new URL(s).pathname.replace(/\/$/,"")}catch{g=""}if(!(new Set([nH,`${nH}${g}`])).has(u))return;if("GET"!==A.method&&"HEAD"!==A.method)return{response:new Response(null,{status:405,headers:{Allow:"GET, HEAD"}})};let h=(0,nv.d)((t={context:e},r=(a.advertisedMetadata?.scopes_supported??a.scopes??[]).filter(A=>!nN.has(A)),n="object"==typeof(i=a.resources?.find(A=>nT(A)===s))&&!0===i.dpopBoundAccessTokensRequired,o={resource:s,authorization_servers:[(0,nO.t)(t,a)],bearer_methods_supported:["header"],dpop_signing_alg_values_supported:[...a.dpop?.signingAlgorithms??nM.G]},n&&(o.dpop_bound_access_tokens_required=!0),r.length&&(o.scopes_supported=[...r]),o));return"HEAD"===A.method?{response:new Response(null,{status:h.status,headers:h.headers})}:{response:h}}}})({loginPage:"/mcp/sign-in",consentPage:"/mcp/consent",resource:e.resource,scopes:n,resources:[{identifier:e.resource,allowedScopes:n,accessTokenTtl:300,refreshTokenTtl:2592e3}],grantTypes:["authorization_code","refresh_token"],accessTokenExpiresIn:300,refreshTokenExpiresIn:2592e3,refreshTokenReuseInterval:0,clientRegistrationDefaultScopes:["mcp:read"],clientRegistrationAllowedScopes:n,allowDynamicClientRegistration:e.dcrEnabled,allowUnauthenticatedClientRegistration:e.dcrEnabled,clientRegistrationDefaultApplicationType:"infer",extensions:[{claims:{accessToken:async({user:t,client:r,referenceId:i,resources:n,scopes:a})=>{t&&i&&n?.includes(e.resource)||nK();let s=await A.mcpAuthorization.findFirst({where:{id:i,userId:t.id,clientId:r.clientId,revokedAt:null,user:{is:{id:t.id}}}});return(!s||a.some(A=>!s.scopes.split(" ").includes(A)))&&nK(),{aide_mcp_authorization_id:s.id}}}}]}),(r=function(A){let e,t=A.metadataRevalidationInterval??"60m",r=A.maxCacheEntries??1e3;if(!Number.isInteger(r)||r<1)throw new g.p("cimd maxCacheEntries must be a positive integer");let i=(e=A.metadataFetchPolicy,{minimumFetchIntervalMs:function(A,e){if("number"==typeof A){if(!Number.isFinite(A)||A<0)throw new g.p(`cimd metadataFetchPolicy.${e} must be a non-negative number of seconds or duration string`);return 1e3*A}try{let e=Math.floor(Date.now()/1e3),t=((0,ns.x)(A,e)-e)*1e3;if(!Number.isFinite(t)||t<0)throw Error("negative duration");return t}catch{throw new g.p(`cimd metadataFetchPolicy.${e} must be a non-negative number of seconds or duration string`)}}(e?.minimumFetchInterval??1,"minimumFetchInterval"),maximumConcurrentFetches:nE(e?.maximumConcurrentFetches??16,"maximumConcurrentFetches"),maximumConcurrentFetchesPerOrigin:nE(e?.maximumConcurrentFetchesPerOrigin??4,"maximumConcurrentFetchesPerOrigin"),maximumFetchesPerMinute:nE(e?.maximumFetchesPerMinute??120,"maximumFetchesPerMinute"),maximumFetchesPerOriginPerMinute:nE(e?.maximumFetchesPerOriginPerMinute??30,"maximumFetchesPerOriginPerMinute")}),n=new Map,a=new Map,s=new Map,o=new Map,l=[],c=0;return async(e,d,u)=>{if(!nc(d))return null;let h=e.context.getPlugin("oauth-provider");if(!h)throw new g.p("cimd discovery invoked without the oauth-provider plugin installed");let I=h.options,p=(A=>{let e=n.get(A);if(e)return n.delete(A),n.set(A,e),e})(d),C=Date.now();if(p&&p.expiresAt>C)return u||nf(e,d,p.metadata,A,I);let f=a.get(d);if(void 0!==f)return f;let m=(A=>{let e=Date.now(),t=s.get(A);if(i.minimumFetchIntervalMs>0&&void 0!==t&&e-t<i.minimumFetchIntervalMs)throw nm("metadata document fetch is within the per-client minimum interval");if(!s.has(A))for(;s.size>=r;){let A=!1;for(let[t,r]of s)if(!a.has(t)&&(!(i.minimumFetchIntervalMs>0)||!(e-r<i.minimumFetchIntervalMs))){s.delete(t),A=!0;break}if(!A)throw nm("metadata fetch client state is at capacity")}let n=((A,e)=>{let t=o.get(A);if(t)return nw(t.fetchStartTimesMs,e),o.delete(A),o.set(A,t),t;for(;o.size>=r;){let A=!1;for(let[t,r]of o)if(nw(r.fetchStartTimesMs,e),!(r.activeFetchCount>0)&&!(r.fetchStartTimesMs.length>0)){o.delete(t),A=!0;break}if(!A)throw nm("metadata fetch origin state is at capacity")}let i={activeFetchCount:0,fetchStartTimesMs:[]};return o.set(A,i),i})(new URL(A).origin,e);if(nw(l,e),c>=i.maximumConcurrentFetches)throw nm("global metadata fetch concurrency limit exceeded");if(n.activeFetchCount>=i.maximumConcurrentFetchesPerOrigin)throw nm("metadata fetch concurrency limit exceeded for client origin");if(l.length>=i.maximumFetchesPerMinute)throw nm("global metadata fetch rate limit exceeded");if(n.fetchStartTimesMs.length>=i.maximumFetchesPerOriginPerMinute)throw nm("metadata fetch rate limit exceeded for client origin");s.delete(A),s.set(A,e),l.push(e),n.fetchStartTimesMs.push(e),c+=1,n.activeFetchCount+=1;let d=!1;return()=>{d||(d=!0,c-=1,n.activeFetchCount-=1)}})(d),E=(async()=>{let i,a=await nC(e,d,A,p?{etag:p.etag,lastModified:p.lastModified}:void 0);if("not-modified"===a.status&&!p)throw g="Metadata document returned 304 without a validated cached document",new nn.E("BAD_REQUEST",{error:"invalid_client",error_description:g});let o="modified"===a.status?a.metadata:p.metadata,l=await nf(e,d,o,A,I,u??void 0),c=(i=function(A,e,t){let{directives:r,duplicates:i}=function(A){let e=new Map,t=new Set;for(let r of A?.split(",")??[]){let[A,...i]=r.trim().split("="),n=A?.toLowerCase();if(!n)continue;e.has(n)&&t.add(n);let a=i.join("=").trim();e.set(n,!a||a.replace(/^"|"$/g,""))}return{directives:e,duplicates:t}}(A.cacheControl),n=A.vary?.split(",").some(A=>"*"===A.trim());if(r.has("no-store")||r.has("private")||n)return{cacheable:!1,expiresAt:t};let a=function(A,e){if("number"==typeof A)return Math.max(0,1e3*A);let t=Math.floor(e/1e3);return Math.max(0,((0,ns.x)(A,t)-t)*1e3)}(e,t);if(r.has("no-cache"))return{cacheable:!0,expiresAt:t};let s=ny(A.age)??0,o=A.date?Date.parse(A.date):t,l=Math.max(Number.isFinite(o)?Math.max(0,t-o):0,1e3*s),c=null,d=r.has("s-maxage"),u=ny(r.get("s-maxage")),g=r.has("max-age"),h=ny(r.get("max-age")),I=d?null===u||i.has("s-maxage"):g&&(null===h||i.has("max-age")),p=d?u:h;if(I)c=0;else if(null!==p)c=Math.max(0,1e3*p-l);else if(A.expires){let e=Date.parse(A.expires);Number.isFinite(e)&&(c=Math.max(0,e-(Number.isFinite(o)?o:t)-l))}return{cacheable:!0,expiresAt:t+Math.min(a,c??a)}}(f="modified"===a.status?a.cacheHeaders:(h=p.responseCacheHeaders,{cacheControl:(C=a.cacheHeaders).cacheControl??h.cacheControl,vary:C.vary??h.vary,expires:C.expires??h.expires,date:C.date??h.date,age:C.age??h.age,etag:C.etag??h.etag,lastModified:C.lastModified??h.lastModified}),t,Date.now())).cacheable?{metadata:o,expiresAt:i.expiresAt,etag:f.etag,lastModified:f.lastModified,responseCacheHeaders:f}:null;if(c){var g,h,C,f;for(n.delete(d);n.size>=r;){let A=n.keys().next().value;if("string"!=typeof A)break;n.delete(A)}n.set(d,c)}else n.delete(d);return s.delete(d),l})();a.set(d,E);try{return await E}catch(A){throw s.delete(d),s.set(d,Date.now()),A}finally{a.get(d)===E&&a.delete(d),m()}}}(t={fetchClientMetadataResource:nb,metadataProfile:"mcp-2026-07-28"}),i={id:ng,matches:nc,resolve:r,fetchClientMetadataResource:t.fetchClientMetadataResource,discoveryMetadata:{client_id_metadata_document_supported:!0}},{id:"cimd",version:"1.7.16",init(A){(0,nA.L)(A,{clientDiscovery:i})}})]}A.s(["y",0,n$,"K",0,nW],9416);let nZ={user:["create","list","set-password","set-email","get","update"],session:["list","revoke","delete"]},nX=(0,D.y)(nZ),n0=nX.newRole(nZ),n1=null;function n4(){return n1||(n1=(0,ij.U)().then(A=>(function(A,e=iq(),t=(0,i7.getMcpOAuthConfig)()){var r;let i,n,a,s,d,u=e.provider,I=(0,iJ.J)(e.origins),p=u?.providerId.toLowerCase()==="github"?u.userInfoUrl:void 0,Q=iK(e.mode)&&u?(A=>{let e=new Set,t=new Set;for(let r of A.config){let A=r.providerId;e.has(A)&&t.add(A),e.add(A)}t.size>0&&console.warn(`Duplicate provider IDs found: ${Array.from(t).join(", ")}`);let r=async(A,e,t)=>{let r=[];for(let i of A){let A,n,a=i.authorizationUrl,s=i.tokenUrl,o=i.userInfoUrl,l=i.endSessionEndpoint,c=!1;if(i.discoveryUrl){let r=await i_(i.discoveryUrl,i.discoveryHeaders,t).catch(A=>(e.logger.error(`Discovery fetch failed for "${i.providerId}": ${A}`),null));if(r){a??=r.authorization_endpoint,s??=r.token_endpoint,o??=r.userinfo_endpoint,l??=r.end_session_endpoint,A=r.issuer;let t=r.id_token_signing_alg_values_supported;if(c=Array.isArray(t)&&t.length>0,r.jwks_uri&&r.issuer){let A;try{A=new URL(r.jwks_uri,i.discoveryUrl)}catch{e.logger.error(`Provider "${i.providerId}": invalid jwks_uri "${r.jwks_uri}" in discovery document. Provider skipped.`);continue}n={jwks:(0,tW.R)(A),issuer:r.issuer,audience:i.clientId,algorithms:c?t:void 0}}}if(!a||!s&&!i.getToken){e.logger.error(`Provider "${i.providerId}": discovery left no usable authorization endpoint or token exchange. Provider skipped.`);continue}}if(i.requireIdTokenVerification&&!n){if(i.discoveryUrl){e.logger.error(`Provider "${i.providerId}": requires verified ID tokens, but discovery did not provide a usable issuer and jwks_uri. Provider skipped.`);continue}throw Error(`Provider "${i.providerId}": requires verified ID tokens, but discovery did not provide a usable issuer and jwks_uri.`)}let d=i.tokenEndpointAuth;if(i.clientSecret&&(d?.method==="private_key_jwt"||d?.method==="none"))throw Error(`Provider "${i.providerId}": tokenEndpointAuth.method "${d?.method}" cannot be combined with clientSecret`);if(!i.clientSecret&&(d?.method==="client_secret_basic"||d?.method==="client_secret_post"))throw Error(`Provider "${i.providerId}": tokenEndpointAuth.method "${d?.method}" requires clientSecret`);if(!i.clientSecret&&!d&&"basic"===i.authentication)throw Error(`Provider "${i.providerId}": authentication "basic" requires clientSecret`);let u=async(A,e)=>{let t=i.getUserInfo?await i.getUserInfo(A):await iP(A,o,e);if(!t)return null;let r=!i.getUserInfo||null!=t.sub;if(e?.sub!==void 0&&r&&String(t.sub)!==e.sub)return null;let n=i.mapProfileToUser?await i.mapProfileToUser(t):{},a={email:t.email,emailVerified:e1(t.emailVerified),image:t.image,name:t.name,...n};return{user:{...a,image:a.image??void 0},data:t}},h=i.accountSubject,I={id:i.providerId,name:i.name??i.providerId,issuer:A,accountSubject:({tokens:A,profile:e})=>h?h({tokens:A,profile:e}):c?n&&A.idToken?iU(A.idToken)?.sub??"":e.sub??"":e.id??"",idToken:n,requiresIdTokenNonce:void 0!==n&&!0!==i.disableIdTokenNonceBinding,allowIdpInitiated:i.allowIdpInitiated,async createEndSessionURL(A){let t;if(i.disableProviderLogout||!l)return null;try{t=new URL(l)}catch{return null}A.idToken&&t.searchParams.set("id_token_hint",A.idToken);let r=A.postLogoutRedirectURI??i.postLogoutRedirectURI,n=r?new URL(r,e.baseURL).toString():void 0;return n?(t.searchParams.set("post_logout_redirect_uri",n),t.searchParams.set("client_id",i.clientId),A.state&&t.searchParams.set("state",A.state)):A.idToken||t.searchParams.set("client_id",i.clientId),t},createAuthorizationURL(A){if(!a)throw g.E.from("BAD_REQUEST",iL.INVALID_OAUTH_CONFIGURATION);return tw({id:i.providerId,options:{clientId:i.clientId,clientSecret:i.clientSecret,redirectURI:i.redirectURI},authorizationEndpoint:a,state:A.state,codeVerifier:i.pkce??!0?A.codeVerifier:void 0,scopes:(()=>{let e=[...A.scopes??[],...i.scopes??[]];return c&&!e.includes("openid")&&e.unshift("openid"),e})(),redirectURI:A.redirectURI,prompt:i.prompt,accessType:i.accessType,responseType:i.responseType,responseMode:i.responseMode,nonce:A.idTokenNonce,additionalParams:{...i.authorizationUrlParams??{},...A.additionalParams??{}},loginHint:A.loginHint})},async validateAuthorizationCode(A){if(i.getToken)return(0,tr.O)(await i.getToken(A),i.accessTokenExpiresIn);if(!s)throw g.E.from("BAD_REQUEST",iL.TOKEN_URL_NOT_FOUND);let e=await tJ({headers:i.authorizationHeaders,code:A.code,codeVerifier:i.pkce??!0?A.codeVerifier:void 0,redirectURI:A.redirectURI,options:{clientId:i.clientId,clientSecret:i.clientSecret,redirectURI:i.redirectURI},tokenEndpoint:s,authentication:i.authentication,tokenEndpointAuth:d,additionalParams:i.tokenUrlParams});return(0,tr.O)(e,i.accessTokenExpiresIn)},async getUserInfoFromIdToken(A){let e=I.idToken?iU(A):void 0;return null===e?null:u({idToken:A},e)},async getUserInfo(A){let{expectedIdTokenNonce:t,...r}=A;if(!r.idToken||!I.idToken)return u(r);let n=await tb(I,r.idToken,t)?iU(r.idToken):null;return n?u(r,n):(e.logger.error(`Provider "${i.providerId}": id_token failed verification against the discovery JWKS or expected nonce`),null)},async refreshAccessToken(A,e){if(!s)throw g.E.from("BAD_REQUEST",iL.TOKEN_URL_NOT_FOUND);let t="function"==typeof i.refreshTokenParams?await i.refreshTokenParams(e):i.refreshTokenParams,r=await tG({refreshToken:A,options:{clientId:i.clientId,clientSecret:i.clientSecret},authentication:i.authentication,tokenEndpointAuth:d,tokenEndpoint:s,extraParams:t});return(0,tr.O)(r,i.accessTokenExpiresIn)},disableImplicitSignUp:i.disableImplicitSignUp,disableSignUp:i.disableSignUp,options:{disableSignUp:i.disableSignUp,overrideUserInfoOnSignIn:i.overrideUserInfo,requireEmailVerification:i.requireEmailVerification}};r.push(I)}return r},i=A=>{let e=A.body?.provider??A.body?.providerId??A.query?.provider??A.params?.id;return"string"==typeof e?e:void 0};return{id:"generic-oauth",version:is.f,init:async e=>{let t=await r(A.config,e),i=new Set(t.map(A=>A.id)),n=new Map(A.config.filter(A=>!i.has(A.providerId)).map(A=>[A.providerId,{config:A}])),a=new Set(e.socialProviders.map(A=>A.id));for(let A of t)a.has(A.id)&&e.logger.warn(`Generic OAuth provider "${A.id}" shadows a built-in social provider with the same ID`);return{context:{socialProviders:t.concat(e.socialProviders),genericOAuthPendingDiscovery:n}}},hooks:{before:[{matcher:A=>A.context.genericOAuthPendingDiscovery?.has(i(A)??"")===!0,handler:(0,l.a)(async A=>{await ((A,e)=>{let t=A.genericOAuthPendingDiscovery,i=t?.get(e);if(i)return i.attempt??=r([i.config],A,1e4).then(([r])=>{r&&(t?.delete(e),A.socialProviders.unshift(r))}).finally(()=>{i.attempt=void 0}),i.attempt})(A.context,i(A)??"")})}]},options:A,$ERROR_CODES:iL}})({config:[{providerId:u.providerId,clientId:u.clientId,clientSecret:u.clientSecret,scopes:u.scopes,discoveryUrl:u.discoveryUrl,authorizationUrl:u.authorizationUrl,tokenUrl:u.tokenUrl,userInfoUrl:u.userInfoUrl,getUserInfo:p?async A=>A.accessToken?i4(p,A.accessToken):null:void 0,pkce:!0,requireIdTokenVerification:u.requireIssuerValidation,disableImplicitSignUp:!1}]}):null;return((A,e)=>{let t=e(A).then(A=>{let e=A.options.advanced?.database?.validateSchema;A.checkSchema||!1===e||A.logger[!0===e?"warn":"debug"](`Schema validation is not available for adapter "${A.adapter.id}". Skipping schema validation. Database operations will proceed normally.`);let t=A.checkSchema?.();return t&&t.catch(e=>{A.logger.error(e instanceof Am._?e.message:"Could not validate the database schema. Check your database connection.")}),A}),{api:r}=rx(t,A),i=A.plugins?.reduce((A,e)=>e.$ERROR_CODES?{...A,...e.$ERROR_CODES}:A,{}),n=async e=>{let r,i=await t,n=i.options.basePath||"/api/auth";if((0,Aj._)(A.baseURL))r=await eu(i,e,ed(i.options));else{r=Object.create(Object.getPrototypeOf(i),Object.getOwnPropertyDescriptors(i));let A=i.options;if(!i.options.baseURL){let t=(0,Aj.X)(void 0,n,e,void 0,i.options.advanced?.trustedProxyHeaders);if(!t)throw new g.p("Could not get base URL from request. Please provide a valid base URL.");r.baseURL=t,r.options={...i.options,baseURL:(0,Aj.H)(t)||void 0},A=r.options}r.trustedOrigins=await ec(A,e),r.trustedProviders=await eh(A,e)}let{handler:a}=((A,e)=>{let t=(0,et.f)(e),{api:r,middlewares:i}=rx(A,e),n=new URL(A.baseURL).pathname;return(0,rG.f)(r,{routerContext:A,openapi:{disabled:!0},basePath:n,routerMiddleware:[{path:"/**",middleware:ek},...i],allowedMediaTypes:["application/json"],skipTrailingSlashes:e.advanced?.skipTrailingSlashes??!1,async onRequest(e){let r=A.options.disabledPaths||[],i=(0,ey.s)(e.url,n);if(r.includes(i))return new Response("Not Found",{status:404});let a=A.checkSchema?.();a&&await a;let s=e,o=await eT(s,A);if(o)return o;for(let e of A.options.plugins||[])if(e.onRequest){let r=await t(`onRequest ${e.id}`,{[ee.A]:"onRequest",[ee.s]:`plugin:${e.id}`},()=>e.onRequest(s,A));if(r&&"response"in r)return r.response;r&&"request"in r&&(s=r.request)}return s},async onResponse(e,r){for(let r of A.options.plugins||[])if(r.onResponse){let i=await t(`onResponse ${r.id}`,{[ee.A]:"onResponse",[ee.s]:`plugin:${r.id}`,[ee.h]:e.status},()=>r.onResponse(e,A));if(i)return i.response}return e},async onError(t){if((0,ew.f)(t)&&"FOUND"===t.status)return;if(e.onAPIError?.throw)throw t;if(e.onAPIError?.onError){try{await e.onAPIError.onError(t,A)}catch(e){A.logger.error("onAPIError.onError threw",e)}return}let r=e.logger?.level,i="error"===r||"warn"===r||"debug"===r?AQ.y:void 0;if(e.logger?.disabled!==!0){if(t&&"object"==typeof t&&"message"in t&&"string"==typeof t.message&&(t.message.includes("no column")||t.message.includes("column")||t.message.includes("relation")||t.message.includes("table")||t.message.includes("does not exist")))return void A.logger?.error(t.message);(0,ew.f)(t)?("INTERNAL_SERVER_ERROR"===t.status&&A.logger.error(t.status,t),i?.error(t.message)):A.logger?.error(t&&"object"==typeof t&&"name"in t?t.name:"",t)}}})})(r,A);return(0,A7.Q)(r.adapter,()=>a(e))};return{handler:n,fetch:n,api:r,options:A,$context:t,$ERROR_CODES:{...i,...eI.f}}})({appName:"AI Development Environment",baseURL:"object"==typeof I?{...I,protocol:"auto"}:I,disabledPaths:t?["/token"]:[],trustedOrigins:A=>{if(!A)return[];let t=(0,iJ.v)(A,e.trustProxyHeaders);return t&&(0,iJ.K)(e.origins,t)?[t]:[]},secret:e.secret,logger:{log:iX},hooks:{before:(0,l.a)(async A=>{let t=A.request?(0,iJ.v)(A.request,e.trustProxyHeaders):null,r=A.headers?.get("cookie")??"",i=t?"https:"===new URL(t).protocol:!!/(?:^|;\s*)__Secure-better-auth\.session_token=/.test(r)||!/(?:^|;\s*)better-auth\.session_token=/.test(r)&&void 0,n={...A.context.options,advanced:{...A.context.options.advanced,useSecureCookies:i}};A.context.authCookies=(0,A4.e)(n),A.context.createAuthCookie=(0,A4.g)(n)})},advanced:{trustedProxyHeaders:e.trustProxyHeaders},database:(r={provider:"sqlite"},i=null,n=(A,e=!1)=>({getFieldName:t,getModelName:i,getFieldAttributes:n,getDefaultModelName:a,schema:s})=>{let o=(A,e,r)=>{if(!A&&!r)return;let i={};if(A)for(let r of A)i[t({model:e,field:r})]=!0;if(r){if(!A){let A=s[a(e)]?.fields||{};for(let r of(A.id={type:"string"},Object.keys(A)))i[t({model:e,field:r})]=!0}for(let[A,t]of Object.entries(r)){let r=l(e,t.modelKey??A,s);"one-to-one"===t.relation?i[r]=!0:i[r]={take:t.limit}}}return i},l=(A,e,t)=>{try{let n=a(A),s=a(e),o=i(e).toLowerCase(),l=Object.entries(t[s]?.fields||{}).filter(([A,e])=>e.references&&a(e.references.model)===n);if(l.length>0){let[A,e]=l[0];return e?.unique===!0||!0===r.usePlural?o:`${o}s`}if((l=Object.entries(t[n]?.fields||{}).filter(([A,e])=>e.references&&a(e.references.model)===s)).length>0)return o}catch{}return`${i(e).toLowerCase()}s`};function c(A){switch(A){case"starts_with":return"startsWith";case"ends_with":return"endsWith";case"ne":return"not";case"not_in":return"notIn";default:return A}}let d=({action:A,model:e,where:i})=>{if(!i||!i.length)return{};let a=A=>{let i=t({model:e,field:A.field}),a=(A.mode??"sensitive")==="insensitive"&&("string"==typeof A.value||Array.isArray(A.value)&&A.value.every(A=>"string"==typeof A)),s="postgresql"===r.provider||"mongodb"===r.provider,o=a&&s?"insensitive":void 0,l=o?{mode:o}:{};if("ne"===A.operator&&null===A.value)return n({model:e,field:A.field})?.required!==!0?{[i]:{not:null}}:{};if(("in"===A.operator||"not_in"===A.operator)&&Array.isArray(A.value)){let e=A.value.filter(A=>null!=A);if(0===e.length)if("in"===A.operator)return{AND:[{[i]:{equals:"__never__"}},{[i]:{not:"__never__"}}]};else return{};return{[i]:{[c(A.operator)]:e,...l}}}return"eq"!==A.operator&&A.operator?"ne"===A.operator?{[i]:{not:{equals:A.value},...l}}:{[i]:{[c(A.operator)]:A.value,...l}}:{[i]:{equals:A.value,...l}}};if("update"===A){let A=i.filter(A=>"AND"===A.connector||!A.connector),r=i.filter(A=>"OR"===A.connector),n=A.filter(A=>"eq"===A.operator||!A.operator),s=A.filter(A=>"eq"!==A.operator&&void 0!==A.operator).map(A=>a(A)),o=r.map(A=>a(A)),l={};for(let A of n)l[t({model:e,field:A.field})]=A.value;return s.length>0&&(l.AND=s),o.length>0&&(l.OR=o),l}if("delete"===A){let A=i.find(A=>"id"===A.field);if(A){let r=t({model:e,field:"id"}),n=i.filter(A=>"id"!==A.field);if(0===n.length)return{[r]:A.value};let s=n.filter(A=>"AND"===A.connector||!A.connector),o=n.filter(A=>"OR"===A.connector),l=s.map(A=>a(A)),c=o.map(A=>a(A)),d={[r]:A.value};return l.length>0&&(d.AND=l),c.length>0&&(d.OR=c),d}}if(1===i.length){let A=i[0];if(!A)return;return a(A)}let s=i.filter(A=>"AND"===A.connector||!A.connector),o=i.filter(A=>"OR"===A.connector),l=s.map(A=>a(A)),d=o.map(A=>a(A));return{...l.length?{AND:l}:{},...d.length?{OR:d}:{}}};return{async create({model:e,modelKey:t=e,data:r,select:i}){if(!A[e])throw new g.p(`Model ${e} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);return await A[e].create({data:r,select:o(i,t)})},async findOne({model:e,modelKey:t=e,where:r,select:i,join:n}){let a=d({model:t,where:r,action:"findOne"});if(!A[e])throw new g.p(`Model ${e} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let c=new Map;for(let[A,e]of Object.entries(n??{})){let r=l(t,e.modelKey??A,s);c.set(r,A)}let u=o(i,t,n),h=await A[e].findFirst({where:a,select:u});if(n&&h)for(let[A,e]of c.entries())A!==e&&A in h&&(h[e]=h[A],delete h[A]);return h},async findMany({model:e,modelKey:r=e,where:i,limit:n,select:a,offset:c,sortBy:u,join:h}){let I=d({model:r,where:i,action:"findMany"});if(!A[e])throw new g.p(`Model ${e} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let p=new Map;if(h)for(let[A,e]of Object.entries(h)){let t=l(r,e.modelKey??A,s);p.set(t,A)}let C=o(a,r,h),f=await A[e].findMany({where:I,take:n||100,skip:c||0,...u?.field?{orderBy:{[t({model:r,field:u.field})]:"desc"===u.direction?"desc":"asc"}}:{},select:C});if(h&&Array.isArray(f))for(let A of f)for(let[e,t]of p.entries())e!==t&&e in A&&(A[t]=A[e],delete A[e]);return f},async count({model:e,modelKey:t=e,where:r}){let i=d({model:t,where:r,action:"count"});if(!A[e])throw new g.p(`Model ${e} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);return await A[e].count({where:i})},async update({model:e,modelKey:t=e,where:i,update:a}){if(!A[e])throw new g.p(`Model ${e} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);if(!(i?.length&&i.some(A=>{if("OR"===A.connector||A.operator&&"eq"!==A.operator)return!1;if("insensitive"===A.mode){let e="postgresql"===r.provider||"mongodb"===r.provider,t="string"==typeof A.value||Array.isArray(A.value)&&A.value.every(A=>"string"==typeof A);if(e&&t)return!1}return"id"===A.field||n({model:t,field:A.field})?.unique===!0}))){let r=d({model:t,where:i,action:"updateMany"});return(await A[e].updateMany({where:r,data:a}))?.count?await A[e].findFirst({where:r}):null}let s=d({model:t,where:i,action:"update"});try{return await A[e].update({where:s,data:a})}catch(A){if(Aw(A))return null;throw A}},async updateMany({model:e,modelKey:t=e,where:r,update:i}){if(!A[e])throw new g.p(`Model ${e} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let n=d({model:t,where:r,action:"updateMany"}),a=await A[e].updateMany({where:n,data:i});return a?a.count:0},async delete({model:e,modelKey:t=e,where:r}){if(!A[e])throw new g.p(`Model ${e} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);if(!r?.some(A=>"id"===A.field)){let i=d({model:t,where:r,action:"deleteMany"});await A[e].deleteMany({where:i});return}let i=d({model:t,where:r,action:"delete"});try{await A[e].delete({where:i})}catch(A){if(Aw(A))return;throw A}},async deleteMany({model:e,modelKey:t=e,where:r}){let i=d({model:t,where:r,action:"deleteMany"}),n=await A[e].deleteMany({where:i});return n?n.count:0},async consumeOne({model:t,modelKey:r=t,where:i}){if(!A[t])throw new g.p(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);if(i?.some(A=>"id"===A.field)){let e=d({model:r,where:i,action:"delete"});try{return await A[t].delete({where:e})??null}catch(A){if(Aw(A))return null;throw A}}let n=d({model:r,where:i,action:"findOne"}),a=async A=>{let e=await A[t].findFirst({where:n});if(!e)return null;try{return(await A[t].deleteMany({where:d({model:r,where:[...i??[],{field:"id",value:e.id,operator:"eq",connector:"AND",mode:"sensitive"}],action:"deleteMany"})}))?.count>0?e:null}catch(A){if(Aw(A))return null;throw A}};return e||"function"!=typeof A.$transaction?a(A):A.$transaction(a)},async incrementOne({model:t,modelKey:r=t,where:i,increment:n,set:a}){if(!A[t])throw new g.p(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let s={...a??{}};for(let[A,e]of Object.entries(n))s[A]={increment:e};if(i?.some(A=>"id"===A.field)){let e=d({model:r,where:i,action:"update"});try{return await A[t].update({where:e,data:s})??null}catch(A){if(Aw(A))return null;throw A}}let o=d({model:r,where:i,action:"findOne"}),l=async A=>{let e=await A[t].findFirst({where:o});if(!e)return null;try{return await A[t].update({where:d({model:r,where:[...i,{field:"id",value:e.id,operator:"eq",connector:"AND",mode:"sensitive"}],action:"update"}),data:s})??null}catch(A){if(Aw(A))return null;throw A}};return e||"function"!=typeof A.$transaction?l(A):A.$transaction(l)},options:r}},a=null,a={config:{adapterId:"prisma",adapterName:"Prisma Adapter",usePlural:r.usePlural??!1,debugLogs:r.debugLogs??!1,supportsUUIDs:"postgresql"===r.provider,supportsArrays:"postgresql"===r.provider||"mongodb"===r.provider,transaction:!!r.transaction&&(e=>A.$transaction(A=>e((0,AC.f)({config:{...a.config,transaction:!1},adapter:n(A,!0)})(i))))},adapter:n(A)},s=(0,AC.f)(a),e=>{let t;i=e;let n=s(e),a="object"==typeof(t=A._runtimeDataModel)&&null!==t&&"models"in t?t:void 0;if(a){let A=(0,Af.t)(()=>{var A;let t;return A=r.usePlural,t=Object.fromEntries(Object.entries((0,Am.w)(e,{usePlural:A})).map(([A,e])=>[AE(A),e])),(0,Am.I)(t,Object.entries(a.models).map(([A,{fields:e}])=>({name:AE(A),columns:e.filter(A=>"object"!==A.kind).map(A=>({name:A.name,nullable:!0!==A.isRequired,hasDefault:!0===A.hasDefaultValue||!0===A.isUpdatedAt}))})))},"prisma");(0,Af.E)(n,A,{runtimeEnabled:(0,Af.S)(e)})}return n}),emailAndPassword:{enabled:iV(e.mode),requireEmailVerification:!1},account:{accountLinking:{enabled:!0,disableImplicitLinking:!0,allowDifferentEmails:!1}},databaseHooks:{...i3,...t?{verification:{create:{before:nW(A,t)}}}:{}},plugins:[function(){let A=(A=>{let e={...A||{},defaultRole:A?.defaultRole??"user",adminRoles:A?.adminRoles??["admin"],bannedUserMessage:A?.bannedUserMessage??"You have been banned from this application. Please contact support if you believe this is an error."};if(A?.adminRoles){let e=(Array.isArray(A.adminRoles)?A.adminRoles:[...A.adminRoles.split(",")]).filter(e=>!Object.keys(A?.roles||ic).map(A=>A.toLowerCase()).includes(e.toLowerCase()));if(e.length>0)throw new g.p(`Invalid admin roles: ${e.join(", ")}. Admin roles must be defined in the 'roles' configuration.`)}return{id:"admin",version:is.f,init:t=>({options:{databaseHooks:{user:{create:{before:async e=>({data:{role:A?.defaultRole??"user",...e}})}},session:{create:{async before(A,r){let i=r?.context.internalAdapter??t.internalAdapter,n=await i.findUserById(A.userId);if(n?.banned){if(n.banExpires&&new Date(n.banExpires).getTime()<Date.now())return void await i.updateUser(A.userId,{banned:!1,banReason:null,banExpires:null});let t=e.bannedUserMessage,r="function"==typeof t?await t(n):t;throw g.E.from("FORBIDDEN",{message:r,code:"BANNED_USER"})}}}}}}}),hooks:{after:[{matcher:A=>"/list-sessions"===A.path,handler:(0,l.a)(async A=>{let e=await iu(A);if(!e)return;let t=e.filter(A=>!A.impersonatedBy);return A.json(t)})}]},endpoints:{setRole:(0,l.g)("/admin/set-role",{method:"POST",body:iC,requireHeaders:!0,use:[iI],metadata:{openapi:{operationId:"setUserRole",summary:"Set the role of a user",description:"Set the role of a user",responses:{200:{description:"User role updated",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}},$Infer:{body:{}}}},async A=>{if(!ig({userId:A.context.session.user.id,role:A.context.session.user.role,options:e,permissions:{user:["set-role"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE);let t=e.roles;if(t){for(let e of Array.isArray(A.body.role)?A.body.role:[A.body.role])if(!t[e])throw g.E.from("BAD_REQUEST",id.YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE)}if(!await A.context.internalAdapter.findUserById(A.body.userId))throw g.E.from("NOT_FOUND",eI.f.USER_NOT_FOUND);let r=await A.context.internalAdapter.updateUser(A.body.userId,{role:ip(A.body.role)});return A.json({user:(0,m.$)(A.context.options,r)})}),getUser:(0,l.g)("/admin/get-user",{method:"GET",query:im,use:[iI],metadata:{openapi:{operationId:"getUser",summary:"Get an existing user",description:"Get an existing user",responses:{200:{description:"User",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async A=>{let{id:t}=A.query;if(!ig({userId:A.context.session.user.id,role:A.context.session.user.role,options:e,permissions:{user:["get"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_GET_USER);let r=await A.context.internalAdapter.findUserById(t);if(!r)throw g.E.from("NOT_FOUND",eI.f.USER_NOT_FOUND);return(0,m.$)(A.context.options,r)}),createUser:(0,l.g)("/admin/create-user",{method:"POST",body:iE,metadata:{openapi:{operationId:"createUser",summary:"Create a new user",description:"Create a new user",responses:{200:{description:"User created",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}},$Infer:{body:{}}}},async A=>{let t=await (0,h.M)(A);if(!t&&(A.request||A.headers))throw A.error("UNAUTHORIZED");if(t&&!ig({userId:t.user.id,role:t.user.role,options:e,permissions:{user:["create"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS);let{role:r,...i}=A.body.data??{},n=A.body.role??r;if(void 0!==n){if(t&&!ig({userId:t.user.id,role:t.user.role,options:e,permissions:{user:["set-role"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE);for(let A of Array.isArray(n)?n:[n]){if("string"!=typeof A)throw g.E.from("BAD_REQUEST",id.INVALID_ROLE_TYPE);if(e.roles&&!e.roles[A])throw g.E.from("BAD_REQUEST",id.YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE)}}if(t&&["banned","banReason","banExpires"].some(A=>Object.prototype.hasOwnProperty.call(i,A))&&!ig({userId:t.user.id,role:t.user.role,options:e,permissions:{user:["ban"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_BAN_USERS);let a=A.body.email.toLowerCase();if(!y.email().safeParse(a).success)throw g.E.from("BAD_REQUEST",eI.f.INVALID_EMAIL);if(A.body.password&&eC(A,A.body.password),await A.context.internalAdapter.findUserByEmail(a))throw g.E.from("BAD_REQUEST",id.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL);let s=await A.context.internalAdapter.createUser({...i,email:a,name:A.body.name,role:void 0!==n?ip(n):e?.defaultRole??"user"},{method:"admin"});if(!s)throw g.E.from("INTERNAL_SERVER_ERROR",id.FAILED_TO_CREATE_USER);if(A.body.password){let e=await A.context.password.hash(A.body.password);await A.context.internalAdapter.linkAccount({providerId:"credential",accountId:s.id,password:e,userId:s.id})}return A.json({user:(0,m.$)(A.context.options,s)})}),adminUpdateUser:(0,l.g)("/admin/update-user",{method:"POST",body:iw,use:[iI],metadata:{openapi:{operationId:"adminUpdateUser",summary:"Update a user",description:"Update a user's details",responses:{200:{description:"User updated",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async A=>{if(!ig({userId:A.context.session.user.id,role:A.context.session.user.role,options:e,permissions:{user:["update"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS);if(0===Object.keys(A.body.data).length)throw g.E.from("BAD_REQUEST",id.NO_DATA_TO_UPDATE);let t=A.body.data,r=A=>Object.prototype.hasOwnProperty.call(t,A);if(r("password"))throw g.E.from("BAD_REQUEST",id.PASSWORD_CANNOT_BE_UPDATED_VIA_UPDATE_USER);if(r("id"))throw g.E.from("BAD_REQUEST",id.USER_ID_CANNOT_BE_UPDATED);if(Object.prototype.hasOwnProperty.call(A.body.data,"role")){if(!ig({userId:A.context.session.user.id,role:A.context.session.user.role,options:e,permissions:{user:["set-role"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE);let t=A.body.data.role,r=Array.isArray(t)?t:[t];for(let A of r){if("string"!=typeof A)throw g.E.from("BAD_REQUEST",id.INVALID_ROLE_TYPE);if(e.roles&&!e.roles[A])throw g.E.from("BAD_REQUEST",id.YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE)}A.body.data.role=ip(r)}if(["banned","banReason","banExpires"].some(r)){if(!ig({userId:A.context.session.user.id,role:A.context.session.user.role,options:e,permissions:{user:["ban"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_BAN_USERS);if(!0===t.banned&&A.body.userId===A.context.session.user.id)throw g.E.from("BAD_REQUEST",id.YOU_CANNOT_BAN_YOURSELF)}if(r("email")||r("emailVerified")){if(!ig({userId:A.context.session.user.id,role:A.context.session.user.role,options:e,permissions:{user:["set-email"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_SET_USERS_EMAIL);if(r("email")){let e=String(t.email).toLowerCase();if(!y.email().safeParse(e).success)throw g.E.from("BAD_REQUEST",eI.f.INVALID_EMAIL);let r=await A.context.internalAdapter.findUserByEmail(e);if(r&&r.user.id!==A.body.userId)throw g.E.from("BAD_REQUEST",id.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL);t.email=e}}if((r("phoneNumber")||r("phoneNumberVerified"))&&!ig({userId:A.context.session.user.id,role:A.context.session.user.role,options:e,permissions:{user:["set-phone"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PHONE_NUMBER);if(!await A.context.internalAdapter.findUserById(A.body.userId))throw g.E.from("NOT_FOUND",eI.f.USER_NOT_FOUND);let i=await A.context.internalAdapter.updateUser(A.body.userId,A.body.data);return!0===t.banned&&await A.context.internalAdapter.deleteUserSessions(A.body.userId),A.json((0,m.$)(A.context.options,i))}),listUsers:(0,l.g)("/admin/list-users",{method:"GET",use:[iI],query:iy,metadata:{openapi:{operationId:"listUsers",summary:"List users",description:"List users",responses:{200:{description:"List of users",content:{"application/json":{schema:{type:"object",properties:{users:{type:"array",items:{$ref:"#/components/schemas/User"}},total:{type:"number"},limit:{type:"number"},offset:{type:"number"}},required:["users","total"]}}}}}}}},async A=>{let t=A.context.session;if(!ig({userId:A.context.session.user.id,role:t.user.role,options:e,permissions:{user:["list"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_LIST_USERS);let r=[];A.query?.searchValue&&r.push({field:A.query.searchField||"email",operator:A.query.searchOperator||"contains",value:A.query.searchValue}),A.query?.filterValue!==void 0&&r.push({field:A.query.filterField||"email",operator:A.query.filterOperator||"eq",value:A.query.filterValue});try{let e=await A.context.internalAdapter.listUsers(Number(A.query?.limit)||void 0,Number(A.query?.offset)||void 0,A.query?.sortBy?{field:A.query.sortBy,direction:A.query.sortDirection||"asc"}:void 0,r.length?r:void 0),t=await A.context.internalAdapter.countTotalUsers(r.length?r:void 0);return A.json({users:e.map(e=>(0,m.$)(A.context.options,e)),total:t,limit:Number(A.query?.limit)||void 0,offset:Number(A.query?.offset)||void 0})}catch{return A.json({users:[],total:0})}}),listUserSessions:(0,l.g)("/admin/list-user-sessions",{method:"POST",use:[iI],body:iQ,metadata:{openapi:{operationId:"adminListUserSessions",summary:"List user sessions",description:"List user sessions",responses:{200:{description:"List of user sessions",content:{"application/json":{schema:{type:"object",properties:{sessions:{type:"array",items:{$ref:"#/components/schemas/Session"}}}}}}}}}}},async A=>{let t=A.context.session;if(!ig({userId:A.context.session.user.id,role:t.user.role,options:e,permissions:{session:["list"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS);let r=await A.context.internalAdapter.listSessions(A.body.userId);return A.json({sessions:r.map(e=>(0,m.Q)(A.context.options,e))})}),unbanUser:(0,l.g)("/admin/unban-user",{method:"POST",body:iB,use:[iI],metadata:{openapi:{operationId:"unbanUser",summary:"Unban a user",description:"Unban a user",responses:{200:{description:"User unbanned",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async A=>{let t=A.context.session;if(!ig({userId:A.context.session.user.id,role:t.user.role,options:e,permissions:{user:["ban"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_BAN_USERS);if(!await A.context.internalAdapter.findUserById(A.body.userId))throw g.E.from("NOT_FOUND",eI.f.USER_NOT_FOUND);let r=await A.context.internalAdapter.updateUser(A.body.userId,{banned:!1,banExpires:null,banReason:null,updatedAt:new Date});return A.json({user:(0,m.$)(A.context.options,r)})}),banUser:(0,l.g)("/admin/ban-user",{method:"POST",body:iD,use:[iI],metadata:{openapi:{operationId:"banUser",summary:"Ban a user",description:"Ban a user",responses:{200:{description:"User banned",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async A=>{let t=A.context.session;if(!ig({userId:A.context.session.user.id,role:t.user.role,options:e,permissions:{user:["ban"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_BAN_USERS);if(!await A.context.internalAdapter.findUserById(A.body.userId))throw g.E.from("NOT_FOUND",eI.f.USER_NOT_FOUND);if(A.body.userId===A.context.session.user.id)throw g.E.from("BAD_REQUEST",id.YOU_CANNOT_BAN_YOURSELF);let r=await A.context.internalAdapter.updateUser(A.body.userId,{banned:!0,banReason:A.body.banReason||e?.defaultBanReason||"No reason",banExpires:A.body.banExpiresIn?(0,A8.f)(A.body.banExpiresIn,"sec"):e?.defaultBanExpiresIn?(0,A8.f)(e.defaultBanExpiresIn,"sec"):null,updatedAt:new Date});return await A.context.internalAdapter.deleteUserSessions(A.body.userId),A.json({user:(0,m.$)(A.context.options,r)})}),impersonateUser:(0,l.g)("/admin/impersonate-user",{method:"POST",body:ik,use:[iI],metadata:{openapi:{operationId:"impersonateUser",summary:"Impersonate a user",description:"Impersonate a user",responses:{200:{description:"Impersonation session created",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}}}}}},async A=>{if(!ig({userId:A.context.session.user.id,role:A.context.session.user.role,options:e,permissions:{user:["impersonate"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS);let t=await A.context.internalAdapter.findUserById(A.body.userId);if(!t)throw g.E.from("NOT_FOUND",eI.f.USER_NOT_FOUND);let r=(Array.isArray(e.adminRoles)?e.adminRoles:e.adminRoles?.split(",")||[]).map(A=>A.trim());if(((t.role||e.defaultRole||"user").split(",").some(A=>r.includes(A))||e.adminUserIds?.includes(t.id))&&!(!0===e.allowImpersonatingAdmins||ig({userId:A.context.session.user.id,role:A.context.session.user.role,options:e,permissions:{user:["impersonate-admins"]}})))throw g.E.from("FORBIDDEN",id.YOU_CANNOT_IMPERSONATE_ADMINS);let i=await A.context.internalAdapter.createSession(t.id,!0,{impersonatedBy:A.context.session.user.id,expiresAt:e?.impersonationSessionDuration?(0,A8.f)(e.impersonationSessionDuration,"sec"):(0,A8.f)(3600,"sec")},!0);if(!i)throw g.E.from("INTERNAL_SERVER_ERROR",id.FAILED_TO_CREATE_USER);let n=A.context.authCookies;(0,A4.Q)(A);let a=await A.getSignedCookie(A.context.authCookies.dontRememberToken.name,A.context.secret),s=A.context.createAuthCookie("admin_session");return await A.setSignedCookie(s.name,`${A.context.session.session.token}:${a||""}`,A.context.secret,n.sessionToken.attributes),await (0,A4.V)(A,{session:i,user:t},!0),A.json({session:i,user:(0,m.$)(A.context.options,t)})}),stopImpersonating:(0,l.g)("/admin/stop-impersonating",{method:"POST",requireHeaders:!0},async A=>{let e=await (0,h.D)(A);if(!e)throw g.E.fromStatus("UNAUTHORIZED");if(!e.session.impersonatedBy)throw g.E.fromStatus("BAD_REQUEST",{message:"You are not impersonating anyone"});let t=await A.context.internalAdapter.findUserById(e.session.impersonatedBy);if(!t)throw g.E.fromStatus("INTERNAL_SERVER_ERROR",{message:"Failed to find user"});let r=A.context.createAuthCookie("admin_session"),i=await A.getSignedCookie(r.name,A.context.secret);if(!i)throw g.E.fromStatus("INTERNAL_SERVER_ERROR",{message:"Failed to find admin session"});let[n,a]=i?.split(":"),s=await A.context.internalAdapter.findSession(n);if(!s||s.session.userId!==t.id)throw g.E.fromStatus("INTERNAL_SERVER_ERROR",{message:"Failed to find admin session"});return await A.context.internalAdapter.deleteSession(e.session.token),await (0,A4.V)(A,s,!!a),(0,A4.c)(A,r),A.json({session:(0,m.Q)(A.context.options,s.session),user:(0,m.$)(A.context.options,s.user)})}),revokeUserSession:(0,l.g)("/admin/revoke-user-session",{method:"POST",body:iS,use:[iI],metadata:{openapi:{operationId:"revokeUserSession",summary:"Revoke a user session",description:"Revoke a user session",responses:{200:{description:"Session revoked",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async A=>{let t=A.context.session;if(!ig({userId:A.context.session.user.id,role:t.user.role,options:e,permissions:{session:["revoke"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS);return await A.context.internalAdapter.deleteSession(A.body.sessionToken),A.json({success:!0})}),revokeUserSessions:(0,l.g)("/admin/revoke-user-sessions",{method:"POST",body:ib,use:[iI],metadata:{openapi:{operationId:"revokeUserSessions",summary:"Revoke all user sessions",description:"Revoke all user sessions",responses:{200:{description:"Sessions revoked",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async A=>{let t=A.context.session;if(!ig({userId:A.context.session.user.id,role:t.user.role,options:e,permissions:{session:["revoke"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS);return await A.context.internalAdapter.deleteUserSessions(A.body.userId),A.json({success:!0})}),removeUser:(0,l.g)("/admin/remove-user",{method:"POST",body:iM,use:[iI],metadata:{openapi:{operationId:"removeUser",summary:"Remove a user",description:"Delete a user and all their sessions and accounts. Cannot be undone.",responses:{200:{description:"User removed",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async A=>{let t=A.context.session;if(!ig({userId:A.context.session.user.id,role:t.user.role,options:e,permissions:{user:["delete"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS);if(A.body.userId===A.context.session.user.id)throw g.E.from("BAD_REQUEST",id.YOU_CANNOT_REMOVE_YOURSELF);if(!await A.context.internalAdapter.findUserById(A.body.userId))throw g.E.from("NOT_FOUND",eI.f.USER_NOT_FOUND);return await A.context.internalAdapter.deleteUserSessions(A.body.userId),await A.context.internalAdapter.deleteUser(A.body.userId),A.json({success:!0})}),setUserPassword:(0,l.g)("/admin/set-user-password",{method:"POST",body:iO,use:[iI],metadata:{openapi:{operationId:"setUserPassword",summary:"Set a user's password",description:"Set a user's password",responses:{200:{description:"Password set",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async A=>{if(!ig({userId:A.context.session.user.id,role:A.context.session.user.role,options:e,permissions:{user:["set-password"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD);let{newPassword:t,userId:r}=A.body;ep(A,t),eC(A,t);let i=await A.context.internalAdapter.findUserById(r);if(!i)throw g.E.from("NOT_FOUND",eI.f.USER_NOT_FOUND);let n=await A.context.password.hash(t);return await A.context.internalAdapter.findCredentialAccount(r)?await A.context.internalAdapter.updatePassword(r,n):await A.context.internalAdapter.createAccount({userId:r,providerId:"credential",accountId:i.id,password:n}),A.json({status:!0})}),userHasPermission:(0,l.g)("/admin/has-permission",{method:"POST",body:iv,metadata:{openapi:{description:"Check if the user has permission",requestBody:{content:{"application/json":{schema:{type:"object",properties:{permissions:{type:"object",description:"The permission to check"}},required:["permissions"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"},success:{type:"boolean"}},required:["success"]}}}}}},$Infer:{body:{}}}},async A=>{if(!A.body?.permissions)throw new g.E("BAD_REQUEST",{message:"invalid permission check. no permission(s) were passed."});let t=await (0,h.M)(A);if(!t&&(A.request||A.headers))throw new g.E("UNAUTHORIZED");if(!t&&!A.body.userId&&!A.body.role)throw new g.E("BAD_REQUEST",{message:"user id or role is required"});let r=t?.user||(A.body.role?{id:A.body.userId||"",role:A.body.role}:null)||(A.body.userId?await A.context.internalAdapter.findUserById(A.body.userId):null);if(!r)throw new g.E("BAD_REQUEST",{message:"user not found"});let i=ig({userId:r.id,role:r.role,options:e,permissions:A.body.permissions});return A.json({error:null,success:i})})},$ERROR_CODES:id,schema:(0,m.C)(iR,e.schema),options:A}})({ac:nX,roles:{user:n0},defaultRole:"user",adminRoles:["user"]}),{setRole:e,banUser:t,unbanUser:r,impersonateUser:i,stopImpersonating:n,removeUser:a,...s}=A.endpoints;return{...A,endpoints:s}}(),function(A){if(Array.isArray(A)&&A.length>0){if(!A.every(A=>A.configId))throw new g.p("configId is required for each API key configuration in the api-key plugin.");let e=A.map(A=>A.configId);if(new Set(e).size!==e.length)throw new g.p("configId must be unique for each API key configuration in the api-key plugin.")}let e=(void 0)??{schema:Array.isArray(A)?void 0:A?.schema},t=[...(Array.isArray(A)?A:[A]).map(A=>({...A,apiKeyHeaders:A?.apiKeyHeaders??"x-api-key",defaultKeyLength:A?.defaultKeyLength||64,maximumPrefixLength:A?.maximumPrefixLength??32,minimumPrefixLength:A?.minimumPrefixLength??1,maximumNameLength:A?.maximumNameLength??32,minimumNameLength:A?.minimumNameLength??1,enableMetadata:A?.enableMetadata??!1,disableKeyHashing:A?.disableKeyHashing??!1,requireName:A?.requireName??!1,storage:A?.storage??"database",rateLimit:{enabled:A?.rateLimit?.enabled===void 0||A?.rateLimit?.enabled,timeWindow:A?.rateLimit?.timeWindow??864e5,maxRequests:A?.rateLimit?.maxRequests??10},keyExpiration:{defaultExpiresIn:A?.keyExpiration?.defaultExpiresIn??null,disableCustomExpiresTime:A?.keyExpiration?.disableCustomExpiresTime??!1,maxExpiresIn:A?.keyExpiration?.maxExpiresIn??365,minExpiresIn:A?.keyExpiration?.minExpiresIn??1},startingCharactersConfig:{shouldStore:A?.startingCharactersConfig?.shouldStore??!0,charactersLength:A?.startingCharactersConfig?.charactersLength??6},enableSessionForAPIKeys:A?.enableSessionForAPIKeys??!1,fallbackToDatabase:A?.fallbackToDatabase??!1,customStorage:A?.customStorage,deferUpdates:A?.deferUpdates??!1}))],r=(0,m.C)((({defaultRateLimitMax:A,defaultTimeWindow:e})=>({apikey:{fields:{configId:{type:"string",required:!0,defaultValue:"default",input:!1,index:!0},name:{type:"string",required:!1,input:!1},start:{type:"string",required:!1,input:!1},referenceId:{type:"string",required:!0,input:!1,index:!0},prefix:{type:"string",required:!1,input:!1},key:{type:"string",required:!0,input:!1,index:!0},refillInterval:{type:"number",required:!1,input:!1},refillAmount:{type:"number",required:!1,input:!1},lastRefillAt:{type:"date",required:!1,input:!1},enabled:{type:"boolean",required:!1,input:!1,defaultValue:!0},rateLimitEnabled:{type:"boolean",required:!1,input:!1,defaultValue:!0},rateLimitTimeWindow:{type:"number",required:!1,input:!1,defaultValue:e},rateLimitMax:{type:"number",required:!1,input:!1,defaultValue:A},requestCount:{type:"number",required:!1,input:!1,defaultValue:0},remaining:{type:"number",required:!1,input:!1},lastRequest:{type:"date",required:!1,input:!1},expiresAt:{type:"date",required:!1,input:!1},createdAt:{type:"date",required:!0,input:!1},updatedAt:{type:"date",required:!0,input:!1},permissions:{type:"string",required:!1,input:!1},metadata:{type:"string",required:!1,input:!0,transform:{input:A=>JSON.stringify(A),output:A=>A?(0,k.f)(A):null}}}}}))({defaultRateLimitMax:(1===t.length?t[0]?.rateLimit.maxRequests:void 0)??10,defaultTimeWindow:(1===t.length?t[0]?.rateLimit.timeWindow:void 0)??864e5}),e.schema);function i(A){for(let e of t){if(!e.enableSessionForAPIKeys)continue;let t=function(A,e){if(e.customAPIKeyGetter)return e.customAPIKeyGetter(A);if(Array.isArray(e.apiKeyHeaders)){for(let t of e.apiKeyHeaders){let e=A.headers?.get(t);if(e)return e}return null}return A.headers?.get(e.apiKeyHeaders)??null}(A,e);if(t)return{key:t,config:e}}return null}let n=function({defaultKeyGenerator:A,configurations:e,schema:t}){return{createApiKey:function({defaultKeyGenerator:A,configurations:e,schema:t,deleteAllExpiredApiKeys:r}){return(0,l.g)("/api-key/create",{method:"POST",body:Z,metadata:{openapi:{description:"Create a new API key for a user",responses:{200:{description:"API key created successfully",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string",description:"Unique identifier of the API key"},createdAt:{type:"string",format:"date-time",description:"Creation timestamp"},updatedAt:{type:"string",format:"date-time",description:"Last update timestamp"},name:{type:"string",nullable:!0,description:"Name of the API key"},prefix:{type:"string",nullable:!0,description:"Prefix of the API key"},start:{type:"string",nullable:!0,description:"Starting characters of the key (if configured)"},key:{type:"string",description:"The full API key (only returned on creation)"},enabled:{type:"boolean",description:"Whether the key is enabled"},expiresAt:{type:"string",format:"date-time",nullable:!0,description:"Expiration timestamp"},referenceId:{type:"string",description:"ID of the reference owning the key"},lastRefillAt:{type:"string",format:"date-time",nullable:!0,description:"Last refill timestamp"},lastRequest:{type:"string",format:"date-time",nullable:!0,description:"Last request timestamp"},metadata:{type:"object",nullable:!0,additionalProperties:!0,description:"Metadata associated with the key"},rateLimitMax:{type:"number",nullable:!0,description:"Maximum requests in time window"},rateLimitTimeWindow:{type:"number",nullable:!0,description:"Rate limit time window in milliseconds"},remaining:{type:"number",nullable:!0,description:"Remaining requests"},refillAmount:{type:"number",nullable:!0,description:"Amount to refill"},refillInterval:{type:"number",nullable:!0,description:"Refill interval in milliseconds"},rateLimitEnabled:{type:"boolean",description:"Whether rate limiting is enabled"},requestCount:{type:"number",description:"Current request count in window"},permissions:{type:"object",nullable:!0,additionalProperties:{type:"array",items:{type:"string"}},description:"Permissions associated with the key"}},required:["id","createdAt","updatedAt","key","enabled","referenceId","rateLimitEnabled","requestCount"]}}}}}}}},async t=>{let i,n,{configId:a,name:s,expiresIn:l,prefix:c,remaining:d,metadata:u,refillAmount:I,refillInterval:p,permissions:C,rateLimitMax:f,rateLimitTimeWindow:m,rateLimitEnabled:y}=t.body,Q=Ac(t.context,e,a),B=Q.customKeyGenerator||A,D=await (0,h.D)(t,{disableCookieCache:!0}),k=t.request||t.headers;if(k&&(void 0!==I||void 0!==p||void 0!==f||void 0!==m||void 0!==y||void 0!==C||null!==d))throw g.E.from("BAD_REQUEST",o.SERVER_ONLY_PROPERTY);if(t.request&&void 0!==t.body.userId)throw g.E.from("UNAUTHORIZED",o.UNAUTHORIZED_SESSION);if("organization"===(Q.references??"user")){let A=t.body.organizationId;if(!A){let A=o.ORGANIZATION_ID_REQUIRED;throw g.E.from("BAD_REQUEST",A)}let e=D?.user.id||t.body.userId;if(!e)throw g.E.from("UNAUTHORIZED",o.UNAUTHORIZED_SESSION);await K(t,e,A,"create"),i=A}else if(k){if(!D?.user.id){let A=o.UNAUTHORIZED_SESSION;throw g.E.from("UNAUTHORIZED",A)}i=D.user.id}else{let A=t.body.userId,e=D?.user.id;if(!e&&!A||D&&A&&e!==A){let A=o.UNAUTHORIZED_SESSION;throw g.E.from("UNAUTHORIZED",A)}i=e||A}if(u){if(!1===Q.enableMetadata)throw g.E.from("BAD_REQUEST",o.METADATA_DISABLED);if("object"!=typeof u)throw g.E.from("BAD_REQUEST",o.INVALID_METADATA_TYPE)}if(I&&!p){let A=o.REFILL_AMOUNT_AND_INTERVAL_REQUIRED;throw g.E.from("BAD_REQUEST",A)}if(p&&!I){let A=o.REFILL_INTERVAL_AND_AMOUNT_REQUIRED;throw g.E.from("BAD_REQUEST",A)}if(l){if(!0===Q.keyExpiration.disableCustomExpiresTime){let A=o.KEY_DISABLED_EXPIRATION;throw g.E.from("BAD_REQUEST",A)}let A=l/86400;if(Q.keyExpiration.minExpiresIn>A){let A=o.EXPIRES_IN_IS_TOO_SMALL;throw g.E.from("BAD_REQUEST",A)}if(Q.keyExpiration.maxExpiresIn<A){let A=o.EXPIRES_IN_IS_TOO_LARGE;throw g.E.from("BAD_REQUEST",A)}}if(c&&(c.length<Q.minimumPrefixLength||c.length>Q.maximumPrefixLength))throw g.E.from("BAD_REQUEST",o.INVALID_PREFIX_LENGTH);if(s){if(s.length<Q.minimumNameLength||s.length>Q.maximumNameLength)throw g.E.from("BAD_REQUEST",o.INVALID_NAME_LENGTH)}else if(Q.requireName)throw g.E.from("BAD_REQUEST",o.NAME_REQUIRED);r(t.context);let S=await B({length:Q.defaultKeyLength,prefix:c||Q.defaultPrefix}),b=Q.disableKeyHashing?S:await AI(S),M=null;Q.startingCharactersConfig.shouldStore&&(M=S.substring(0,Q.startingCharactersConfig.charactersLength));let O=Q.permissions?.defaultPermissions?"function"==typeof Q.permissions.defaultPermissions?await Q.permissions.defaultPermissions(i,t):Q.permissions.defaultPermissions:void 0,v=C?JSON.stringify(C):O?JSON.stringify(O):void 0,R={configId:Q.configId??"default",createdAt:new Date,updatedAt:new Date,name:s??null,prefix:c??Q.defaultPrefix??null,start:M,key:b,enabled:!0,expiresAt:l?$(l,"sec"):Q.keyExpiration.defaultExpiresIn?$(Q.keyExpiration.defaultExpiresIn,"sec"):null,referenceId:i,lastRefillAt:null,lastRequest:null,metadata:null,rateLimitMax:f??Q.rateLimit.maxRequests??null,rateLimitTimeWindow:m??Q.rateLimit.timeWindow??null,remaining:null===d?d:d??I??null,refillAmount:I??null,refillInterval:p??null,rateLimitEnabled:void 0===y?Q.rateLimit.enabled??!0:y,requestCount:0,permissions:v};if(u&&(R.metadata=u),"secondary-storage"===Q.storage&&Q.fallbackToDatabase)n=await t.context.adapter.create({model:Ap,data:R}),await F(t,n,Q);else if("secondary-storage"===Q.storage){let A=t.context.generateId({model:"apikey"})||(0,E.f)();n={...R,id:A},await F(t,n,Q)}else n=await t.context.adapter.create({model:Ap,data:R});return t.json({...n,key:S,metadata:u??null,permissions:n.permissions?(0,w.f)(n.permissions):null})})}({defaultKeyGenerator:A,configurations:e,schema:t,deleteAllExpiredApiKeys:Ah}),verifyApiKey:function({configurations:A,schema:e,deleteAllExpiredApiKeys:t}){return l.g.serverOnly({method:"POST",body:Al},async r=>{let i,{configId:n,key:a}=r.body,s=Ac(r.context,A,n);if(void 0!==n&&s.customAPIKeyValidator&&!await s.customAPIKeyValidator({ctx:r,key:a}))return r.json({valid:!1,error:{message:o.INVALID_API_KEY,code:"KEY_NOT_FOUND"},key:null});let l=null;try{let o=await Ai({key:a,permissions:r.body.permissions,ctx:r,lookupOpts:s,configurations:A,schema:e,expectedConfigId:n,runCustomValidator:void 0===n});l=o.apiKey,(i=o.opts).deferUpdates&&r.context.runInBackground(t(r.context).catch(A=>{r.context.logger.error("Failed to delete expired API keys:",A)}))}catch(A){if(r.context.logger.error("Failed to validate API key:",A),A instanceof g.E||A instanceof g.E||A?.name==="APIError")return r.json({valid:!1,error:{...A.body,message:A.body?.message,code:A.body?.code},key:null});return r.json({valid:!1,error:{message:o.INVALID_API_KEY,code:"INVALID_API_KEY"},key:null})}let{key:c,...d}=l??{key:1,permissions:void 0},u=null;return l&&(u=await O(r,l,i)),d.permissions=d.permissions?(0,w.f)(d.permissions):null,r.json({valid:!0,error:null,key:null===l?null:{...d,metadata:u}})})}({configurations:e,schema:t,deleteAllExpiredApiKeys:Ah}),getApiKey:function({configurations:A,schema:e,deleteAllExpiredApiKeys:t}){return(0,l.g)("/api-key/get",{method:"GET",query:AA,use:[h.Z],metadata:{openapi:{description:"Retrieve an existing API key by ID",responses:{200:{description:"API key retrieved successfully",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string",description:"ID"},name:{type:"string",nullable:!0,description:"The name of the key"},start:{type:"string",nullable:!0,description:"Shows the first few characters of the API key, including the prefix. This allows you to show those few characters in the UI to make it easier for users to identify the API key."},prefix:{type:"string",nullable:!0,description:"The API Key prefix. Stored as plain text."},userId:{type:"string",description:"The owner of the user id"},refillInterval:{type:"number",nullable:!0,description:"The interval in milliseconds between refills of the `remaining` count. Example: 3600000 // refill every hour (3600000ms = 1h)"},refillAmount:{type:"number",nullable:!0,description:"The amount to refill"},lastRefillAt:{type:"string",format:"date-time",nullable:!0,description:"The last refill date"},enabled:{type:"boolean",description:"Sets if key is enabled or disabled",default:!0},rateLimitEnabled:{type:"boolean",description:"Whether the key has rate limiting enabled"},rateLimitTimeWindow:{type:"number",nullable:!0,description:"The duration in milliseconds"},rateLimitMax:{type:"number",nullable:!0,description:"Maximum amount of requests allowed within a window"},requestCount:{type:"number",description:"The number of requests made within the rate limit time window"},remaining:{type:"number",nullable:!0,description:"Remaining requests (every time api key is used this should updated and should be updated on refill as well)"},lastRequest:{type:"string",format:"date-time",nullable:!0,description:"When last request occurred"},expiresAt:{type:"string",format:"date-time",nullable:!0,description:"Expiry date of a key"},createdAt:{type:"string",format:"date-time",description:"created at"},updatedAt:{type:"string",format:"date-time",description:"updated at"},metadata:{type:"object",nullable:!0,additionalProperties:!0,description:"Extra metadata about the apiKey"},permissions:{type:"string",nullable:!0,description:"Permissions for the api key (stored as JSON string)"}},required:["id","userId","enabled","rateLimitEnabled","requestCount","createdAt","updatedAt"]}}}}}}}},async e=>{let{configId:r,id:i}=e.query,n=e.context.session,a=Ac(e.context,A,r),s=null;if(!(s=await Y(e,i,a))||!Au(s.configId,a.configId))throw g.E.from("NOT_FOUND",o.KEY_NOT_FOUND);let l=Ac(e.context,A,s.configId);if((l.references??"user")==="organization")await K(e,n.user.id,s.referenceId,"read");else if(s.referenceId!==n.user.id)throw g.E.from("NOT_FOUND",o.KEY_NOT_FOUND);t(e.context);let c=await O(e,s,l),{key:d,...u}=s;return e.json({...u,metadata:c,permissions:u.permissions?(0,w.f)(u.permissions):null})})}({configurations:e,schema:t,deleteAllExpiredApiKeys:Ah}),updateApiKey:function({configurations:A,schema:e,deleteAllExpiredApiKeys:t}){return(0,l.g)("/api-key/update",{method:"POST",body:At,metadata:{openapi:{description:"Update an existing API key by ID",responses:{200:{description:"API key updated successfully",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string",description:"ID"},name:{type:"string",nullable:!0,description:"The name of the key"},start:{type:"string",nullable:!0,description:"Shows the first few characters of the API key, including the prefix. This allows you to show those few characters in the UI to make it easier for users to identify the API key."},prefix:{type:"string",nullable:!0,description:"The API Key prefix. Stored as plain text."},userId:{type:"string",description:"The owner of the user id"},refillInterval:{type:"number",nullable:!0,description:"The interval in milliseconds between refills of the `remaining` count. Example: 3600000 // refill every hour (3600000ms = 1h)"},refillAmount:{type:"number",nullable:!0,description:"The amount to refill"},lastRefillAt:{type:"string",format:"date-time",nullable:!0,description:"The last refill date"},enabled:{type:"boolean",description:"Sets if key is enabled or disabled",default:!0},rateLimitEnabled:{type:"boolean",description:"Whether the key has rate limiting enabled"},rateLimitTimeWindow:{type:"number",nullable:!0,description:"The duration in milliseconds"},rateLimitMax:{type:"number",nullable:!0,description:"Maximum amount of requests allowed within a window"},requestCount:{type:"number",description:"The number of requests made within the rate limit time window"},remaining:{type:"number",nullable:!0,description:"Remaining requests (every time api key is used this should updated and should be updated on refill as well)"},lastRequest:{type:"string",format:"date-time",nullable:!0,description:"When last request occurred"},expiresAt:{type:"string",format:"date-time",nullable:!0,description:"Expiry date of a key"},createdAt:{type:"string",format:"date-time",description:"created at"},updatedAt:{type:"string",format:"date-time",description:"updated at"},metadata:{type:"object",nullable:!0,additionalProperties:!0,description:"Extra metadata about the apiKey"},permissions:{type:"string",nullable:!0,description:"Permissions for the api key (stored as JSON string)"}},required:["id","userId","enabled","rateLimitEnabled","requestCount","createdAt","updatedAt"]}}}}}}}},async e=>{let{configId:r,keyId:i,expiresIn:n,enabled:a,metadata:s,refillAmount:l,refillInterval:c,remaining:d,name:u,permissions:I,rateLimitEnabled:p,rateLimitTimeWindow:C,rateLimitMax:f}=e.body,m=await (0,h.D)(e,{disableCookieCache:!0}),E=e.request||e.headers,y=E&&!m?null:m?.user||{id:e.body.userId};if(!y?.id||m&&e.body.userId&&m?.user.id!==e.body.userId)throw g.E.from("UNAUTHORIZED",o.UNAUTHORIZED_SESSION);if(E&&(void 0!==l||void 0!==c||void 0!==f||void 0!==C||void 0!==p||void 0!==d||void 0!==I))throw g.E.from("BAD_REQUEST",o.SERVER_ONLY_PROPERTY);let Q=Ac(e.context,A,r),B=null;if(!(B=await Y(e,i,Q))||!Au(B.configId,Q.configId))throw g.E.from("NOT_FOUND",o.KEY_NOT_FOUND);let D=Ac(e.context,A,B.configId);if((D.references??"user")==="organization")await K(e,y.id,B.referenceId,"update");else if(B.referenceId!==y.id)throw g.E.from("NOT_FOUND",o.KEY_NOT_FOUND);let k={};if(void 0!==u){if(u.length<D.minimumNameLength||u.length>D.maximumNameLength)throw g.E.from("BAD_REQUEST",o.INVALID_NAME_LENGTH);k.name=u}if(void 0!==a&&(k.enabled=a),void 0!==n){if(!0===D.keyExpiration.disableCustomExpiresTime)throw g.E.from("BAD_REQUEST",o.KEY_DISABLED_EXPIRATION);if(null!==n){let A=n/86400;if(A<D.keyExpiration.minExpiresIn)throw g.E.from("BAD_REQUEST",o.EXPIRES_IN_IS_TOO_SMALL);if(A>D.keyExpiration.maxExpiresIn)throw g.E.from("BAD_REQUEST",o.EXPIRES_IN_IS_TOO_LARGE)}k.expiresAt=n?$(n,"sec"):null}if(void 0!==s&&!0===D.enableMetadata){if("object"!=typeof s)throw g.E.from("BAD_REQUEST",o.INVALID_METADATA_TYPE);k.metadata=s}if(void 0!==d&&(k.remaining=d),void 0!==l||void 0!==c){if(void 0!==l&&void 0===c)throw g.E.from("BAD_REQUEST",o.REFILL_AMOUNT_AND_INTERVAL_REQUIRED);if(void 0!==c&&void 0===l)throw g.E.from("BAD_REQUEST",o.REFILL_INTERVAL_AND_AMOUNT_REQUIRED);k.refillAmount=l,k.refillInterval=c}if(void 0!==p&&(k.rateLimitEnabled=p),void 0!==C&&(k.rateLimitTimeWindow=C),void 0!==f&&(k.rateLimitMax=f),void 0!==I&&(k.permissions=JSON.stringify(I)),0===Object.keys(k).length)throw g.E.from("BAD_REQUEST",o.NO_VALUES_TO_UPDATE);let S=B;try{if("secondary-storage"===D.storage&&D.fallbackToDatabase){let A=await e.context.adapter.update({model:Ap,where:[{field:"id",value:B.id}],update:k});A&&(await F(e,A,D),S=A)}else if("database"===D.storage){let A=await e.context.adapter.update({model:Ap,where:[{field:"id",value:B.id}],update:k});A&&(S=A)}else{let A={...B,...k,updatedAt:new Date};await F(e,A,D),S=A}}catch(A){throw g.E.fromStatus("INTERNAL_SERVER_ERROR",{message:A?.message})}t(e.context);let b=await O(e,S,D),{key:M,...v}=S;return e.json({...v,metadata:b,permissions:v.permissions?(0,w.f)(v.permissions):null})})}({configurations:e,schema:t,deleteAllExpiredApiKeys:Ah}),deleteApiKey:function({configurations:A,schema:e,deleteAllExpiredApiKeys:t}){return(0,l.g)("/api-key/delete",{method:"POST",body:X,use:[h.Z],metadata:{openapi:{description:"Delete an existing API key",requestBody:{content:{"application/json":{schema:{type:"object",properties:{keyId:{type:"string",description:"The id of the API key to delete"}},required:["keyId"]}}}},responses:{200:{description:"API key deleted successfully",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",description:"Indicates if the API key was successfully deleted"}},required:["success"]}}}}}}}},async e=>{let{configId:r,keyId:i}=e.body,n=e.context.session;if(!0===n.user.banned)throw g.E.from("UNAUTHORIZED",o.USER_BANNED);let a=Ac(e.context,A,r),s=null;if(!(s=await Y(e,i,a))||!Au(s.configId,a.configId))throw g.E.from("NOT_FOUND",o.KEY_NOT_FOUND);let l=Ac(e.context,A,s.configId);if((l.references??"user")==="organization")await K(e,n.user.id,s.referenceId,"delete");else if(s.referenceId!==n.user.id)throw g.E.from("NOT_FOUND",o.KEY_NOT_FOUND);try{"secondary-storage"===l.storage&&l.fallbackToDatabase?(await z(e,s,l),await e.context.adapter.delete({model:Ap,where:[{field:"id",value:s.id}]})):"database"===l.storage?await e.context.adapter.delete({model:Ap,where:[{field:"id",value:s.id}]}):await z(e,s,l)}catch(A){throw g.E.fromStatus("INTERNAL_SERVER_ERROR",{message:A?.message})}return t(e.context),e.json({success:!0})})}({configurations:e,schema:t,deleteAllExpiredApiKeys:Ah}),listApiKeys:function({configurations:A,schema:e,deleteAllExpiredApiKeys:t}){return(0,l.g)("/api-key/list",{method:"GET",use:[h.Z],query:Ae,metadata:{openapi:{description:"List all API keys for the authenticated user or for a specific organization",responses:{200:{description:"API keys retrieved successfully",content:{"application/json":{schema:{type:"object",properties:{apiKeys:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"ID"},name:{type:"string",nullable:!0,description:"The name of the key"},start:{type:"string",nullable:!0,description:"Shows the first few characters of the API key, including the prefix. This allows you to show those few characters in the UI to make it easier for users to identify the API key."},prefix:{type:"string",nullable:!0,description:"The API Key prefix. Stored as plain text."},userId:{type:"string",description:"The owner of the user id"},refillInterval:{type:"number",nullable:!0,description:"The interval in milliseconds between refills of the `remaining` count. Example: 3600000 // refill every hour (3600000ms = 1h)"},refillAmount:{type:"number",nullable:!0,description:"The amount to refill"},lastRefillAt:{type:"string",format:"date-time",nullable:!0,description:"The last refill date"},enabled:{type:"boolean",description:"Sets if key is enabled or disabled",default:!0},rateLimitEnabled:{type:"boolean",description:"Whether the key has rate limiting enabled"},rateLimitTimeWindow:{type:"number",nullable:!0,description:"The duration in milliseconds"},rateLimitMax:{type:"number",nullable:!0,description:"Maximum amount of requests allowed within a window"},requestCount:{type:"number",description:"The number of requests made within the rate limit time window"},remaining:{type:"number",nullable:!0,description:"Remaining requests (every time api key is used this should updated and should be updated on refill as well)"},lastRequest:{type:"string",format:"date-time",nullable:!0,description:"When last request occurred"},expiresAt:{type:"string",format:"date-time",nullable:!0,description:"Expiry date of a key"},createdAt:{type:"string",format:"date-time",description:"created at"},updatedAt:{type:"string",format:"date-time",description:"updated at"},metadata:{type:"object",nullable:!0,additionalProperties:!0,description:"Extra metadata about the apiKey"},permissions:{type:"string",nullable:!0,description:"Permissions for the api key (stored as JSON string)"}},required:["id","userId","enabled","rateLimitEnabled","requestCount","createdAt","updatedAt"]}},total:{type:"number",description:"Total number of API keys"},limit:{type:"number",nullable:!0,description:"The limit used for pagination"},offset:{type:"number",nullable:!0,description:"The offset used for pagination"}},required:["apiKeys","total"]}}}}}}}},async e=>{let r=e.context.session,i=e.query?.configId,n=e.query?.organizationId,a=e.query?.limit!=null?Number(e.query.limit):void 0,s=e.query?.offset!=null?Number(e.query.offset):void 0;n&&await K(e,r.user.id,n,"read");let o=n??r.user.id,l=n?"organization":"user",c=[];if(i){let{apiKeys:t}=await V(e,o,Ac(e.context,A,i),{limit:void 0,offset:void 0,sortBy:e.query?.sortBy,sortDirection:e.query?.sortDirection});c=t}else{let t=new Map;for(let e of A){let A="database"===e.storage?"database":e.customStorage?`custom:${e.configId??"default"}`:e.fallbackToDatabase?"secondary-storage-with-fallback":"secondary-storage";t.has(A)||t.set(A,e)}let r=await Promise.all([...t.values()].map(A=>V(e,o,A,{limit:void 0,offset:void 0,sortBy:e.query?.sortBy,sortDirection:e.query?.sortDirection}))),i=new Set;for(let{apiKeys:A}of r)for(let e of A)i.has(e.id)||(i.add(e.id),c.push(e))}let d=c.filter(e=>(A.find(A=>Ad(e.configId)?Ad(A.configId):A.configId===e.configId)?.references??"user")===l&&e.referenceId===o);i&&(d=d.filter(A=>Au(A.configId,i)));let u=d.length,g=d;void 0!==s&&(g=g.slice(s)),void 0!==a&&(g=g.slice(0,a)),t(e.context);let h=g.map(A=>{let{key:e,...t}=A;return{...t,metadata:S(A.metadata),permissions:t.permissions?(0,w.f)(t.permissions):null}}),I=A.find(A=>"database"===A.storage||A.fallbackToDatabase);return I&&await e.context.runInBackgroundOrAwait(M(e,g,I)),e.json({apiKeys:h,total:u,limit:a,offset:s})})}({configurations:e,schema:t,deleteAllExpiredApiKeys:Ah}),deleteAllExpiredApiKeys:function({deleteAllExpiredApiKeys:A}){return l.g.serverOnly({method:"POST"},async e=>{try{await A(e.context,!0)}catch(A){return e.context.logger.error("[API KEY PLUGIN] Failed to delete expired API keys:",A),e.json({success:!1,error:A})}return e.json({success:!0,error:null})})}({deleteAllExpiredApiKeys:Ah})}}({defaultKeyGenerator:async A=>{let e=(0,f.f)(A.length,"a-z","A-Z");return`${A.prefix||""}${e}`},configurations:t,schema:r});return{id:"api-key",version:"1.7.16",$ERROR_CODES:o,hooks:{before:[{matcher:A=>!!i(A),handler:(0,l.a)(async A=>{let{key:e,config:n}=i(A);if("string"!=typeof e)throw g.E.from("BAD_REQUEST",o.INVALID_API_KEY_GETTER_RETURN_TYPE);if(e.length<n.defaultKeyLength||n.customAPIKeyValidator&&!await n.customAPIKeyValidator({ctx:A,key:e}))throw g.E.from("FORBIDDEN",o.INVALID_API_KEY);let{apiKey:a}=await Ai({key:e,ctx:A,lookupOpts:n,configurations:t,schema:r,expectedConfigId:n.configId}),s=Ah(A.context).catch(e=>{A.context.logger.error("Failed to delete expired API keys:",e)});if(n.deferUpdates&&A.context.runInBackground(s),(n.references??"user")!=="user"){let A=o.INVALID_REFERENCE_ID_FROM_API_KEY;throw g.E.from("UNAUTHORIZED",A)}let l=await A.context.internalAdapter.findUserById(a.referenceId);if(!l){let A=o.INVALID_REFERENCE_ID_FROM_API_KEY;throw g.E.from("UNAUTHORIZED",A)}let d={user:l,session:{id:a.id,token:e,userId:a.referenceId,userAgent:A.request?.headers.get("user-agent")??null,ipAddress:A.request?(0,c.M)(A.request,A.context.options):null,createdAt:new Date,updatedAt:new Date,expiresAt:a.expiresAt||$(A.context.options.session?.expiresIn||604800,"ms")}};return(await C(e),A.context.session=d,"/get-session"===A.path)?d:{context:A}})}]},endpoints:{createApiKey:n.createApiKey,verifyApiKey:n.verifyApiKey,getApiKey:n.getApiKey,updateApiKey:n.updateApiKey,deleteApiKey:n.deleteApiKey,listApiKeys:n.listApiKeys,deleteAllExpiredApiKeys:n.deleteAllExpiredApiKeys},schema:r}}({schema:{apikey:{modelName:"apiKey"}},defaultPrefix:"aide_",requireName:!0,startingCharactersConfig:{shouldStore:!0,charactersLength:12},keyExpiration:{defaultExpiresIn:null,disableCustomExpiresTime:!1,minExpiresIn:1,maxExpiresIn:3650},rateLimit:{enabled:!1},enableSessionForAPIKeys:!1}),{id:"bearer",version:is.f,hooks:{before:[{matcher:A=>!!(A.request?.headers.get("authorization")||A.headers?.get("authorization")),handler:(0,l.a)(async A=>{let e,t=A.request?.headers.get("authorization")||A.headers?.get("Authorization");if(!t||"bearer "!==t.slice(0,7).toLowerCase())return;let r=t.slice(7).trim();if(!r)return;e=r.includes(".")?r.includes("%")?iT(r):r:iT((await (0,iH.k)("",r,A.context.secret)).replace("=",""));try{if(!await (0,iN.f)("SHA-256","base64urlnopad").verify(A.context.secret,e.split(".")[0],e.split(".")[1]))return}catch{return}let i=A.request?.headers||A.headers,n=new Headers({...Object.fromEntries(i?.entries())});return(0,ia.K)(n,A.context.authCookies.sessionToken.name,e),{context:{headers:n}}})}],after:[{matcher:A=>!0,handler:(0,l.a)(async A=>{let e=A.context.responseHeaders?.get("set-cookie");if(!e)return;let t=(0,ia.p)(e),r=A.context.authCookies.sessionToken.name,i=t.get(r);if(!i||!i.value||0===i["max-age"])return;let n=i.value,a=new Set((A.context.responseHeaders?.get("access-control-expose-headers")||"").split(",").map(A=>A.trim()).filter(Boolean));a.add("set-auth-token"),A.setHeader("set-auth-token",n),A.setHeader("Access-Control-Expose-Headers",Array.from(a).join(", "))})}]},options:void 0},(A=>{let e={storeToken:"plain",...A};async function t(A,t){return"hashed"===e.storeToken?await iG(t):"object"==typeof e.storeToken&&"type"in e.storeToken&&"custom-hasher"===e.storeToken.type?await e.storeToken.hash(t):t}async function r(A,r){let i=e?.generateToken?await e.generateToken(r,A):(0,f.f)(32),n=new Date(Date.now()+(e?.expiresIn??3)*6e4),a=await t(A,i);return await A.context.internalAdapter.createVerificationValue({value:r.session.token,identifier:`one-time-token:${a}`,expiresAt:n}),i}return{id:"one-time-token",version:is.f,endpoints:{generateOneTimeToken:(0,l.g)("/one-time-token/generate",{method:"GET",use:[h.Z]},async A=>{if(e?.disableClientRequest&&A.request)throw A.error("BAD_REQUEST",{message:"Client requests are disabled"});let t=A.context.session,i=await r(A,t);return A.json({token:i})}),verifyOneTimeToken:(0,l.g)("/one-time-token/verify",{method:"POST",body:ix},async A=>{let{token:r}=A.body,i=await t(A,r),n=await A.context.internalAdapter.consumeVerificationValue(`one-time-token:${i}`);if(!n)throw A.error("BAD_REQUEST",{message:"Invalid token"});let a=await A.context.internalAdapter.findSession(n.value);if(!a)throw A.error("BAD_REQUEST",{message:"Session not found"});if(e?.disableSetSessionCookie||await (0,A4.V)(A,a),a.session.expiresAt<new Date)throw A.error("BAD_REQUEST",{message:"Session expired"});return A.json(a)})},hooks:{after:[{matcher:()=>!0,handler:(0,l.a)(async A=>{if(A.context.newSession){if(!e?.setOttHeaderOnNewSession)return;let t=new Set((A.context.responseHeaders?.get("access-control-expose-headers")||"").split(",").map(A=>A.trim()).filter(Boolean));t.add("set-ott");let i=await r(A,A.context.newSession);A.setHeader("set-ott",i),A.setHeader("Access-Control-Expose-Headers",Array.from(t).join(", "))}})}]},options:A}})({disableClientRequest:!0,expiresIn:1,storeToken:"hashed"}),...Q?[Q]:[],...t?n$(A,t):[],(d=!1,{id:"next-cookies",version:is.f,hooks:{before:[{matcher:A=>"/get-session"===A.path,handler:(0,l.a)(async A=>{let e;if(d||(!function(A,e){let t=A.options.plugins||[];if(0===t.length)return;let r=t.findIndex(A=>A.id===e);-1===r||t.slice(r+1).some(A=>A.hooks&&Array.isArray(A.hooks.after)&&A.hooks.after.length>0)&&A.logger.warn(`[better-auth] Cookie integration plugin "${e}" should be placed last in the plugins array. Plugins with \`hooks.after\` running after it may set cookies that are not forwarded to the framework cookie store. Move your cookie integration plugin to the end of the \`plugins\` array to avoid missing \`Set-Cookie\` headers.`)}(A.context,"next-cookies"),d=!0),"_flag"in A&&"router"===A._flag)return;try{let{headers:A}=await io();e=await A()}catch{return}let t="1"===e.get("RSC"),r=!!e.get("next-action");t&&!r&&await (0,eU.w)(!0)})}],after:[{matcher:A=>!0,handler:(0,l.a)(async A=>{let e=A.context.responseHeaders;if((!("_flag"in A)||"router"!==A._flag)&&e instanceof Headers){let A,t=e?.get("set-cookie");if(!t)return;let r=(0,ia.p)(t);try{let{cookies:e}=await io();A=await e()}catch(A){if(A instanceof Error&&(A.message.startsWith("`cookies` was called outside a request scope.")||A.message.includes("Cannot find module")))return;throw A}r.forEach((e,t)=>{if(t)try{A.set(t,e.value,(0,ia.n)(e))}catch{}});return}})}]}})]},ii)})(A))),n1}A.s(["f",0,n4],792116);class n8 extends Error{status;constructor(A,e=401){super(A),this.status=e,this.name="PrincipalResolutionError"}}function n5(A){return/(?:^|;\s*)(?:__Secure-)?better-auth\.session_token=/.test(A.get("cookie")??"")}async function n2(A,e){if(Number(!!A.get("x-api-key")?.trim())+Number(!!A.get("authorization")?.trim())+Number(n5(A))>1)throw new n8("Provide exactly one application credential.",400);let t=A.get("x-api-key")?.trim()||null,r=function(A){let e=A.get("authorization");if(!e)return null;if(!e.startsWith("Bearer "))throw new n8("Authorization must use the Bearer scheme.");let t=e.slice(7).trim();if(!t)throw new n8("The bearer credential is empty.");return t}(A),i=n5(A);if(t){let A=await n4(),e=await A.api.verifyApiKey({body:{key:t}});if(!e.valid||!e.key)throw new n8("The API key is invalid or inactive.");return{kind:"apiKey",apiKeyId:e.key.id,userId:e.key.referenceId,name:e.key.name??null}}if(r?.startsWith("agent_")){if(!e)throw new n8("Agent credentials are not accepted by this endpoint.");let A=await e.authenticate(r);if(!A)throw new n8("The agent credential is invalid.");return{kind:"agent",agentId:A}}if(r||i){if(r&&3===r.split(".").length)throw new n8("OAuth access tokens are accepted only by the MCP endpoint.");let e=await n4(),t=await e.api.getSession({headers:A});if(!t?.session||!t.user)throw new n8("The session is invalid or expired.");return{kind:"user",userId:t.user.id,email:t.user.email,sessionId:t.session.id}}return{kind:"anonymous"}}A.s(["f",0,n2],847435)},914710,A=>{"use strict";A.i(792116),A.i(658978),A.i(847435),A.i(525796),A.s([],914710)},908323,A=>{"use strict";var e=A.i(135475);async function t(A){let t=await (0,e.U)(),r=await t.mcpAuthorization.findFirst({where:{id:A.authorizationId,userId:A.userId,clientId:A.clientId,revokedAt:null,user:{is:{id:A.userId}}}});return!!(r&&A.scopes.every(A=>r.scopes.split(" ").includes(A)))}A.i(792116),A.i(9416),A.i(847435),A.s(["f",0,t])},597812,A=>{"use strict";var e=A.i(666680),t=A.i(268573),r=A.i(845414),i=A.i(135475);A.i(256554);var n=A.i(118387),a=A.i(848201),s=A.i(520962),o=A.i(988438),l=A.i(682884);let c=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT","INVALID"]),d={agents:{include:{agent:!0}},jobs:{orderBy:{createdAt:"asc"}}};function u(A){return null!==A.lastSeenAt&&Date.now()-A.lastSeenAt.getTime()<=(0,n.z)(A)&&null===A.disconnectedAt}function g(A){try{let e=JSON.parse(A.capabilitiesJson);return Array.isArray(e)?e.filter(A=>"string"==typeof A):[]}catch{return[]}}function h(A){return null===A?null:JSON.parse(A)}function I(A){let e=h(A.payloadJson);return(A.kind===r.t?(0,r.A)(e).targets:(0,r.T)(e).targets).map(A=>A.path)}function p(A,e){let t=A===r.t?"delete":"size";return`Invalid Build Data ${t} result: ${e instanceof Error?e.message:String(e)}`}function C(A,e,t){try{for(let r of I(e)){let i=A.get(f(e.agentId,r));i&&(i.error=t)}}catch{}}function f(A,t){return(0,e.createHash)("sha256").update(A).update("\0").update(t).digest("base64url")}A.s(["f",0,class{agentControlService;initialized;nextHistoryPruneAt;historyPrune;constructor(A){this.agentControlService=A,this.initialized=!1,this.nextHistoryPruneAt=0,this.historyPrune=null,this.agentControlService.registerCompletionHandler(r.t,A=>this.projectDeletion(A))}async initialize(){this.initialized||(await this.pruneHistory(),this.initialized=!0)}async refresh(A){await this.initialize();let t=A?.trim()||(0,e.randomUUID)();return await this.ensureCollection(t),await this.getCollection(t)}async getCollection(A){await this.initialize();let e=await this.loadCollection(A);if(!e)return null;!e.finishedAt&&e.deadlineAt.getTime()<=Date.now()&&(await this.expireCollection(e),e=await this.loadCollection(A)??e);let t=await this.snapshot(e);if("COMPLETED"===t.status&&!e.finishedAt){let e=new Date,r=await (0,i.U)();await r.buildDataCollection.updateMany({where:{id:A,finishedAt:null},data:{finishedAt:e}}),t.finishedAt=e.toISOString()}return t}async *subscribe(A){await this.initialize();let e=a._H.iterate((0,a.I2)(A));try{let t=await this.getCollection(A);for(t&&(yield t);;){if((await e.next()).done)return;let t=await this.getCollection(A);t&&(yield t)}}finally{await e.return?.()}}async calculateSizes(A,e,t){let i=await this.requireCollection(A);return await this.createTargetJobs(i,e,t,r.G),await this.getCollection(A)}async deleteEntries(A,e,t,i=!1){let n=await this.requireCollection(A);return await this.createTargetJobs(n,e,t,r.t,i),await this.getCollection(A)}async history(A=100,e){await this.initialize(),await this.pruneHistory();let t=Math.max(1,Math.min(A,200)),r=await (0,i.U)(),n=e?await r.buildDataDeletionHistory.findUnique({where:{id:e},select:{id:!0,deletedAt:!0}}):null,a=await r.buildDataDeletionHistory.findMany({where:{deletedAt:{gte:new Date(Date.now()-7776e6)},...n?{OR:[{deletedAt:{lt:n.deletedAt}},{deletedAt:n.deletedAt,id:{lt:n.id}}]}:{}},orderBy:[{deletedAt:"desc"},{id:"desc"}],take:t+1}),s=a.length>t,o=a.slice(0,t);return{items:o,nextCursor:s?o.at(-1)?.id??null:null}}async clearHistory(){await this.initialize();let A=await (0,i.U)();return(await A.buildDataDeletionHistory.deleteMany()).count}async ensureCollection(A){let e=await (0,i.U)(),t=await e.buildDataCollection.findUnique({where:{id:A},select:{id:!0}});if(!t){let i=await this.agentControlService.listAgents();try{t=await e.buildDataCollection.create({data:{id:A,deadlineAt:new Date(Date.now()+6e4),agents:{create:i.map(A=>({agentId:A.id,initialStatus:u(A)?g(A).includes(r.F)?"QUEUING":"UNSUPPORTED":"OFFLINE"}))}},select:{id:!0}}),this.publish(A)}catch(r){if(!(t=await e.buildDataCollection.findUnique({where:{id:A},select:{id:!0}})))throw r}}await this.ensureScanJobs(A)}async ensureScanJobs(A){let e=await (0,i.U)(),n=await e.buildDataCollection.findUnique({where:{id:A},select:{deadlineAt:!0,finishedAt:!0}});if(!n||n.finishedAt||n.deadlineAt<=new Date)return;let a=await e.buildDataCollectionAgent.findMany({where:{collectionId:A,initialStatus:"QUEUING"},include:{agent:!0}}),s=new Set((await e.agentJob.findMany({where:{buildDataCollectionId:A,kind:r.F},select:{agentId:!0}})).map(A=>A.agentId));for(let i of a)if(!s.has(i.agentId))try{let n=await e.worktree.findMany({where:{missingAt:null,codebase:{agentId:i.agentId}},select:{id:!0,folder:!0}});await this.agentControlService.createJob({agentId:i.agentId,kind:r.F,payload:{mode:i.agent.derivedDataLocationMode,path:i.agent.derivedDataPath,...g(i.agent).includes(t.r)?{managedRoot:(0,o.j)(i.agent)?(0,o.T)((0,o.j)(i.agent)):null}:{},worktrees:n},idempotencyKey:`build-data:scan:${A}`,timeoutSeconds:45,buildDataCollectionId:A,visibility:"SYSTEM"})}catch(t){await e.buildDataCollectionAgent.update({where:{collectionId_agentId:{collectionId:A,agentId:i.agentId}},data:{initialStatus:"FAILED",error:t instanceof Error?t.message:String(t)}}),this.publish(A)}}async createTargetJobs(A,e,t,n,a=!1){let s=[...new Set(e)];if(!s.length)throw Error("Select at least one Derived Data entry");let o=new Map(A.entries.map(A=>[A.id,A])),l=s.map(A=>{let e=o.get(A);if(!e)throw Error("A selected Derived Data entry is no longer available");return e});if(n===r.t&&!a){let A=l.filter(A=>A.locked||A.activeResources.length>0);if(A.length)throw Error(`Explicit override confirmation is required to delete protected Derived Data: ${A.map(A=>A.name).join(", ")}`)}let c=new Map;for(let A of l){let e=c.get(A.agent.id)??[];e.push(A),c.set(A.agent.id,e)}let d=await (0,i.U)(),h=[];for(let[A,e]of c){let t=e[0].agent,r=await d.agent.findUnique({where:{id:A}});if(!r||!u(r))throw Error(`${t.name} is offline; reconnect it before running this operation`);if(!g(r).includes(n))throw Error(`${t.name} must be updated before this operation can run`);h.push({agentId:A,entries:e})}for(let{agentId:e,entries:i}of h){let a=n===r.t?[...new Map(i.filter(A=>!!A.worktreeId).map(A=>[A.worktreeId,A])).values()]:[],s=[];try{for(let A of a)await d.derivedDataCleanupLease.create({data:{worktreeId:A.worktreeId,agentId:e,path:A.path,source:"USER",expiresAt:new Date(Date.now()+6048e5)}}),s.push(A.worktreeId);let r=await this.agentControlService.createJob({agentId:e,kind:n,payload:{targets:i.map(({path:A,rootPath:e})=>({path:A,rootPath:e}))},idempotencyKey:`${n}:${A.id}:${t}:${e}`,timeoutSeconds:604800,buildDataCollectionId:A.id,visibility:"SYSTEM"});a.length&&await d.derivedDataCleanupLease.updateMany({where:{worktreeId:{in:a.map(A=>A.worktreeId)},jobId:null},data:{jobId:r.id}})}catch(A){throw s.length&&await d.derivedDataCleanupLease.deleteMany({where:{worktreeId:{in:s},source:"USER",jobId:null}}),A}}}async requireCollection(A){let e=await this.getCollection(A);if(!e)throw Error("Derived Data collection not found");if("COMPLETED"!==e.status)throw Error("Wait for the Derived Data scan to finish");return e}async loadCollection(A){return(await (0,i.U)()).buildDataCollection.findUnique({where:{id:A},include:d})}progress(A){let e=new Map(A.jobs.filter(A=>A.kind===r.F).map(A=>[A.agentId,A])),t=A.agents.map(A=>{let t=e.get(A.agentId),i=A.initialStatus,n=A.error,a=[];if("QUEUING"===A.initialStatus&&t&&(i=t.status,n=t.error,"SUCCEEDED"===t.status))try{a=(0,r.e)(h(t.resultJson)).warnings}catch(A){i="INVALID",n=A instanceof Error?A.message:String(A)}return{agent:A.agent,status:i,jobId:t?.id??null,error:n,warnings:a}}),i=t.filter(({status:A})=>"OFFLINE"!==A&&"UNSUPPORTED"!==A),n=i.filter(({status:A})=>c.has(A));return{agents:t,eligibleCount:i.length,finishedCount:n.length,successfulCount:i.filter(({status:A})=>"SUCCEEDED"===A).length}}async snapshot(A){let e=this.progress(A),t=await this.entries(A,!1);return{id:A.id,status:e.finishedCount===e.eligibleCount?"COMPLETED":"COLLECTING",createdAt:A.createdAt.toISOString(),deadlineAt:A.deadlineAt.toISOString(),finishedAt:A.finishedAt?.toISOString()??null,progress:e,entries:t}}async entries(A,e){let t=await (0,i.U)(),n=new Map(A.agents.map(A=>[A.agentId,A.agent])),a=await t.worktree.findMany({where:{missingAt:null,codebase:{agentId:{in:[...n.keys()]}}},include:{codebase:{select:{agentId:!0}}}}),o=new Map;for(let A of a){let e=o.get(A.codebase.agentId)??[];e.push(A),o.set(A.codebase.agentId,e)}let d=new Map;for(let e of A.jobs){let A;if(e.kind!==r.F||"SUCCEEDED"!==e.status)continue;let t=n.get(e.agentId);if(t){try{A=(0,r.e)(h(e.resultJson))}catch{continue}for(let r of A.entries){let A=(r.workspacePath?(o.get(e.agentId)??[]).filter(A=>(function(A,e){let t="/"===A?A:A.replace(/\/+$/,"");return e===t||e.startsWith(`${t}/`)})(A.folder,r.workspacePath)).sort((A,e)=>e.folder.length-A.folder.length):[])[0]??null,i=f(e.agentId,r.path);d.set(i,{id:i,name:r.name,kind:r.kind,status:"DEVICE_SUPPORT"===r.kind?"READY":"PENDING"===r.kind?"PENDING":"SHARED_CACHE"===r.kind?"SHARED_CACHE":A?"READY":"UNLINKED",workspacePath:r.workspacePath,worktreeId:A?.id??null,worktreePath:A?(0,s.b)(A.folder,t.baseRepoDirectory):null,sizeBytes:null,operation:"IDLE",error:null,agent:t,path:r.path,rootPath:r.rootPath,modifiedAt:r.modifiedAt,volumeId:r.volumeId,locked:!1,activeResources:[]})}}}for(let t of A.jobs){if(t.kind===r.G&&"SUCCEEDED"===t.status)try{for(let A of(0,r.i)(h(t.resultJson)).sizes){let e=d.get(f(t.agentId,A.path));e&&(e.sizeBytes=A.sizeBytes,e.error=A.error)}}catch(A){C(d,t,p(r.G,A))}if(t.kind===r.t&&"SUCCEEDED"===t.status)try{for(let A of(0,r.X)(h(t.resultJson)).deleted){let r=f(t.agentId,A.path),i=d.get(r);i&&(A.deleted&&!e?d.delete(r):i.error=A.error)}}catch(A){C(d,t,p(r.t,A))}if("QUEUED"===t.status||"RUNNING"===t.status){if(t.kind!==r.G&&t.kind!==r.t)continue;try{for(let A of I(t)){let e=d.get(f(t.agentId,A));e&&(e.operation=t.kind===r.t?"DELETING":"SIZING")}}catch{}}if("SUCCEEDED"!==t.status&&c.has(t.status)&&(t.kind===r.G||t.kind===r.t))try{for(let A of I(t)){let e=d.get(f(t.agentId,A));e&&(e.error=t.error||"Build Data operation failed")}}catch{}}let u=[...d.values()],g=u.map(A=>A.worktreeId).filter(A=>!!A),[m,E]=await Promise.all([t.derivedDataLock.findMany({where:{OR:u.map(A=>({agentId:A.agent.id,path:A.path}))},select:{agentId:!0,path:!0}}),(0,l.f)(g)]),w=new Set(m.map(A=>`${A.agentId}\0${A.path}`));for(let A of u)A.locked=w.has(`${A.agent.id}\0${A.path}`),A.activeResources=A.worktreeId?E.get(A.worktreeId)??[]:[];return u.sort((A,e)=>A.agent.name.localeCompare(e.agent.name)||(null===A.modifiedAt?1:null===e.modifiedAt?-1:new Date(A.modifiedAt).getTime()-new Date(e.modifiedAt).getTime())||A.name.localeCompare(e.name))}async setEntryLocked(A,t,r){let n=(await this.requireCollection(A)).entries.find(A=>A.id===t);if(!n)throw Error("Derived Data entry not found");let a=await (0,i.U)();return r?await a.derivedDataLock.upsert({where:{agentId_path:{agentId:n.agent.id,path:n.path}},create:{id:(0,e.randomUUID)(),agentId:n.agent.id,path:n.path},update:{}}):await a.derivedDataLock.deleteMany({where:{agentId:n.agent.id,path:n.path}}),this.publish(A),await this.getCollection(A)}async expireCollection(A){let e=await (0,i.U)(),t=new Set(A.jobs.filter(A=>A.kind===r.F).map(A=>A.agentId));await e.buildDataCollectionAgent.updateMany({where:{collectionId:A.id,initialStatus:"QUEUING",agentId:{notIn:[...t]}},data:{initialStatus:"TIMED_OUT"}}),await this.agentControlService.timeoutBuildDataCollectionJobs(A.id),this.publish(A.id)}async projectDeletion(A){let t;if("SUCCEEDED"!==A.status||!A.resultJson)return;await this.pruneHistory();let n=await (0,i.U)();if(await n.buildDataDeleteProjection.findUnique({where:{jobId:A.id}}))return;try{t=(0,r.X)(h(A.resultJson)).deleted.filter(A=>A.deleted)}catch(t){let e=p(r.t,t);try{await n.buildDataDeleteProjection.create({data:{jobId:A.id,error:e}})}catch(e){if(!await n.buildDataDeleteProjection.findUnique({where:{jobId:A.id}}))throw e}return}if(!t.length)return void await n.buildDataDeleteProjection.create({data:{jobId:A.id}});let a=(0,r.A)(h(A.payloadJson)),s=A.buildDataCollectionId?await this.loadCollection(A.buildDataCollectionId):null,o=new Map((s?await this.entries(s,!0):[]).filter(e=>e.agent.id===A.agentId).map(A=>[A.path,A])),l=new Map(a.targets.map(A=>[A.path,A])),c=await n.agent.findUnique({where:{id:A.agentId}});if(c)try{await n.$transaction(async r=>{if(!await r.buildDataDeleteProjection.findUnique({where:{jobId:A.id}}))for(let i of(await r.buildDataDeleteProjection.create({data:{jobId:A.id}}),t)){let t=o.get(i.path),n=l.get(i.path),s=n?.worktreeId??t?.worktreeId??null,d=s?(await r.worktree.findUnique({where:{id:s},select:{id:!0}}))?.id??null:null;await r.buildDataDeletionHistory.create({data:{id:(0,e.randomUUID)(),agentId:A.agentId,agentName:c.name,folderName:n?.name??t?.name??i.path,worktreeId:d,worktreePath:n?.worktreePath??t?.worktreePath??null,source:a.source,entryKind:n?.kind??t?.kind??"PROJECT",jobId:A.id,targetKey:t?.id??f(A.agentId,i.path)}})}})}catch(e){if(!await n.buildDataDeleteProjection.findUnique({where:{jobId:A.id}}))throw e}}async pruneHistory(){if(this.historyPrune)return this.historyPrune;if(!(Date.now()<this.nextHistoryPruneAt)){this.historyPrune=(async()=>{let A=await (0,i.U)();await A.buildDataDeletionHistory.deleteMany({where:{deletedAt:{lt:new Date(Date.now()-7776e6)}}}),this.nextHistoryPruneAt=Date.now()+6e4})();try{await this.historyPrune}finally{this.historyPrune=null}}}publish(A){let t={id:A,changeId:(0,e.randomUUID)()};a._H.publish(a.oz,{buildDataCollectionChanged:t}),a._H.publish((0,a.I2)(A),{buildDataCollectionChanged:t})}}])},46208,A=>{"use strict";A.i(597812),A.s([])},354473,A=>A.a(async(e,t)=>{try{A.s(["cachedArtifact",()=>I,"materializeArtifact",()=>f]);var r=A.i(666680),i=A.i(912714),n=A.i(660526),a=A.i(750227),s=A.i(135475),o=A.i(826587),l=A.i(604104),c=e([l]);[l]=c.then?(await c)():c;let m=process.env.ARTIFACT_CACHE_DIRECTORY?.trim()||(0,a.join)((0,n.tmpdir)(),"ade-build-artifact-cache"),E=Number(process.env.ARTIFACT_CACHE_MAX_BYTES)||0x140000000,w=globalThis,y=w.buildArtifactMaterializations??(w.buildArtifactMaterializations=new Map);async function d(A,e){try{await (0,i.rename)(A,e);return}catch(A){if("EXDEV"!==A.code)throw A}let t=`${e}.${(0,r.randomUUID)()}.incoming`;try{await (0,i.copyFile)(A,t),await (0,i.rename)(t,e),await (0,i.rm)(A,{force:!0})}finally{await (0,i.rm)(t,{force:!0}).catch(()=>{})}}async function u(A){try{let e=JSON.parse(await (0,i.readFile)(A,"utf8"));if(!e||"object"!=typeof e)return null;let{filename:t,contentType:r,size:n}=e;if("string"!=typeof t||"string"!=typeof r||"number"!=typeof n)return null;return{filename:t,contentType:r,size:n}}catch{return null}}async function g(A){let e=(0,a.join)(m,A),t=await u(`${e}.json`);if(!t)return null;try{let r=await (0,i.stat)(e);if(!r.isFile()||r.size!==t.size)return null;let n=new Date;return await (0,i.utimes)(e,n,n).catch(()=>{}),{path:e,etag:`"${A}"`,...t}}catch{return null}}async function h(A,e){var t;let i=(0,l.f)(),n=await i.buildsService.artifactForInstall(A,e);if(!n)throw Error("Build artifact not found");return{artifact:n,key:(t=n.checksum??n.createdAt,(0,r.createHash)("sha1").update(`${e}:${t}`).digest("hex"))}}async function I(A,e){let{key:t}=await h(A,e);return g(t)}async function p(A){let e,t=new Set;try{let A=await (0,s.U)();for(let e of(await A.buildArtifactTransfer.findMany({where:{status:{in:["READY","DOWNLOADING"]},expiresAt:{gt:new Date},stagingPath:{not:null}},select:{stagingPath:!0}})))e.stagingPath&&t.add(e.stagingPath)}catch{}try{e=await (0,i.readdir)(m)}catch{return}let r=[],n=Date.now()-216e5;for(let s of e){if(s.endsWith(".json"))continue;let e=(0,a.join)(m,s);try{let a=await (0,i.stat)(e);if(!a.isFile())continue;if(s.endsWith(".incoming")){a.mtimeMs<n&&await (0,i.rm)(e,{force:!0}).catch(()=>{});continue}r.push({path:e,size:a.size,mtimeMs:a.mtimeMs,keep:s===A||t.has(e)})}catch{continue}}r.sort((A,e)=>A.mtimeMs-e.mtimeMs);let o=r.reduce((A,e)=>A+e.size,0);for(let A of r)!A.keep&&(o<=E&&A.mtimeMs>=n||(await (0,i.rm)(A.path,{force:!0}).catch(()=>{}),await (0,i.rm)(`${A.path}.json`,{force:!0}).catch(()=>{}),o-=A.size))}async function C(A,e,t,n){let s=(0,r.randomUUID)(),c=(0,l.f)(),u=await c.buildsService.getBuild(A);if(!u?.agentId)throw Error("Build agent is unavailable");let g=Math.min(18e5,12e4+(n??0)/1e3),h=null;try{let[r]=await Promise.all([(0,o.e)(s,u.agentId,g),c.buildsService.prepareArtifactDownload(A,e,s,g)]);h=r.path,await (0,i.mkdir)(m,{recursive:!0,mode:448});let n=(0,a.join)(m,t);await d(r.path,n),h=null;let l=(await (0,i.stat)(n)).size,I={filename:r.filename,contentType:r.contentType,size:l};return await (0,i.writeFile)(`${n}.json`,JSON.stringify(I),{mode:384}),await p(t).catch(()=>{}),{path:n,etag:`"${t}"`,...I}}catch(A){throw(0,o.L)(s,A),h&&await (0,i.rm)(h,{force:!0}).catch(()=>{}),A}}async function f(A,e){let{artifact:t,key:r}=await h(A,e),i=await g(r);if(i)return i;let n=y.get(r);if(n)return n;let a=C(A,e,r,t.sizeBytes).finally(()=>{y.delete(r)});return y.set(r,a),a}t()}catch(A){t(A)}},!1),250746,A=>A.a(async(e,t)=>{try{A.s(["buildArtifactFileChecksum",()=>u,"failBuildArtifactTransferForJob",()=>g,"writeArtifactTransferBytes",()=>d]);var r=A.i(666680),i=A.i(902157);A.i(912714);var n=A.i(660526),a=A.i(750227),s=A.i(135475);A.i(256554);var o=A.i(848201),l=A.i(354473),c=e([l]);[l]=c.then?(await c)():c,process.env.ARTIFACT_TRANSFER_MAX_BYTES,process.env.ARTIFACT_TRANSFER_DIRECTORY?.trim()||(0,a.join)((0,n.tmpdir)(),"ade-build-artifact-transfers");let h=globalThis;async function d(A,e,t){let r=0;for(;r<e.byteLength;){let i=e.byteLength-r,{bytesWritten:n}=await A.write(e,r,i,t+r);if(!Number.isSafeInteger(n)||n<=0||n>i)throw Error("Artifact transfer file write made no progress");r+=n}}async function u(A){let e=(0,r.createHash)("sha256");for await(let t of(0,i.createReadStream)(A))e.update(t);return e.digest("hex")}async function g(A,e){let t=await (0,s.U)(),r=await t.buildArtifactTransfer.findFirst({where:{OR:[{sourceJobId:A},{targetJobId:A}]},include:{artifact:!0}});if(!(!r||["SUCCEEDED","FAILED"].includes(r.status))){var i;await t.$transaction([t.buildArtifactTransfer.update({where:{id:r.id},data:{status:"FAILED",error:e,finishedAt:new Date}}),t.buildDeployment.updateMany({where:{transferId:r.id,status:{in:["QUEUED","TRANSFERRING"]}},data:{status:"FAILED",error:e,finishedAt:new Date}})]),i=r.artifact.buildId,o._H.publish((0,o.cm)(i),{buildChanged:{id:i}}),o._H.publish(o.$A,{buildsChanged:{id:i}})}}h.buildArtifactTransferLocks??(h.buildArtifactTransferLocks=new Map),t()}catch(A){t(A)}},!1),826587,A=>{"use strict";A.i(902157),A.i(912714),A.i(660526),A.i(750227),A.i(81111),A.i(188646);let e=globalThis,t=e.buildArtifactTransfers??(e.buildArtifactTransfers=new Map);A.s(["L",0,function(A,e){let r=t.get(A);r&&(t.delete(A),clearTimeout(r.timeout),r.reject(e instanceof Error?e:Error(String(e))))},"e",0,function(A,e,r=17e4){return new Promise((i,n)=>{let a=setTimeout(()=>{t.delete(A),n(Error("The agent did not upload the artifact in time"))},r);a.unref(),t.set(A,{agentId:e,resolve:i,reject:n,timeout:a})})}])},988438,A=>{"use strict";var e=A.i(750227);function t(A){return(/^[a-z]:[\\/]/i.test(A)||A.startsWith("\\\\")?e.win32:e.posix).join(A,".worktree-derived-data")}A.s(["j",0,function(A){var t;return A.buildsDirectory??((t=A.baseRepoDirectory)?/^[a-z]:[\\/]/i.test(t)||t.startsWith("\\\\")?e.win32.join(t,"Builds"):e.posix.join(t,"Builds"):null)},"T",0,t,"r",0,function(A,r){if(!r||"."===r||".."===r||/[\\/\0]/.test(r))throw Error("Worktree identifier cannot be used as a Derived Data directory");return(/^[a-z]:[\\/]/i.test(A)||A.startsWith("\\\\")?e.win32:e.posix).join(t(A),r)}])},13666,A=>{"use strict";A.i(790142);var e=A.i(824236),t=A.i(861034);let r=A=>e.f.sql`
821
+ `)}}(e={...e,secret:r,baseURL:u?e.baseURL:h?new URL(h).origin:"",basePath:e.basePath||"/api/auth",plugins:o.concat(l)},d);let w=e.advanced?.ipAddress?.trustedProxies;if(w&&w.length>0){let A=(0,c.p)(w);A.length>0&&d.warn(`Ignoring invalid \`advanced.ipAddress.trustedProxies\` entries: ${A.join(", ")}. Each entry must be an IP address or CIDR range.`)}let y=(0,A4.e)(e),Q=(0,Ay.R)(e),B=(await Promise.all(Object.entries(e.socialProviders||{}).map(async([A,e])=>{let t="function"==typeof e?await e():e;if(null==t||!1===t.enabled)return null;t.clientId||d.warn(`Social provider ${A} is missing clientId or clientSecret`);let r=t7[A](t);return r.disableImplicitSignUp=t.disableImplicitSignUp,r}))).filter(A=>null!==A),D=({model:A,size:t})=>{if("function"==typeof e.advanced?.generateId)return e.advanced.generateId({model:A,size:t});let r=e?.advanced?.database?.generateId;return"function"==typeof r?r({model:A,size:t}):"uuid"===r?crypto.randomUUID():"serial"!==r&&!1!==r&&(0,E.f)(t)},{publish:k}=await it(e,{adapter:A.id,database:"function"==typeof e.database?"adapter":t(e.database)}),S=new Set(e.plugins.map(A=>A.id)),b=await ec(e),M=await eh(e),O={appName:e.appName||"Better Auth",baseURL:h||"",version:(0,rJ.I)(),socialProviders:B,options:e,oauthConfig:{storeStateStrategy:e.account?.storeStateStrategy||(s?"database":"cookie"),skipStateCookieCheck:!!e.account?.skipStateCookieCheck},tables:Q,trustedOrigins:b,trustedProviders:M,isTrustedOrigin(A,e){return this.trustedOrigins.some(t=>AZ(A,t,e))},sessionConfig:{updateAge:e.session?.updateAge!==void 0?e.session.updateAge:86400,expiresIn:e.session?.expiresIn||604800,freshAge:e.session?.freshAge===void 0?86400:e.session.freshAge,cookieRefreshCache:(n=e.session?.cookieCache?.refreshCache,a=e.session?.cookieCache?.maxAge||300,s&&n?(d.warn("[better-auth] `session.cookieCache.refreshCache` is enabled while `database` or `secondaryStorage` is configured. `refreshCache` is meant for stateless (DB-less) setups. Disabling `refreshCache` — remove it from your config to silence this warning."),!1):!1!==n&&void 0!==n&&(!0===n?{enabled:!0,updateAge:Math.floor(.2*a)}:{enabled:!0,updateAge:void 0!==n.updateAge?n.updateAge:Math.floor(.2*a)}))},secret:r,secretConfig:i,rateLimit:{...e.rateLimit,enabled:e.rateLimit?.enabled??ea.C,window:e.rateLimit?.window||10,max:e.rateLimit?.max||100,storage:e.rateLimit?.storage||(e.secondaryStorage?"secondary-storage":"memory")},authCookies:y,logger:d,generateId:D,session:null,secondaryStorage:e.secondaryStorage,password:{hash:e.emailAndPassword?.password?.hash||A1.Z,verify:e.emailAndPassword?.password?.verify||A1.B,config:{minPasswordLength:e.emailAndPassword?.minPasswordLength||8,maxPasswordLength:e.emailAndPassword?.maxPasswordLength||128},checkPassword:eE},setNewSession(A){this.newSession=A},newSession:null,adapter:A,internalAdapter:en(A,{options:e,logger:d,hooks:e.databaseHooks?[{source:"user",hooks:e.databaseHooks}]:[],generateId:D}),createAuthCookie:(0,A4.g)(e),async runMigrations(){throw new g.p("runMigrations will be set by the specific init implementation")},publishTelemetry:k,skipCSRFCheck:!!e.advanced?.disableCSRFCheck,skipOriginCheck:e.advanced?.disableOriginCheck!==void 0?e.advanced.disableOriginCheck:!!(0,ea.s)(),runInBackground:e.advanced?.backgroundTasks?.handler??(A=>{A.catch(()=>{})}),async runInBackgroundOrAwait(A){try{e.advanced?.backgroundTasks?.handler?A instanceof Promise&&e.advanced.backgroundTasks.handler(A.catch(A=>{d.error("Failed to run background task:",A)})):await A}catch(A){d.error("Failed to run background task:",A)}},getPlugin:A=>e.plugins.find(e=>e.id===A)??null,hasPlugin:A=>S.has(A)},v=el(O);return(0,A0.f)(v)&&await v,O.checkSchema=(0,Af.f)(O.adapter),O.explicitSchemaCheck=(0,Af.j)(O.adapter),O}let ii=async A=>{let e=await AD(A),t=await ir(e,A,A=>(0,AS.getKyselyDatabaseType)(A)||"unknown");return t.runMigrations=async function(){if(!A.database||"updateMany"in A.database)throw new g.p("Database is not provided or it's an adapter. Migrations are only supported with a database instance.");let{runMigrations:e}=await AJ(A);await e()},t};var ia=A.i(779198),is=A.i(595544);let io=()=>i??=A.A(162916).catch(A=>{throw i=void 0,A}),il=(0,D.y)({user:["create","list","set-role","ban","impersonate","impersonate-admins","delete","set-password","set-email","set-phone","get","update"],session:["list","revoke","delete"]}),ic={admin:il.newRole({user:["create","list","set-role","ban","impersonate","delete","set-password","set-email","set-phone","get","update"],session:["list","revoke","delete"]}),user:il.newRole({user:[],session:[]})},id=(0,s.f)({FAILED_TO_CREATE_USER:"Failed to create user",USER_ALREADY_EXISTS:"User already exists.",USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL:"User already exists. Use another email.",YOU_CANNOT_BAN_YOURSELF:"You cannot ban yourself",YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE:"You are not allowed to change users role",YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS:"You are not allowed to create users",YOU_ARE_NOT_ALLOWED_TO_LIST_USERS:"You are not allowed to list users",YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS:"You are not allowed to list users sessions",YOU_ARE_NOT_ALLOWED_TO_BAN_USERS:"You are not allowed to ban users",YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS:"You are not allowed to impersonate users",YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS:"You are not allowed to revoke users sessions",YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS:"You are not allowed to delete users",YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD:"You are not allowed to set users password",BANNED_USER:"You have been banned from this application",YOU_ARE_NOT_ALLOWED_TO_GET_USER:"You are not allowed to get user",NO_DATA_TO_UPDATE:"No data to update",YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS:"You are not allowed to update users",YOU_CANNOT_REMOVE_YOURSELF:"You cannot remove yourself",YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE:"You are not allowed to set a non-existent role value",YOU_CANNOT_IMPERSONATE_ADMINS:"You cannot impersonate admins",INVALID_ROLE_TYPE:"Invalid role type",YOU_ARE_NOT_ALLOWED_TO_SET_USERS_EMAIL:"You are not allowed to update users email",YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PHONE_NUMBER:"You are not allowed to update users phone number",PASSWORD_CANNOT_BE_UPDATED_VIA_UPDATE_USER:"Password cannot be updated through update-user. Use the set-user-password endpoint instead",USER_ID_CANNOT_BE_UPDATED:"User id cannot be updated"}),iu=async A=>{let e=A.context.returned;return e?e instanceof Response?200!==e.status?null:await e.clone().json():(0,ew.f)(e)?null:e:null},ig=A=>{if(A.userId&&A.options?.adminUserIds?.includes(A.userId))return!0;if(!A.permissions)return!1;let e=(A.role||A.options?.defaultRole||"user").split(","),t=A.options?.roles||ic;for(let r of e)if(t[r]?.authorize(A.permissions)?.success)return!0;return!1};var ih=A.i(752067);let iI=(0,l.a)(async A=>{let e=await (0,h.M)(A);if(!e)throw g.E.fromStatus("UNAUTHORIZED");return{session:e}});function ip(A){return Array.isArray(A)?A.join(","):A}let iC=y.object({userId:Q.f.string().meta({description:"The user id"}),role:y.union([y.string().meta({description:"The role to set. `admin` or `user` by default"}),y.array(y.string().meta({description:"The roles to set. `admin` or `user` by default"}))]).meta({description:"The role to set, this can be a string or an array of strings. Eg: `admin` or `[admin, user]`"})}),im=y.object({id:y.string().meta({description:"The id of the User"})}),iE=y.object({email:y.string().meta({description:"The email of the user"}),password:y.string().optional().meta({description:"The password of the user. If not provided, the user will be created without a credential account (useful for magic link or social login only users)."}),name:y.string().meta({description:"The name of the user"}),role:y.union([y.string().meta({description:"The role of the user"}),y.array(y.string().meta({description:"The roles of user"}))]).optional().meta({description:'A string or array of strings representing the roles to apply to the new user. Eg: "user"'}),data:y.record(y.string(),y.any()).optional().meta({description:"Extra fields for the user. Including custom additional fields."})}),iw=y.object({userId:Q.f.string().meta({description:"The user id"}),data:y.record(y.any(),y.any()).meta({description:"The user data to update"})}),iy=y.object({searchValue:y.string().optional().meta({description:'The value to search for. Eg: "some name"'}),searchField:y.enum(["email","name"]).meta({description:'The field to search in, defaults to email. Can be `email` or `name`. Eg: "name"'}).optional(),searchOperator:y.enum(["contains","starts_with","ends_with"]).meta({description:'The operator to use for the search. Can be `contains`, `starts_with` or `ends_with`. Eg: "contains"'}).optional(),limit:y.string().meta({description:"The number of users to return"}).or(y.number()).optional(),offset:y.string().meta({description:"The offset to start from"}).or(y.number()).optional(),sortBy:y.string().meta({description:"The field to sort by"}).optional(),sortDirection:y.enum(["asc","desc"]).meta({description:"The direction to sort by"}).optional(),filterField:y.string().meta({description:"The field to filter by"}).optional(),filterValue:y.string().meta({description:"The value to filter by"}).or(y.number()).or(y.boolean()).or(y.array(y.string())).or(y.array(y.number())).optional(),filterOperator:y.enum(ih.f).meta({description:"The operator to use for the filter"}).optional()}),iQ=y.object({userId:Q.f.string().meta({description:"The user id"})}),iB=y.object({userId:Q.f.string().meta({description:"The user id"})}),iD=y.object({userId:Q.f.string().meta({description:"The user id"}),banReason:y.string().meta({description:"The reason for the ban"}).optional(),banExpiresIn:y.number().meta({description:"The number of seconds until the ban expires"}).optional()}),ik=y.object({userId:Q.f.string().meta({description:"The user id"})}),iS=y.object({sessionToken:y.string().meta({description:"The session token"})}),ib=y.object({userId:Q.f.string().meta({description:"The user id"})}),iM=y.object({userId:Q.f.string().meta({description:"The user id"})}),iO=y.object({newPassword:y.string().nonempty("newPassword cannot be empty").meta({description:"The new password"}),userId:Q.f.string().nonempty("userId cannot be empty").meta({description:"The user id"})}),iv=y.object({userId:Q.f.string().optional().meta({description:'The user id. Eg: "user-id"'}),role:y.string().optional().meta({description:'The role to check permission for. Eg: "admin"'})}).and(y.xor([y.object({permission:y.record(y.string(),y.array(y.string()))}),y.object({permissions:y.record(y.string(),y.array(y.string()))})])),iR={user:{fields:{role:{type:"string",required:!1,input:!1},banned:{type:"boolean",defaultValue:!1,required:!1,input:!1},banReason:{type:"string",required:!1,input:!1},banExpires:{type:"date",required:!1,input:!1}}},session:{fields:{impersonatedBy:{type:"string",required:!1,input:!1}}}};var iH=A.i(259968),iN=A.i(976394);function iT(A){try{return decodeURIComponent(A)}catch{return A}}let iL=(0,s.f)({INVALID_OAUTH_CONFIGURATION:"Invalid OAuth configuration",TOKEN_URL_NOT_FOUND:"Invalid OAuth configuration. Token URL not found."}),iU=A=>{try{return(0,tj.f)(A)}catch{return null}};async function i_(A,e,t){let r=await (0,tz.f)(A,{method:"GET",headers:e,signal:t?AbortSignal.timeout(t):void 0});if(r.error||!r.data)return null;if(r.data.issuer)try{new URL(r.data.issuer)}catch{return null}return r.data}async function iP(A,e,t){if(A.idToken){let e=t??iU(A.idToken);if(e?.sub&&e?.email)return{id:e.sub,emailVerified:e1(e.email_verified),image:e.picture,...e}}if(!e||!A.accessToken)return null;let r=await (0,tz.f)(e,{method:"GET",headers:{Authorization:`Bearer ${A.accessToken}`}});return r.error||!r.data?null:{...r.data,email:r.data.email,emailVerified:e1(r.data.email_verified),image:r.data.picture,name:r.data.name}}let iG=async A=>{let e=await (0,u.f)("SHA-256").digest(new TextEncoder().encode(A));return d.W.encode(new Uint8Array(e),{padding:!1})},ix=y.object({token:y.string().meta({description:'The token to verify. Eg: "some-token"'})}),iJ=A=>{let e={storeToken:"plain",...A};async function t(A,t){return"hashed"===e.storeToken?await iG(t):"object"==typeof e.storeToken&&"type"in e.storeToken&&"custom-hasher"===e.storeToken.type?await e.storeToken.hash(t):t}async function r(A,r){let i=e?.generateToken?await e.generateToken(r,A):(0,f.f)(32),n=new Date(Date.now()+(e?.expiresIn??3)*6e4),a=await t(A,i);return await A.context.internalAdapter.createVerificationValue({value:r.session.token,identifier:`one-time-token:${a}`,expiresAt:n}),i}return{id:"one-time-token",version:is.f,endpoints:{generateOneTimeToken:(0,l.g)("/one-time-token/generate",{method:"GET",use:[h.Z]},async A=>{if(e?.disableClientRequest&&A.request)throw A.error("BAD_REQUEST",{message:"Client requests are disabled"});let t=A.context.session,i=await r(A,t);return A.json({token:i})}),verifyOneTimeToken:(0,l.g)("/one-time-token/verify",{method:"POST",body:ix},async A=>{let{token:r}=A.body,i=await t(A,r),n=await A.context.internalAdapter.consumeVerificationValue(`one-time-token:${i}`);if(!n)throw A.error("BAD_REQUEST",{message:"Invalid token"});let a=await A.context.internalAdapter.findSession(n.value);if(!a)throw A.error("BAD_REQUEST",{message:"Session not found"});if(e?.disableSetSessionCookie||await (0,A4.V)(A,a),a.session.expiresAt<new Date)throw A.error("BAD_REQUEST",{message:"Session expired"});return A.json(a)})},hooks:{after:[{matcher:()=>!0,handler:(0,l.a)(async A=>{if(A.context.newSession){if(!e?.setOttHeaderOnNewSession)return;let t=new Set((A.context.responseHeaders?.get("access-control-expose-headers")||"").split(",").map(A=>A.trim()).filter(Boolean));t.add("set-ott");let i=await r(A,A.context.newSession);A.setHeader("set-ott",i),A.setHeader("Access-Control-Expose-Headers",Array.from(t).join(", "))}})}]},options:A}};var ij=A.i(270133),iY=A.i(135475),iF=A.i(768843);function iz(A,e){return A[e]?.trim()||void 0}function iq(A,e){let t=iz(A,e);if(!t)throw Error(`${e} is required for AUTH_MODE.`);return t}function iV(A=process.env){let e=function(A){let e=iz(A,"AUTH_MODE")??"password";if("password"!==e&&"oidc"!==e&&"both"!==e)throw Error('AUTH_MODE must be "password", "oidc", or "both".');return e}(A),t=(0,ij.U)(A);return{secret:(0,iF.h)(A).authSecret,origins:t,baseURL:t.canonical,trustProxyHeaders:function(A){let e=iz(A,"TRUST_PROXY_HEADERS")?.toLowerCase();if(!e||"false"===e||"0"===e)return!1;if("true"===e||"1"===e)return!0;throw Error("TRUST_PROXY_HEADERS must be true, false, 1, or 0.")}(A),mode:e,provider:function(A,e){if("password"===e)return null;let t=iz(A,"AUTH_OAUTH_DISCOVERY_URL"),r=iz(A,"AUTH_OAUTH_AUTHORIZATION_URL"),i=iz(A,"AUTH_OAUTH_TOKEN_URL"),n=iz(A,"AUTH_OAUTH_USER_INFO_URL"),a=iz(A,"AUTH_OAUTH_ISSUER"),s=!!(r||i||n),o=r&&i&&n;if(t&&s)throw Error("OIDC configuration must use either discovery or explicit endpoints, not both.");if(!t&&!o)throw Error("OIDC authentication requires AUTH_OAUTH_DISCOVERY_URL or all of AUTH_OAUTH_AUTHORIZATION_URL, AUTH_OAUTH_TOKEN_URL, and AUTH_OAUTH_USER_INFO_URL.");if(s&&!o)throw Error("Explicit OAuth configuration must include authorization, token, and user-info URLs.");if(o&&!a)throw Error("AUTH_OAUTH_ISSUER is required with explicit OAuth endpoints.");let l=iq(A,"AUTH_OAUTH_SCOPES").split(",").map(A=>A.trim()).filter(Boolean);if(0===l.length)throw Error("AUTH_OAUTH_SCOPES must contain at least one scope.");return{providerId:iq(A,"AUTH_OAUTH_PROVIDER_ID"),displayName:iq(A,"AUTH_OAUTH_PROVIDER_NAME"),clientId:iq(A,"AUTH_OAUTH_CLIENT_ID"),clientSecret:iq(A,"AUTH_OAUTH_CLIENT_SECRET"),scopes:l,requireIssuerValidation:function(A){let e=iz(A,"AUTH_OAUTH_REQUIRE_ISSUER_VALIDATION")?.toLowerCase();if(!e||"false"===e||"0"===e)return!1;if("true"===e||"1"===e)return!0;throw Error("AUTH_OAUTH_REQUIRE_ISSUER_VALIDATION must be true, false, 1, or 0.")}(A),discoveryUrl:t,issuer:a,authorizationUrl:r,tokenUrl:i,userInfoUrl:n}}(A,e)}}function iK(A){return"password"===A||"both"===A}function iW(A){return"oidc"===A||"both"===A}A.s(["L",0,iV,"_",0,iW,"Z",0,iK],658978);var i$=A.i(812057);let iZ=RegExp(String.raw`((?:"?(?:authorization|password|access[_-]?token|refresh[_-]?token|id[_-]?token|session[_-]?token|client[_-]?secret|client_assertion|code_verifier|code|token|secret|privateKey)"?)\s*:\s*)(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^,\n}\]]+)`,"gi");function iX(A){return A.replace(iZ,'$1"[REDACTED]"').replace(/\b(Bearer|DPoP)\s+[A-Za-z0-9._~+\/-]+/gi,"$1 [REDACTED]").replace(/([?&](?:access_token|refresh_token|client_secret|code|code_verifier)=)[^&\s]+/gi,"$1[REDACTED]")}function i0(A,e,...t){let r=[`${new Date().toISOString()} ${A.toUpperCase()} [Better Auth]: ${e}`,...t.map(A=>"string"==typeof A?A:(0,i$.inspect)(A,{depth:6,breakLength:120}))].map(iX);"error"===A?console.error(...r):"warn"===A?console.warn(...r):console.log(...r)}function i1(A){return"string"==typeof A&&A.length>0?A:void 0}async function i4(A,e){try{return await fetch(A,{headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${e}`,"User-Agent":"AI-Development-Environment"}})}catch{return null}}async function i8(A,e){let t,r=await i4(A,e);if(!r?.ok)return null;let i=await r.json(),n=i1(i.email),a=await i4(((t=new URL(A)).pathname=`${t.pathname.replace(/\/$/,"")}/emails`,t.toString()),e),s=a?.ok?await a.json():[],o=Array.isArray(s)?s:[],l=o.find(A=>!0===A.primary)??o[0],c=n??i1(l?.email),d=o.find(A=>i1(A.email)===c);return{...i,email:c,emailVerified:d?.verified===!0,image:i1(i.avatar_url),name:i1(i.name)??i1(i.login)??""}}var i5=A.i(666680);let i2="default";async function i9(){let A=await (0,iY.U)();return await A.authSettings.findUnique({where:{id:i2}})??await A.authSettings.upsert({where:{id:i2},create:{id:i2},update:{}})}async function i6({allowWhenRegistrationClosed:A=!1}={}){let e=await (0,iY.U)(),t=await i9();if(t.bootstrapCompleted){if(!t.registrationEnabled&&!A)throw new g.E("FORBIDDEN",{message:"Account registration is disabled."});return}if(await e.user.count()>0){if(await e.authSettings.update({where:{id:i2},data:{bootstrapCompleted:!0,registrationEnabled:!1,bootstrapClaimId:null,bootstrapClaimedAt:null}}),A)return;throw new g.E("FORBIDDEN",{message:"Account registration is disabled."})}let r=new Date(Date.now()-18e4),i=(0,i5.randomUUID)();if(1!==(await e.authSettings.updateMany({where:{id:i2,bootstrapCompleted:!1,OR:[{bootstrapClaimedAt:null},{bootstrapClaimedAt:{lt:r}}]},data:{bootstrapClaimId:i,bootstrapClaimedAt:new Date}})).count)throw new g.E("CONFLICT",{message:"The initial account is already being created. Try again shortly."})}async function i3(){let A=await (0,iY.U)();await A.authSettings.updateMany({where:{id:i2,bootstrapCompleted:!1},data:{bootstrapCompleted:!0,registrationEnabled:!1,bootstrapClaimId:null,bootstrapClaimedAt:null}})}let i7={user:{create:{before:async(A,e)=>(await i6({allowWhenRegistrationClosed:e?.path?.includes("/admin/create-user")??!1}),{data:{...A,role:"user",banned:!1,banReason:null,banExpires:null}}),after:async()=>{await i3()}},update:{before:async A=>({data:{...A,role:"user",banned:!1,banReason:null,banExpires:null}})},delete:{before:async()=>{throw new g.E("BAD_REQUEST",{message:"Accounts must be deleted through the management API."})}}}};A.s(["f",0,i7],525796);var nA=A.i(160501),ne=A.i(375013),ne=ne,nt=A.i(747029),nt=nt,nr=nt,ni=nt,nn=nt,na=A.i(880272),ns=A.i(776578),no=A.i(656998);let nl=/\/(?:\.|%2e)(?:\.|%2e)?(?:\/|$|#|\?)/i,nc=new Set(["client_secret_post","client_secret_basic","client_secret_jwt"]);function nd(A){let e;try{e=new URL(A)}catch{return!1}return"https:"===e.protocol}let nu=/^application\/(?:[-\w.]+\+)?json\s*(?:;|$)/i,ng="Failed to fetch metadata document (network error or redirect blocked)",nh="cimd";function nI(A){return new na.E("BAD_REQUEST",{error:"invalid_client",error_description:A})}function np(){return nI("Metadata document exceeds 5KB size limit")}async function nC(A,e,t){let r,i=A.body?.getReader();if(!i){let t=await A.text();if(new TextEncoder().encode(t).byteLength>e)throw np();return t}let n=[],a=0,s=new Promise((A,e)=>{r=e}),o=()=>{r?.(Error("Metadata document body read aborted")),i.cancel().catch(()=>{})};t.aborted?o():t.addEventListener("abort",o,{once:!0});try{for(;;){let{done:A,value:t}=await Promise.race([i.read(),s]);if(A)break;if((a+=t.byteLength)>e)throw await i.cancel(),np();n.push(t)}}finally{t.removeEventListener("abort",o),i.releaseLock()}let l=new Uint8Array(a),c=0;for(let A of n)l.set(A,c),c+=A.byteLength;return new TextDecoder().decode(l)}async function nf(A,e,t,r){let i,n=function(A){let e;if(nl.test(A))return"client_id URL MUST NOT contain dot segments";if(A.includes("#"))return"client_id URL MUST NOT contain a fragment";try{e=new URL(A)}catch{return"client_id is not a valid URL"}if("https:"!==e.protocol)return"client_id URL must use HTTPS";let t=/^https:\/\//i.exec(A);if(!t||A.includes("\\"))return"client_id URL MUST use an explicit HTTPS authority form";let r=A.slice(t[0].length),i=r.search(/[/?#]/);return 0===i?"client_id URL MUST use an explicit HTTPS authority form":i<0||"/"!==r[i]?"client_id URL MUST contain an explicit path component":e.username||e.password?"client_id URL MUST NOT contain credentials":(0,eo.$)(e.hostname)?null:"client_id URL must not target a private or reserved address"}(e);if(n)throw nI(n);if(t.isMetadataDocumentUrlAllowed&&!await t.isMetadataDocumentUrlAllowed(e,A))throw nI("client_id URL is not permitted by the server's fetch policy");let a=new Headers({Accept:"application/json"});r?.etag&&a.set("If-None-Match",r.etag),r?.lastModified&&a.set("If-Modified-Since",r.lastModified);let s=new AbortController,o=!1,l=setTimeout(()=>{o=!0,s.abort()},5e3);try{var c;let n,l;try{i=await t.fetchClientMetadataResource(e,{headers:a,redirect:"error",signal:s.signal})}catch{throw nI(o?"Metadata document fetch timed out after 5000ms":ng)}if(i.redirected)throw nI("Metadata document fetch must not follow redirects");let d={cacheControl:(c=i.headers).get("cache-control")??void 0,vary:c.get("vary")??void 0,expires:c.get("expires")??void 0,date:c.get("date")??void 0,age:c.get("age")??void 0,etag:c.get("etag")??void 0,lastModified:c.get("last-modified")??void 0};if(304===i.status){if(!r?.etag&&!r?.lastModified)throw nI("Metadata document returned 304 without a conditional validator");return{status:"not-modified",cacheHeaders:d}}if(200!==i.status)throw nI(`Metadata document fetch returned HTTP ${i.status}`);let u=i.headers.get("content-type")??"";if(!nu.test(u))throw nI(`Metadata document must be JSON (got Content-Type "${u||"(none)"}")`);try{let A=i.headers.get("content-length");if(A){let e=Number.parseInt(A,10);if(Number.isFinite(e)&&e>5120)throw await i.body?.cancel(),np()}n=await nC(i,5120,s.signal)}catch(A){if(o)throw nI("Metadata document fetch timed out after 5000ms");if(A instanceof na.E)throw A;throw nI(ng)}try{l=JSON.parse(n)}catch{throw nI("Metadata document is not valid JSON")}let g=function(A,e,t={}){let r;if(!e||"object"!=typeof e)return{valid:!1,error:"metadata document is not a JSON object"};for(let A of Object.keys(e))if((0,nr.c)(A))return{valid:!1,error:`metadata document MUST NOT contain "${A}"`};let i=nt.b.strip().safeParse(e);if(!i.success){let A=i.error.issues[0];return{valid:!1,error:`${A?.path.join(".")||"metadata document"}: ${A?.message??"invalid client metadata"}`}}let n=i.data,a=[];if(n.client_id!==A)return{valid:!1,error:`client_id "${String(n.client_id)}" does not match the metadata document URL`};if("mcp-2026-07-28"===t.metadataProfile&&!n.client_name?.trim())return{valid:!1,error:"client_name must be a non-empty string"};for(let A of["backchannel_logout_uri","backchannel_logout_session_required"])if(void 0!==n[A])return{valid:!1,error:`metadata document MUST NOT contain "${A}"`};let s=new Set(["none","private_key_jwt"]);if("string"==typeof n.token_endpoint_auth_method){if(nc.has(n.token_endpoint_auth_method))return{valid:!1,error:`symmetric auth method "${n.token_endpoint_auth_method}" is prohibited for Client ID Metadata Document clients`};if(!s.has(n.token_endpoint_auth_method))return{valid:!1,error:'token_endpoint_auth_method must be "none" or "private_key_jwt" for Client ID Metadata Document clients'};if("private_key_jwt"===n.token_endpoint_auth_method&&!n.jwks&&!n.jwks_uri)return{valid:!1,error:"private_key_jwt requires either jwks or jwks_uri in the metadata document"}}if(n.jwks&&!(0,nn.l)(n.jwks).valid)return{valid:!1,error:"jwks must contain only structurally valid public keys"};if(n.jwks_uri)try{let A=new URL(n.jwks_uri);if(A.username||A.password)return{valid:!1,error:"jwks_uri must not contain credentials"};if(n.jwks_uri.includes("#"))return{valid:!1,error:"jwks_uri must not contain a fragment"}}catch{return{valid:!1,error:"jwks_uri must be a valid URL"}}if("mcp-2026-07-28"===t.metadataProfile&&!n.redirect_uris||n.redirect_uris&&!n.redirect_uris.every(A=>(function(A){try{let e=new URL(A);return"http:"===e.protocol||"https:"===e.protocol||(0,ns.Y)(e)}catch{return!1}})(A)))return{valid:!1,error:"redirect_uris must be a non-empty array of absolute HTTP(S) or private-use URIs"};for(let A of["client_uri","logo_uri","tos_uri","policy_uri"]){if(void 0!==n[A]&&"string"!=typeof n[A])return{valid:!1,error:`${A} must be a string`};if("string"==typeof n[A])try{let e=new URL(n[A]);if("https:"!==e.protocol&&"http:"!==e.protocol)return{valid:!1,error:`${A} must use HTTP(S)`};if(e.username||e.password)return{valid:!1,error:`${A} must not contain credentials`};if(!(0,eo.$)(e.hostname))return{valid:!1,error:`${A} must not point to a private or reserved address`}}catch{return{valid:!1,error:`${A} is not a valid URL`}}}let o=t.originBoundFields??["post_logout_redirect_uris","client_uri"];try{r=new URL(A).origin}catch{return{valid:!1,error:"client_id is not a valid URL"}}for(let A of o){let e,t=n[A];if(void 0!==t){if("string"==typeof t)e=[t];else{if(!Array.isArray(t)||!t.every(A=>"string"==typeof A))return{valid:!1,error:`${A} must be a string or an array of strings`};e=t}for(let t of e){let e;try{e=new URL(t)}catch{return{valid:!1,error:`${A} contains an invalid URL: "${t}"`}}let i="redirect_uris"===A||"post_logout_redirect_uris"===A,n=i&&(0,ns.Y)(e);if("https:"!==e.protocol&&"http:"!==e.protocol&&!n)return{valid:!1,error:`all values for ${A} must use HTTP(S) or a private-use scheme`};if(n&&("redirect_uris"===A||(0,ns.a)(e)))continue;let a=i&&("http:"===e.protocol||"https:"===e.protocol)&&(0,eo.g)(e.hostname);if(e.origin!==r&&!a)return{valid:!1,error:`${A} value "${t}" must have the same origin as client_id (${r})`}}}}return a.push(...function(A){let e=[];try{let t=new URL(A);"/"===t.pathname&&e.push("client_id URL path / is NOT RECOMMENDED (§3)"),t.search&&e.push("client_id URL SHOULD NOT contain a query string (§3)")}catch{}return e}(A)),{valid:!0,metadata:{...n,token_endpoint_auth_method:n.token_endpoint_auth_method??"none"},...a.length>0?{warnings:a}:{}}}(e,l,{originBoundFields:t.originBoundFields,metadataProfile:t.metadataProfile});if(!g.valid)throw nI(g.error);for(let e of g.warnings??[])A.context.logger.warn(`cimd metadata document warning: ${e}`);return{status:"modified",metadata:g.metadata,cacheHeaders:d}}finally{clearTimeout(l)}}async function nm(A,e,t,r,i,n){let a=n?{...n}:void 0,s=await (0,ni.a)(A,i,{clientId:e,clientDiscoveryId:nh,metadata:{...t,client_id:t.client_id,redirect_uris:t.redirect_uris??[]},existingClient:n});if(s.created)try{await r.onClientCreated?.({client:s.client,clientMetadataDocument:t,context:A})}catch(e){A.context.logger.error("cimd onClientCreated notification failed",e)}else try{a&&await r.onClientRefreshed?.({client:s.client,previousClient:a,clientMetadataDocument:t,context:A})}catch(e){A.context.logger.error("cimd onClientRefreshed notification failed",e)}return s.client}function nE(A){return new na.E("TOO_MANY_REQUESTS",{error:"temporarily_unavailable",error_description:A})}function nw(A,e){if(!Number.isInteger(A)||A<1)throw new g.p(`cimd metadataFetchPolicy.${e} must be a positive integer`);return A}function ny(A,e){let t=e-6e4,r=0;for(;r<A.length&&A[r]<=t;)r+=1;r>0&&A.splice(0,r)}function nQ(A){if("string"!=typeof A||!/^\d+$/.test(A))return null;let e=Number(A);return Number.isSafeInteger(e)?e:null}var nB=A.i(300794),nD=A.i(743698),nk=A.i(761095),nS=A.i(81111);let nb=new Set([204,205,304]),nM=async(A,e)=>{let t=new Request(A,e),r=new URL(t.url);if("https:"!==r.protocol)throw TypeError("CIMD Node transport requires an HTTPS URL");if("GET"!==t.method&&"HEAD"!==t.method)throw TypeError("CIMD Node transport supports only GET and HEAD");let i=await (0,nB.lookup)(r.hostname,{all:!0,verbatim:!0});if(0===i.length)throw TypeError("metadata hostname returned no DNS addresses");for(let A of i)if(!(0,eo.$)(A.address))throw TypeError("metadata hostname must resolve only to public-routable addresses");let n=i[0],a=Object.fromEntries(t.headers.entries());a.host=r.host;let s=e?.signal??(A instanceof Request?A.signal:t.signal);return new Promise((A,e)=>{let i=(0,nD.request)(r,{agent:!1,headers:a,method:t.method,servername:0===(0,nk.isIP)(r.hostname.replace(/^\[|\]$/g,""))?r.hostname:void 0,signal:s,lookup:(A,e,t)=>{e.all?t(null,[n]):t(null,n.address,n.family)}},r=>{let i=r.statusCode??500,n="HEAD"===t.method||nb.has(i)?null:nS.Readable.toWeb(r);try{A(new Response(n,{headers:function(A){let e=new Headers;for(let[t,r]of Object.entries(A))if(Array.isArray(r))for(let A of r)e.append(t,A);else void 0!==r&&e.append(t,r);return e}(r.headers),status:i,statusText:r.statusMessage}))}catch(A){r.destroy(),e(A)}});i.once("error",e),i.end()})};var nO=A.i(480416),nv=nt,nR=nt,nH=nt;let nN="/.well-known/oauth-protected-resource",nT=new Set(["openid","profile","email","phone","address","offline_access"]),nL=A=>"string"==typeof A?A:A.identifier;var nU=A.i(394110),n_=A.i(656057),nP=A.i(36616),nG=A.i(969068);function nx(A){let e=A.context.options.baseURL;return"string"==typeof e?e||"better-auth:session-cache":A.context.baseURL||"better-auth:session-cache"}async function nJ(A,e,t){let r=(0,tX.f)(e).kid;if(!r)return A.context.logger.debug("Cookie-cache JWT missing kid in header"),null;let i=await (0,nU.i)(A.context.adapter,t).getAllKeys(A);if(!i?.length)return A.context.logger.debug("No JWKS keys available for cookie-cache JWT"),null;let n=i.find(A=>A.id===r);if(!n)return A.context.logger.debug(`No JWKS key found for cookie-cache JWT kid: ${r}`),null;let a=n.alg??(0,nU.V)(t);return{alg:a,publicKey:await (0,tY.g)(JSON.parse(n.publicKey),a)}}async function nj(A,e,t,r){let i=await (0,n_.L)(A,r);if(!i)throw new g.p("`jwt({ sessionCookieCache: true })` requires locally managed JWT plugin keys and does not support `jwt.sign`.");return await new nG.f({...e,sid:e.session.token}).setProtectedHeader({alg:i.alg,kid:i.kid,typ:nP.Y}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).setIssuer(nx(A)).setAudience(nP.H).setSubject(e.user.id).sign(i.privateKey)}async function nY(A,e,t){try{if("better-auth.session-cache+jwt"!==(0,tX.f)(e).typ)return null;let r=await nJ(A,e,t);if(!r)return null;let{payload:i}=await (0,e6.f)(e,r.publicKey,{...(0,nP.V)({issuer:nx(A)}),algorithms:[r.alg]}),n=(0,nP.R)(i);if(!n)return null;return{payload:n,expiresAt:n.exp?1e3*n.exp:Date.now()}}catch(e){return A.context.logger.debug("Cookie-cache JWT verification failed",e),null}}let nF={jwks:{fields:{publicKey:{type:"string",required:!0},privateKey:{type:"string",required:!0},createdAt:{type:"date",required:!0},expiresAt:{type:"date",required:!1},alg:{type:"string",required:!1},crv:{type:"string",required:!1}}}};async function nz(A,e){let t=(0,eA.g)();try{let r=A.split(".");if(3!==r.length)return null;let i=new TextDecoder().decode(d.t.decode(r[0])),n=JSON.parse(i).kid;if(!n)return t.context.logger.debug("JWT missing kid in header"),null;let a=await (0,nU.i)(t.context.adapter,e).getAllKeys(t);if(!a||0===a.length)return t.context.logger.debug("No JWKS keys available"),null;let s=a.find(A=>A.id===n);if(!s)return t.context.logger.debug(`No JWKS key found for kid: ${n}`),null;let o=JSON.parse(s.publicKey),l=s.alg??(0,nU.V)(e),c=await (0,tY.g)(o,l),u="string"==typeof t.context.options.baseURL?t.context.options.baseURL:void 0,g=e?.jwt?.issuer??u,h=e?.jwt?.audience??u;g&&h||t.context.logger.warn("[better-auth] The JWT plugin is verifying a JWT without checking its issuer or audience because no base URL was resolved for this call. Set `baseURL`, or `jwt.issuer` and `jwt.audience` in the JWT plugin options.");let{payload:I}=await (0,e6.f)(A,c,{issuer:g,audience:h,algorithms:[l]});if(!I.sub||!I.aud)return null;return I}catch(A){return t.context.logger.debug("JWT verification failed",A),null}}let nq=y.object({payload:y.record(y.string(),y.any()),overrideOptions:y.record(y.string(),y.any()).optional()}),nV=y.object({token:y.string(),issuer:y.string().optional()});var nK=A.i(358307);function nW(){throw new g.E("BAD_REQUEST",{error:"invalid_grant",error_description:"The MCP authorization is inactive. Authorize this application again."})}function n$(A,e){return async t=>{let r;try{r=JSON.parse(t.value)}catch{return}if(r?.type!=="authorization_code")return;let i=r.resource??r.query?.resource;(Array.isArray(i)?i.includes(e.resource):i===e.resource)||nW(),("string"!=typeof r.userId||"string"!=typeof r.query?.client_id)&&nW();let n=await A.oauthClient.findUnique({where:{clientId:r.query.client_id}}),a=await A.mcpAuthorization.create({data:{id:(0,i5.randomUUID)(),authorizationCodeId:t.identifier,userId:r.userId,clientId:r.query.client_id,clientName:n?.name??r.query.client_id,scopes:r.query.scope??""}});return{data:{...t,value:JSON.stringify({...r,referenceId:a.id})}}}}function nZ(A,e){var t;let r,i,n=[...nK.n,"offline_access"];return[(A=>{if(A?.jwt?.sign&&!A.jwks?.remoteUrl)throw new g.p("options.jwks.remoteUrl must be set when using options.jwt.sign");if(A?.jwks?.remoteUrl&&!A.jwks?.keyPairConfig?.alg)throw new g.p("options.jwks.keyPairConfig.alg must be specified when options.jwks.remoteUrl is used for OpenID metadata");let e=A?.jwks?.jwksPath??"/jwks";if("string"!=typeof e||0===e.length||!e.startsWith("/")||e.includes(".."))throw new g.p("options.jwks.jwksPath must be a non-empty string starting with '/' and not contain '..'");return{id:"jwt",version:is.f,options:A,init(e){if(!A?.sessionCookieCache)return;if(e.options.session?.cookieCache?.strategy!=="jwt")throw new g.p('`jwt({ sessionCookieCache: true })` requires `session.cookieCache.strategy = "jwt"`.');if(A.jwt?.sign)throw new g.p("`jwt({ sessionCookieCache: true })` requires locally managed JWT plugin keys and does not support `jwt.sign`.");let t=A.jwks?.gracePeriod,r=e.options.session.cookieCache.maxAge||300;return void 0!==t&&r>t&&e.logger.warn(`[better-auth] \`session.cookieCache.maxAge\` (${r}s) exceeds the JWT plugin JWKS grace period (${t}s). Rotated keys may stop verifying cookie-cache JWTs before the cookie expires.`),{context:{sessionConfig:{...e.sessionConfig,cookieCacheSigner:{sign:(e,t,r)=>nj(e,t,r,A),verify:(e,t)=>nY(e,t,A)}}}}},endpoints:{getJwks:(0,l.g)(e,{method:"GET",metadata:{openapi:{operationId:"getJSONWebKeySet",description:"Get the JSON Web Key Set",responses:{200:{description:"JSON Web Key Set retrieved successfully",content:{"application/json":{schema:{type:"object",properties:{keys:{type:"array",description:"Array of public JSON Web Keys",items:{type:"object",properties:{kid:{type:"string",description:"Key ID uniquely identifying the key, corresponds to the 'id' from the stored Jwk"},kty:{type:"string",description:"Key type (e.g., 'RSA', 'EC', 'OKP')"},alg:{type:"string",description:"Algorithm intended for use with the key (e.g., 'EdDSA', 'RS256')"},use:{type:"string",description:"Intended use of the public key (e.g., 'sig' for signature)",enum:["sig"],nullable:!0},n:{type:"string",description:"Modulus for RSA keys (base64url-encoded)",nullable:!0},e:{type:"string",description:"Exponent for RSA keys (base64url-encoded)",nullable:!0},crv:{type:"string",description:"Curve name for elliptic curve keys (e.g., 'Ed25519', 'P-256')",nullable:!0},x:{type:"string",description:"X coordinate for elliptic curve keys (base64url-encoded)",nullable:!0},y:{type:"string",description:"Y coordinate for elliptic curve keys (base64url-encoded)",nullable:!0}},required:["kid","kty","alg"]}}},required:["keys"]}}}}}}}},async e=>{if(A?.jwks?.remoteUrl)throw new g.E("NOT_FOUND");let t=(0,nU.i)(e.context.adapter,A),r=await t.getAllKeys(e);if(r&&r?.length!==0||(await (0,no.K)(e,A),r=await t.getAllKeys(e)),!r?.length)throw new g.p("No key sets found. Make sure you have a key in your database.");let i=Date.now(),n=(A?.jwks?.gracePeriod??2592e3)*1e3,a=r.filter(A=>!A.expiresAt||A.expiresAt.getTime()+n>i),s=A?.jwks?.keyPairConfig,o=s&&"crv"in s?s.crv:void 0;return e.json({keys:a.map(e=>({alg:e.alg??(0,nU.V)(A),crv:e.crv??o,...JSON.parse(e.publicKey),kid:e.id}))})}),getToken:(0,l.g)("/token",{method:"GET",requireHeaders:!0,use:[h.Z],metadata:{openapi:{operationId:"getJSONWebToken",description:"Get a JWT token",responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{token:{type:"string"}}}}}}}}}},async e=>{let t=await (0,n_.d)(e,A);return e.json({token:t})}),signJWT:l.g.serverOnly({method:"POST",metadata:{$Infer:{body:{}}},body:nq},async e=>{let t=await (0,n_.X)(e,{options:{...A,...e.body.overrideOptions},payload:e.body.payload});return e.json({token:t})}),verifyJWT:l.g.serverOnly({method:"POST",metadata:{$Infer:{body:{},response:{}}},body:nV},async e=>{let t=e.body.issuer?{...A,jwt:{...A?.jwt,issuer:e.body.issuer}}:A,r=await nz(e.body.token,t);return e.json({payload:r})})},hooks:{after:[{matcher:A=>"/get-session"===A.path,handler:(0,l.a)(async e=>{if(A?.disableSettingJwtHeader)return;let t=e.context.session||e.context.newSession;if(t&&t.session){let t=await (0,n_.d)(e,A),r=new Set((e.context.responseHeaders?.get("access-control-expose-headers")||"").split(",").map(A=>A.trim()).filter(Boolean));r.add("set-auth-jwt"),e.setHeader("set-auth-jwt",t),e.setHeader("Access-Control-Expose-Headers",Array.from(r).join(", "))}})}]},schema:(0,m.C)(nF,A?.schema)}})({jwt:{issuer:e.issuer,audience:e.resource}}),(A=>{var e;let t,r,{resource:i,refreshTokenReuseInterval:n=30,...a}=A,s=function(A){var e;let t,r,i;if("string"!=typeof A)throw TypeError("MCP resource must be a single URL string");try{t=new URL(A)}catch{throw TypeError("MCP resource must be an absolute URL")}if(t.username||t.password)throw TypeError("MCP resource URL must not contain credentials");if(A.includes("#"))throw TypeError("MCP resource URL must not contain a fragment");if(A.includes("?"))throw TypeError("MCP resource URL must not contain a query; to protect a query-carrying resource, verify tokens with verifyAccessTokenRequest and build challenges with createResourceServerChallenge");if("https:"!==t.protocol&&!("http:"===t.protocol&&(i=4===(r=(e=t.hostname).split(".")).length&&"127"===r[0]&&r.every(A=>/^\d+$/.test(A)&&255>=Number(A)),"localhost"===e||"[::1]"===e||i)))throw TypeError("MCP resource URL must use HTTPS, except for localhost or loopback IP development URLs");return A}(i),o=(0,nH.i)({refreshTokenReuseInterval:n,...a,resources:(e=a.resources,(t=e??[]).some(A=>nL(A)===s)?t:[...t,s]),clientRegistrationDefaultResources:(r=a.clientRegistrationDefaultResources,r?.includes(s)?r:[...r??[],s])}),l=o.onRequest;return{...o,onRequest:async(A,e)=>{var t;let r,i,n,o,c=await l?.(A,e);if(c)return c;let d=new URL(A.url).pathname,u=e.options.advanced?.skipTrailingSlashes?d.replace(/\/+$/,"")||"/":d,g="";try{g=new URL(s).pathname.replace(/\/$/,"")}catch{g=""}if(!(new Set([nN,`${nN}${g}`])).has(u))return;if("GET"!==A.method&&"HEAD"!==A.method)return{response:new Response(null,{status:405,headers:{Allow:"GET, HEAD"}})};let h=(0,nR.d)((t={context:e},r=(a.advertisedMetadata?.scopes_supported??a.scopes??[]).filter(A=>!nT.has(A)),n="object"==typeof(i=a.resources?.find(A=>nL(A)===s))&&!0===i.dpopBoundAccessTokensRequired,o={resource:s,authorization_servers:[(0,nv.t)(t,a)],bearer_methods_supported:["header"],dpop_signing_alg_values_supported:[...a.dpop?.signingAlgorithms??nO.G]},n&&(o.dpop_bound_access_tokens_required=!0),r.length&&(o.scopes_supported=[...r]),o));return"HEAD"===A.method?{response:new Response(null,{status:h.status,headers:h.headers})}:{response:h}}}})({loginPage:"/mcp/sign-in",consentPage:"/mcp/consent",resource:e.resource,scopes:n,resources:[{identifier:e.resource,allowedScopes:n,accessTokenTtl:300,refreshTokenTtl:2592e3}],grantTypes:["authorization_code","refresh_token"],accessTokenExpiresIn:300,refreshTokenExpiresIn:2592e3,refreshTokenReuseInterval:0,clientRegistrationDefaultScopes:["mcp:read"],clientRegistrationAllowedScopes:n,allowDynamicClientRegistration:e.dcrEnabled,allowUnauthenticatedClientRegistration:e.dcrEnabled,clientRegistrationDefaultApplicationType:"infer",extensions:[{claims:{accessToken:async({user:t,client:r,referenceId:i,resources:n,scopes:a})=>{t&&i&&n?.includes(e.resource)||nW();let s=await A.mcpAuthorization.findFirst({where:{id:i,userId:t.id,clientId:r.clientId,revokedAt:null,user:{is:{id:t.id}}}});return(!s||a.some(A=>!s.scopes.split(" ").includes(A)))&&nW(),{aide_mcp_authorization_id:s.id}}}}]}),(r=function(A){let e,t=A.metadataRevalidationInterval??"60m",r=A.maxCacheEntries??1e3;if(!Number.isInteger(r)||r<1)throw new g.p("cimd maxCacheEntries must be a positive integer");let i=(e=A.metadataFetchPolicy,{minimumFetchIntervalMs:function(A,e){if("number"==typeof A){if(!Number.isFinite(A)||A<0)throw new g.p(`cimd metadataFetchPolicy.${e} must be a non-negative number of seconds or duration string`);return 1e3*A}try{let e=Math.floor(Date.now()/1e3),t=((0,no.x)(A,e)-e)*1e3;if(!Number.isFinite(t)||t<0)throw Error("negative duration");return t}catch{throw new g.p(`cimd metadataFetchPolicy.${e} must be a non-negative number of seconds or duration string`)}}(e?.minimumFetchInterval??1,"minimumFetchInterval"),maximumConcurrentFetches:nw(e?.maximumConcurrentFetches??16,"maximumConcurrentFetches"),maximumConcurrentFetchesPerOrigin:nw(e?.maximumConcurrentFetchesPerOrigin??4,"maximumConcurrentFetchesPerOrigin"),maximumFetchesPerMinute:nw(e?.maximumFetchesPerMinute??120,"maximumFetchesPerMinute"),maximumFetchesPerOriginPerMinute:nw(e?.maximumFetchesPerOriginPerMinute??30,"maximumFetchesPerOriginPerMinute")}),n=new Map,a=new Map,s=new Map,o=new Map,l=[],c=0;return async(e,d,u)=>{if(!nd(d))return null;let h=e.context.getPlugin("oauth-provider");if(!h)throw new g.p("cimd discovery invoked without the oauth-provider plugin installed");let I=h.options,p=(A=>{let e=n.get(A);if(e)return n.delete(A),n.set(A,e),e})(d),C=Date.now();if(p&&p.expiresAt>C)return u||nm(e,d,p.metadata,A,I);let f=a.get(d);if(void 0!==f)return f;let m=(A=>{let e=Date.now(),t=s.get(A);if(i.minimumFetchIntervalMs>0&&void 0!==t&&e-t<i.minimumFetchIntervalMs)throw nE("metadata document fetch is within the per-client minimum interval");if(!s.has(A))for(;s.size>=r;){let A=!1;for(let[t,r]of s)if(!a.has(t)&&(!(i.minimumFetchIntervalMs>0)||!(e-r<i.minimumFetchIntervalMs))){s.delete(t),A=!0;break}if(!A)throw nE("metadata fetch client state is at capacity")}let n=((A,e)=>{let t=o.get(A);if(t)return ny(t.fetchStartTimesMs,e),o.delete(A),o.set(A,t),t;for(;o.size>=r;){let A=!1;for(let[t,r]of o)if(ny(r.fetchStartTimesMs,e),!(r.activeFetchCount>0)&&!(r.fetchStartTimesMs.length>0)){o.delete(t),A=!0;break}if(!A)throw nE("metadata fetch origin state is at capacity")}let i={activeFetchCount:0,fetchStartTimesMs:[]};return o.set(A,i),i})(new URL(A).origin,e);if(ny(l,e),c>=i.maximumConcurrentFetches)throw nE("global metadata fetch concurrency limit exceeded");if(n.activeFetchCount>=i.maximumConcurrentFetchesPerOrigin)throw nE("metadata fetch concurrency limit exceeded for client origin");if(l.length>=i.maximumFetchesPerMinute)throw nE("global metadata fetch rate limit exceeded");if(n.fetchStartTimesMs.length>=i.maximumFetchesPerOriginPerMinute)throw nE("metadata fetch rate limit exceeded for client origin");s.delete(A),s.set(A,e),l.push(e),n.fetchStartTimesMs.push(e),c+=1,n.activeFetchCount+=1;let d=!1;return()=>{d||(d=!0,c-=1,n.activeFetchCount-=1)}})(d),E=(async()=>{let i,a=await nf(e,d,A,p?{etag:p.etag,lastModified:p.lastModified}:void 0);if("not-modified"===a.status&&!p)throw g="Metadata document returned 304 without a validated cached document",new na.E("BAD_REQUEST",{error:"invalid_client",error_description:g});let o="modified"===a.status?a.metadata:p.metadata,l=await nm(e,d,o,A,I,u??void 0),c=(i=function(A,e,t){let{directives:r,duplicates:i}=function(A){let e=new Map,t=new Set;for(let r of A?.split(",")??[]){let[A,...i]=r.trim().split("="),n=A?.toLowerCase();if(!n)continue;e.has(n)&&t.add(n);let a=i.join("=").trim();e.set(n,!a||a.replace(/^"|"$/g,""))}return{directives:e,duplicates:t}}(A.cacheControl),n=A.vary?.split(",").some(A=>"*"===A.trim());if(r.has("no-store")||r.has("private")||n)return{cacheable:!1,expiresAt:t};let a=function(A,e){if("number"==typeof A)return Math.max(0,1e3*A);let t=Math.floor(e/1e3);return Math.max(0,((0,no.x)(A,t)-t)*1e3)}(e,t);if(r.has("no-cache"))return{cacheable:!0,expiresAt:t};let s=nQ(A.age)??0,o=A.date?Date.parse(A.date):t,l=Math.max(Number.isFinite(o)?Math.max(0,t-o):0,1e3*s),c=null,d=r.has("s-maxage"),u=nQ(r.get("s-maxage")),g=r.has("max-age"),h=nQ(r.get("max-age")),I=d?null===u||i.has("s-maxage"):g&&(null===h||i.has("max-age")),p=d?u:h;if(I)c=0;else if(null!==p)c=Math.max(0,1e3*p-l);else if(A.expires){let e=Date.parse(A.expires);Number.isFinite(e)&&(c=Math.max(0,e-(Number.isFinite(o)?o:t)-l))}return{cacheable:!0,expiresAt:t+Math.min(a,c??a)}}(f="modified"===a.status?a.cacheHeaders:(h=p.responseCacheHeaders,{cacheControl:(C=a.cacheHeaders).cacheControl??h.cacheControl,vary:C.vary??h.vary,expires:C.expires??h.expires,date:C.date??h.date,age:C.age??h.age,etag:C.etag??h.etag,lastModified:C.lastModified??h.lastModified}),t,Date.now())).cacheable?{metadata:o,expiresAt:i.expiresAt,etag:f.etag,lastModified:f.lastModified,responseCacheHeaders:f}:null;if(c){var g,h,C,f;for(n.delete(d);n.size>=r;){let A=n.keys().next().value;if("string"!=typeof A)break;n.delete(A)}n.set(d,c)}else n.delete(d);return s.delete(d),l})();a.set(d,E);try{return await E}catch(A){throw s.delete(d),s.set(d,Date.now()),A}finally{a.get(d)===E&&a.delete(d),m()}}}(t={fetchClientMetadataResource:nM,metadataProfile:"mcp-2026-07-28"}),i={id:nh,matches:nd,resolve:r,fetchClientMetadataResource:t.fetchClientMetadataResource,discoveryMetadata:{client_id_metadata_document_supported:!0}},{id:"cimd",version:"1.7.16",init(A){(0,ne.L)(A,{clientDiscovery:i})}})]}A.s(["y",0,nZ,"K",0,n$],9416);let nX={disableClientRequest:!0,expiresIn:1,storeToken:"hashed"};iJ({...nX,disableSetSessionCookie:!0}).endpoints.verifyOneTimeToken;let n0={user:["create","list","set-password","set-email","get","update"],session:["list","revoke","delete"]},n1=(0,D.y)(n0),n4=n1.newRole(n0),n8=null;function n5(){return n8||(n8=(0,iY.U)().then(A=>(function(A,e=iV(),t=(0,nA.getMcpOAuthConfig)()){var r;let i,n,a,s,d,u=e.provider,I=(0,ij.J)(e.origins),p=u?.providerId.toLowerCase()==="github"?u.userInfoUrl:void 0,Q=iW(e.mode)&&u?(A=>{let e=new Set,t=new Set;for(let r of A.config){let A=r.providerId;e.has(A)&&t.add(A),e.add(A)}t.size>0&&console.warn(`Duplicate provider IDs found: ${Array.from(t).join(", ")}`);let r=async(A,e,t)=>{let r=[];for(let i of A){let A,n,a=i.authorizationUrl,s=i.tokenUrl,o=i.userInfoUrl,l=i.endSessionEndpoint,c=!1;if(i.discoveryUrl){let r=await i_(i.discoveryUrl,i.discoveryHeaders,t).catch(A=>(e.logger.error(`Discovery fetch failed for "${i.providerId}": ${A}`),null));if(r){a??=r.authorization_endpoint,s??=r.token_endpoint,o??=r.userinfo_endpoint,l??=r.end_session_endpoint,A=r.issuer;let t=r.id_token_signing_alg_values_supported;if(c=Array.isArray(t)&&t.length>0,r.jwks_uri&&r.issuer){let A;try{A=new URL(r.jwks_uri,i.discoveryUrl)}catch{e.logger.error(`Provider "${i.providerId}": invalid jwks_uri "${r.jwks_uri}" in discovery document. Provider skipped.`);continue}n={jwks:(0,tW.R)(A),issuer:r.issuer,audience:i.clientId,algorithms:c?t:void 0}}}if(!a||!s&&!i.getToken){e.logger.error(`Provider "${i.providerId}": discovery left no usable authorization endpoint or token exchange. Provider skipped.`);continue}}if(i.requireIdTokenVerification&&!n){if(i.discoveryUrl){e.logger.error(`Provider "${i.providerId}": requires verified ID tokens, but discovery did not provide a usable issuer and jwks_uri. Provider skipped.`);continue}throw Error(`Provider "${i.providerId}": requires verified ID tokens, but discovery did not provide a usable issuer and jwks_uri.`)}let d=i.tokenEndpointAuth;if(i.clientSecret&&(d?.method==="private_key_jwt"||d?.method==="none"))throw Error(`Provider "${i.providerId}": tokenEndpointAuth.method "${d?.method}" cannot be combined with clientSecret`);if(!i.clientSecret&&(d?.method==="client_secret_basic"||d?.method==="client_secret_post"))throw Error(`Provider "${i.providerId}": tokenEndpointAuth.method "${d?.method}" requires clientSecret`);if(!i.clientSecret&&!d&&"basic"===i.authentication)throw Error(`Provider "${i.providerId}": authentication "basic" requires clientSecret`);let u=async(A,e)=>{let t=i.getUserInfo?await i.getUserInfo(A):await iP(A,o,e);if(!t)return null;let r=!i.getUserInfo||null!=t.sub;if(e?.sub!==void 0&&r&&String(t.sub)!==e.sub)return null;let n=i.mapProfileToUser?await i.mapProfileToUser(t):{},a={email:t.email,emailVerified:e1(t.emailVerified),image:t.image,name:t.name,...n};return{user:{...a,image:a.image??void 0},data:t}},h=i.accountSubject,I={id:i.providerId,name:i.name??i.providerId,issuer:A,accountSubject:({tokens:A,profile:e})=>h?h({tokens:A,profile:e}):c?n&&A.idToken?iU(A.idToken)?.sub??"":e.sub??"":e.id??"",idToken:n,requiresIdTokenNonce:void 0!==n&&!0!==i.disableIdTokenNonceBinding,allowIdpInitiated:i.allowIdpInitiated,async createEndSessionURL(A){let t;if(i.disableProviderLogout||!l)return null;try{t=new URL(l)}catch{return null}A.idToken&&t.searchParams.set("id_token_hint",A.idToken);let r=A.postLogoutRedirectURI??i.postLogoutRedirectURI,n=r?new URL(r,e.baseURL).toString():void 0;return n?(t.searchParams.set("post_logout_redirect_uri",n),t.searchParams.set("client_id",i.clientId),A.state&&t.searchParams.set("state",A.state)):A.idToken||t.searchParams.set("client_id",i.clientId),t},createAuthorizationURL(A){if(!a)throw g.E.from("BAD_REQUEST",iL.INVALID_OAUTH_CONFIGURATION);return tw({id:i.providerId,options:{clientId:i.clientId,clientSecret:i.clientSecret,redirectURI:i.redirectURI},authorizationEndpoint:a,state:A.state,codeVerifier:i.pkce??!0?A.codeVerifier:void 0,scopes:(()=>{let e=[...A.scopes??[],...i.scopes??[]];return c&&!e.includes("openid")&&e.unshift("openid"),e})(),redirectURI:A.redirectURI,prompt:i.prompt,accessType:i.accessType,responseType:i.responseType,responseMode:i.responseMode,nonce:A.idTokenNonce,additionalParams:{...i.authorizationUrlParams??{},...A.additionalParams??{}},loginHint:A.loginHint})},async validateAuthorizationCode(A){if(i.getToken)return(0,tr.O)(await i.getToken(A),i.accessTokenExpiresIn);if(!s)throw g.E.from("BAD_REQUEST",iL.TOKEN_URL_NOT_FOUND);let e=await tJ({headers:i.authorizationHeaders,code:A.code,codeVerifier:i.pkce??!0?A.codeVerifier:void 0,redirectURI:A.redirectURI,options:{clientId:i.clientId,clientSecret:i.clientSecret,redirectURI:i.redirectURI},tokenEndpoint:s,authentication:i.authentication,tokenEndpointAuth:d,additionalParams:i.tokenUrlParams});return(0,tr.O)(e,i.accessTokenExpiresIn)},async getUserInfoFromIdToken(A){let e=I.idToken?iU(A):void 0;return null===e?null:u({idToken:A},e)},async getUserInfo(A){let{expectedIdTokenNonce:t,...r}=A;if(!r.idToken||!I.idToken)return u(r);let n=await tb(I,r.idToken,t)?iU(r.idToken):null;return n?u(r,n):(e.logger.error(`Provider "${i.providerId}": id_token failed verification against the discovery JWKS or expected nonce`),null)},async refreshAccessToken(A,e){if(!s)throw g.E.from("BAD_REQUEST",iL.TOKEN_URL_NOT_FOUND);let t="function"==typeof i.refreshTokenParams?await i.refreshTokenParams(e):i.refreshTokenParams,r=await tG({refreshToken:A,options:{clientId:i.clientId,clientSecret:i.clientSecret},authentication:i.authentication,tokenEndpointAuth:d,tokenEndpoint:s,extraParams:t});return(0,tr.O)(r,i.accessTokenExpiresIn)},disableImplicitSignUp:i.disableImplicitSignUp,disableSignUp:i.disableSignUp,options:{disableSignUp:i.disableSignUp,overrideUserInfoOnSignIn:i.overrideUserInfo,requireEmailVerification:i.requireEmailVerification}};r.push(I)}return r},i=A=>{let e=A.body?.provider??A.body?.providerId??A.query?.provider??A.params?.id;return"string"==typeof e?e:void 0};return{id:"generic-oauth",version:is.f,init:async e=>{let t=await r(A.config,e),i=new Set(t.map(A=>A.id)),n=new Map(A.config.filter(A=>!i.has(A.providerId)).map(A=>[A.providerId,{config:A}])),a=new Set(e.socialProviders.map(A=>A.id));for(let A of t)a.has(A.id)&&e.logger.warn(`Generic OAuth provider "${A.id}" shadows a built-in social provider with the same ID`);return{context:{socialProviders:t.concat(e.socialProviders),genericOAuthPendingDiscovery:n}}},hooks:{before:[{matcher:A=>A.context.genericOAuthPendingDiscovery?.has(i(A)??"")===!0,handler:(0,l.a)(async A=>{await ((A,e)=>{let t=A.genericOAuthPendingDiscovery,i=t?.get(e);if(i)return i.attempt??=r([i.config],A,1e4).then(([r])=>{r&&(t?.delete(e),A.socialProviders.unshift(r))}).finally(()=>{i.attempt=void 0}),i.attempt})(A.context,i(A)??"")})}]},options:A,$ERROR_CODES:iL}})({config:[{providerId:u.providerId,clientId:u.clientId,clientSecret:u.clientSecret,scopes:u.scopes,discoveryUrl:u.discoveryUrl,authorizationUrl:u.authorizationUrl,tokenUrl:u.tokenUrl,userInfoUrl:u.userInfoUrl,getUserInfo:p?async A=>A.accessToken?i8(p,A.accessToken):null:void 0,pkce:!0,requireIdTokenVerification:u.requireIssuerValidation,disableImplicitSignUp:!1}]}):null;return((A,e)=>{let t=e(A).then(A=>{let e=A.options.advanced?.database?.validateSchema;A.checkSchema||!1===e||A.logger[!0===e?"warn":"debug"](`Schema validation is not available for adapter "${A.adapter.id}". Skipping schema validation. Database operations will proceed normally.`);let t=A.checkSchema?.();return t&&t.catch(e=>{A.logger.error(e instanceof Am._?e.message:"Could not validate the database schema. Check your database connection.")}),A}),{api:r}=rx(t,A),i=A.plugins?.reduce((A,e)=>e.$ERROR_CODES?{...A,...e.$ERROR_CODES}:A,{}),n=async e=>{let r,i=await t,n=i.options.basePath||"/api/auth";if((0,Aj._)(A.baseURL))r=await eu(i,e,ed(i.options));else{r=Object.create(Object.getPrototypeOf(i),Object.getOwnPropertyDescriptors(i));let A=i.options;if(!i.options.baseURL){let t=(0,Aj.X)(void 0,n,e,void 0,i.options.advanced?.trustedProxyHeaders);if(!t)throw new g.p("Could not get base URL from request. Please provide a valid base URL.");r.baseURL=t,r.options={...i.options,baseURL:(0,Aj.H)(t)||void 0},A=r.options}r.trustedOrigins=await ec(A,e),r.trustedProviders=await eh(A,e)}let{handler:a}=((A,e)=>{let t=(0,et.f)(e),{api:r,middlewares:i}=rx(A,e),n=new URL(A.baseURL).pathname;return(0,rG.f)(r,{routerContext:A,openapi:{disabled:!0},basePath:n,routerMiddleware:[{path:"/**",middleware:ek},...i],allowedMediaTypes:["application/json"],skipTrailingSlashes:e.advanced?.skipTrailingSlashes??!1,async onRequest(e){let r=A.options.disabledPaths||[],i=(0,ey.s)(e.url,n);if(r.includes(i))return new Response("Not Found",{status:404});let a=A.checkSchema?.();a&&await a;let s=e,o=await eT(s,A);if(o)return o;for(let e of A.options.plugins||[])if(e.onRequest){let r=await t(`onRequest ${e.id}`,{[ee.A]:"onRequest",[ee.s]:`plugin:${e.id}`},()=>e.onRequest(s,A));if(r&&"response"in r)return r.response;r&&"request"in r&&(s=r.request)}return s},async onResponse(e,r){for(let r of A.options.plugins||[])if(r.onResponse){let i=await t(`onResponse ${r.id}`,{[ee.A]:"onResponse",[ee.s]:`plugin:${r.id}`,[ee.h]:e.status},()=>r.onResponse(e,A));if(i)return i.response}return e},async onError(t){if((0,ew.f)(t)&&"FOUND"===t.status)return;if(e.onAPIError?.throw)throw t;if(e.onAPIError?.onError){try{await e.onAPIError.onError(t,A)}catch(e){A.logger.error("onAPIError.onError threw",e)}return}let r=e.logger?.level,i="error"===r||"warn"===r||"debug"===r?AQ.y:void 0;if(e.logger?.disabled!==!0){if(t&&"object"==typeof t&&"message"in t&&"string"==typeof t.message&&(t.message.includes("no column")||t.message.includes("column")||t.message.includes("relation")||t.message.includes("table")||t.message.includes("does not exist")))return void A.logger?.error(t.message);(0,ew.f)(t)?("INTERNAL_SERVER_ERROR"===t.status&&A.logger.error(t.status,t),i?.error(t.message)):A.logger?.error(t&&"object"==typeof t&&"name"in t?t.name:"",t)}}})})(r,A);return(0,A7.Q)(r.adapter,()=>a(e))};return{handler:n,fetch:n,api:r,options:A,$context:t,$ERROR_CODES:{...i,...eI.f}}})({appName:"AI Development Environment",baseURL:"object"==typeof I?{...I,protocol:"auto"}:I,disabledPaths:t?["/token"]:[],trustedOrigins:A=>{if(!A)return[];let t=(0,ij.v)(A,e.trustProxyHeaders);return t&&(0,ij.K)(e.origins,t)?[t]:[]},secret:e.secret,logger:{log:i0},hooks:{before:(0,l.a)(async A=>{let t=A.request?(0,ij.v)(A.request,e.trustProxyHeaders):null,r=A.headers?.get("cookie")??"",i=t?"https:"===new URL(t).protocol:!!/(?:^|;\s*)__Secure-better-auth\.session_token=/.test(r)||!/(?:^|;\s*)better-auth\.session_token=/.test(r)&&void 0,n={...A.context.options,advanced:{...A.context.options.advanced,useSecureCookies:i}};A.context.authCookies=(0,A4.e)(n),A.context.createAuthCookie=(0,A4.g)(n)})},advanced:{trustedProxyHeaders:e.trustProxyHeaders},database:(r={provider:"sqlite"},i=null,n=(A,e=!1)=>({getFieldName:t,getModelName:i,getFieldAttributes:n,getDefaultModelName:a,schema:s})=>{let o=(A,e,r)=>{if(!A&&!r)return;let i={};if(A)for(let r of A)i[t({model:e,field:r})]=!0;if(r){if(!A){let A=s[a(e)]?.fields||{};for(let r of(A.id={type:"string"},Object.keys(A)))i[t({model:e,field:r})]=!0}for(let[A,t]of Object.entries(r)){let r=l(e,t.modelKey??A,s);"one-to-one"===t.relation?i[r]=!0:i[r]={take:t.limit}}}return i},l=(A,e,t)=>{try{let n=a(A),s=a(e),o=i(e).toLowerCase(),l=Object.entries(t[s]?.fields||{}).filter(([A,e])=>e.references&&a(e.references.model)===n);if(l.length>0){let[A,e]=l[0];return e?.unique===!0||!0===r.usePlural?o:`${o}s`}if((l=Object.entries(t[n]?.fields||{}).filter(([A,e])=>e.references&&a(e.references.model)===s)).length>0)return o}catch{}return`${i(e).toLowerCase()}s`};function c(A){switch(A){case"starts_with":return"startsWith";case"ends_with":return"endsWith";case"ne":return"not";case"not_in":return"notIn";default:return A}}let d=({action:A,model:e,where:i})=>{if(!i||!i.length)return{};let a=A=>{let i=t({model:e,field:A.field}),a=(A.mode??"sensitive")==="insensitive"&&("string"==typeof A.value||Array.isArray(A.value)&&A.value.every(A=>"string"==typeof A)),s="postgresql"===r.provider||"mongodb"===r.provider,o=a&&s?"insensitive":void 0,l=o?{mode:o}:{};if("ne"===A.operator&&null===A.value)return n({model:e,field:A.field})?.required!==!0?{[i]:{not:null}}:{};if(("in"===A.operator||"not_in"===A.operator)&&Array.isArray(A.value)){let e=A.value.filter(A=>null!=A);if(0===e.length)if("in"===A.operator)return{AND:[{[i]:{equals:"__never__"}},{[i]:{not:"__never__"}}]};else return{};return{[i]:{[c(A.operator)]:e,...l}}}return"eq"!==A.operator&&A.operator?"ne"===A.operator?{[i]:{not:{equals:A.value},...l}}:{[i]:{[c(A.operator)]:A.value,...l}}:{[i]:{equals:A.value,...l}}};if("update"===A){let A=i.filter(A=>"AND"===A.connector||!A.connector),r=i.filter(A=>"OR"===A.connector),n=A.filter(A=>"eq"===A.operator||!A.operator),s=A.filter(A=>"eq"!==A.operator&&void 0!==A.operator).map(A=>a(A)),o=r.map(A=>a(A)),l={};for(let A of n)l[t({model:e,field:A.field})]=A.value;return s.length>0&&(l.AND=s),o.length>0&&(l.OR=o),l}if("delete"===A){let A=i.find(A=>"id"===A.field);if(A){let r=t({model:e,field:"id"}),n=i.filter(A=>"id"!==A.field);if(0===n.length)return{[r]:A.value};let s=n.filter(A=>"AND"===A.connector||!A.connector),o=n.filter(A=>"OR"===A.connector),l=s.map(A=>a(A)),c=o.map(A=>a(A)),d={[r]:A.value};return l.length>0&&(d.AND=l),c.length>0&&(d.OR=c),d}}if(1===i.length){let A=i[0];if(!A)return;return a(A)}let s=i.filter(A=>"AND"===A.connector||!A.connector),o=i.filter(A=>"OR"===A.connector),l=s.map(A=>a(A)),d=o.map(A=>a(A));return{...l.length?{AND:l}:{},...d.length?{OR:d}:{}}};return{async create({model:e,modelKey:t=e,data:r,select:i}){if(!A[e])throw new g.p(`Model ${e} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);return await A[e].create({data:r,select:o(i,t)})},async findOne({model:e,modelKey:t=e,where:r,select:i,join:n}){let a=d({model:t,where:r,action:"findOne"});if(!A[e])throw new g.p(`Model ${e} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let c=new Map;for(let[A,e]of Object.entries(n??{})){let r=l(t,e.modelKey??A,s);c.set(r,A)}let u=o(i,t,n),h=await A[e].findFirst({where:a,select:u});if(n&&h)for(let[A,e]of c.entries())A!==e&&A in h&&(h[e]=h[A],delete h[A]);return h},async findMany({model:e,modelKey:r=e,where:i,limit:n,select:a,offset:c,sortBy:u,join:h}){let I=d({model:r,where:i,action:"findMany"});if(!A[e])throw new g.p(`Model ${e} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let p=new Map;if(h)for(let[A,e]of Object.entries(h)){let t=l(r,e.modelKey??A,s);p.set(t,A)}let C=o(a,r,h),f=await A[e].findMany({where:I,take:n||100,skip:c||0,...u?.field?{orderBy:{[t({model:r,field:u.field})]:"desc"===u.direction?"desc":"asc"}}:{},select:C});if(h&&Array.isArray(f))for(let A of f)for(let[e,t]of p.entries())e!==t&&e in A&&(A[t]=A[e],delete A[e]);return f},async count({model:e,modelKey:t=e,where:r}){let i=d({model:t,where:r,action:"count"});if(!A[e])throw new g.p(`Model ${e} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);return await A[e].count({where:i})},async update({model:e,modelKey:t=e,where:i,update:a}){if(!A[e])throw new g.p(`Model ${e} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);if(!(i?.length&&i.some(A=>{if("OR"===A.connector||A.operator&&"eq"!==A.operator)return!1;if("insensitive"===A.mode){let e="postgresql"===r.provider||"mongodb"===r.provider,t="string"==typeof A.value||Array.isArray(A.value)&&A.value.every(A=>"string"==typeof A);if(e&&t)return!1}return"id"===A.field||n({model:t,field:A.field})?.unique===!0}))){let r=d({model:t,where:i,action:"updateMany"});return(await A[e].updateMany({where:r,data:a}))?.count?await A[e].findFirst({where:r}):null}let s=d({model:t,where:i,action:"update"});try{return await A[e].update({where:s,data:a})}catch(A){if(Aw(A))return null;throw A}},async updateMany({model:e,modelKey:t=e,where:r,update:i}){if(!A[e])throw new g.p(`Model ${e} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let n=d({model:t,where:r,action:"updateMany"}),a=await A[e].updateMany({where:n,data:i});return a?a.count:0},async delete({model:e,modelKey:t=e,where:r}){if(!A[e])throw new g.p(`Model ${e} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);if(!r?.some(A=>"id"===A.field)){let i=d({model:t,where:r,action:"deleteMany"});await A[e].deleteMany({where:i});return}let i=d({model:t,where:r,action:"delete"});try{await A[e].delete({where:i})}catch(A){if(Aw(A))return;throw A}},async deleteMany({model:e,modelKey:t=e,where:r}){let i=d({model:t,where:r,action:"deleteMany"}),n=await A[e].deleteMany({where:i});return n?n.count:0},async consumeOne({model:t,modelKey:r=t,where:i}){if(!A[t])throw new g.p(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);if(i?.some(A=>"id"===A.field)){let e=d({model:r,where:i,action:"delete"});try{return await A[t].delete({where:e})??null}catch(A){if(Aw(A))return null;throw A}}let n=d({model:r,where:i,action:"findOne"}),a=async A=>{let e=await A[t].findFirst({where:n});if(!e)return null;try{return(await A[t].deleteMany({where:d({model:r,where:[...i??[],{field:"id",value:e.id,operator:"eq",connector:"AND",mode:"sensitive"}],action:"deleteMany"})}))?.count>0?e:null}catch(A){if(Aw(A))return null;throw A}};return e||"function"!=typeof A.$transaction?a(A):A.$transaction(a)},async incrementOne({model:t,modelKey:r=t,where:i,increment:n,set:a}){if(!A[t])throw new g.p(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let s={...a??{}};for(let[A,e]of Object.entries(n))s[A]={increment:e};if(i?.some(A=>"id"===A.field)){let e=d({model:r,where:i,action:"update"});try{return await A[t].update({where:e,data:s})??null}catch(A){if(Aw(A))return null;throw A}}let o=d({model:r,where:i,action:"findOne"}),l=async A=>{let e=await A[t].findFirst({where:o});if(!e)return null;try{return await A[t].update({where:d({model:r,where:[...i,{field:"id",value:e.id,operator:"eq",connector:"AND",mode:"sensitive"}],action:"update"}),data:s})??null}catch(A){if(Aw(A))return null;throw A}};return e||"function"!=typeof A.$transaction?l(A):A.$transaction(l)},options:r}},a=null,a={config:{adapterId:"prisma",adapterName:"Prisma Adapter",usePlural:r.usePlural??!1,debugLogs:r.debugLogs??!1,supportsUUIDs:"postgresql"===r.provider,supportsArrays:"postgresql"===r.provider||"mongodb"===r.provider,transaction:!!r.transaction&&(e=>A.$transaction(A=>e((0,AC.f)({config:{...a.config,transaction:!1},adapter:n(A,!0)})(i))))},adapter:n(A)},s=(0,AC.f)(a),e=>{let t;i=e;let n=s(e),a="object"==typeof(t=A._runtimeDataModel)&&null!==t&&"models"in t?t:void 0;if(a){let A=(0,Af.t)(()=>{var A;let t;return A=r.usePlural,t=Object.fromEntries(Object.entries((0,Am.w)(e,{usePlural:A})).map(([A,e])=>[AE(A),e])),(0,Am.I)(t,Object.entries(a.models).map(([A,{fields:e}])=>({name:AE(A),columns:e.filter(A=>"object"!==A.kind).map(A=>({name:A.name,nullable:!0!==A.isRequired,hasDefault:!0===A.hasDefaultValue||!0===A.isUpdatedAt}))})))},"prisma");(0,Af.E)(n,A,{runtimeEnabled:(0,Af.S)(e)})}return n}),emailAndPassword:{enabled:iK(e.mode),requireEmailVerification:!1},account:{accountLinking:{enabled:!0,disableImplicitLinking:!0,allowDifferentEmails:!1}},databaseHooks:{...i7,...t?{verification:{create:{before:n$(A,t)}}}:{}},plugins:[function(){let A=(A=>{let e={...A||{},defaultRole:A?.defaultRole??"user",adminRoles:A?.adminRoles??["admin"],bannedUserMessage:A?.bannedUserMessage??"You have been banned from this application. Please contact support if you believe this is an error."};if(A?.adminRoles){let e=(Array.isArray(A.adminRoles)?A.adminRoles:[...A.adminRoles.split(",")]).filter(e=>!Object.keys(A?.roles||ic).map(A=>A.toLowerCase()).includes(e.toLowerCase()));if(e.length>0)throw new g.p(`Invalid admin roles: ${e.join(", ")}. Admin roles must be defined in the 'roles' configuration.`)}return{id:"admin",version:is.f,init:t=>({options:{databaseHooks:{user:{create:{before:async e=>({data:{role:A?.defaultRole??"user",...e}})}},session:{create:{async before(A,r){let i=r?.context.internalAdapter??t.internalAdapter,n=await i.findUserById(A.userId);if(n?.banned){if(n.banExpires&&new Date(n.banExpires).getTime()<Date.now())return void await i.updateUser(A.userId,{banned:!1,banReason:null,banExpires:null});let t=e.bannedUserMessage,r="function"==typeof t?await t(n):t;throw g.E.from("FORBIDDEN",{message:r,code:"BANNED_USER"})}}}}}}}),hooks:{after:[{matcher:A=>"/list-sessions"===A.path,handler:(0,l.a)(async A=>{let e=await iu(A);if(!e)return;let t=e.filter(A=>!A.impersonatedBy);return A.json(t)})}]},endpoints:{setRole:(0,l.g)("/admin/set-role",{method:"POST",body:iC,requireHeaders:!0,use:[iI],metadata:{openapi:{operationId:"setUserRole",summary:"Set the role of a user",description:"Set the role of a user",responses:{200:{description:"User role updated",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}},$Infer:{body:{}}}},async A=>{if(!ig({userId:A.context.session.user.id,role:A.context.session.user.role,options:e,permissions:{user:["set-role"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE);let t=e.roles;if(t){for(let e of Array.isArray(A.body.role)?A.body.role:[A.body.role])if(!t[e])throw g.E.from("BAD_REQUEST",id.YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE)}if(!await A.context.internalAdapter.findUserById(A.body.userId))throw g.E.from("NOT_FOUND",eI.f.USER_NOT_FOUND);let r=await A.context.internalAdapter.updateUser(A.body.userId,{role:ip(A.body.role)});return A.json({user:(0,m.$)(A.context.options,r)})}),getUser:(0,l.g)("/admin/get-user",{method:"GET",query:im,use:[iI],metadata:{openapi:{operationId:"getUser",summary:"Get an existing user",description:"Get an existing user",responses:{200:{description:"User",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async A=>{let{id:t}=A.query;if(!ig({userId:A.context.session.user.id,role:A.context.session.user.role,options:e,permissions:{user:["get"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_GET_USER);let r=await A.context.internalAdapter.findUserById(t);if(!r)throw g.E.from("NOT_FOUND",eI.f.USER_NOT_FOUND);return(0,m.$)(A.context.options,r)}),createUser:(0,l.g)("/admin/create-user",{method:"POST",body:iE,metadata:{openapi:{operationId:"createUser",summary:"Create a new user",description:"Create a new user",responses:{200:{description:"User created",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}},$Infer:{body:{}}}},async A=>{let t=await (0,h.M)(A);if(!t&&(A.request||A.headers))throw A.error("UNAUTHORIZED");if(t&&!ig({userId:t.user.id,role:t.user.role,options:e,permissions:{user:["create"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS);let{role:r,...i}=A.body.data??{},n=A.body.role??r;if(void 0!==n){if(t&&!ig({userId:t.user.id,role:t.user.role,options:e,permissions:{user:["set-role"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE);for(let A of Array.isArray(n)?n:[n]){if("string"!=typeof A)throw g.E.from("BAD_REQUEST",id.INVALID_ROLE_TYPE);if(e.roles&&!e.roles[A])throw g.E.from("BAD_REQUEST",id.YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE)}}if(t&&["banned","banReason","banExpires"].some(A=>Object.prototype.hasOwnProperty.call(i,A))&&!ig({userId:t.user.id,role:t.user.role,options:e,permissions:{user:["ban"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_BAN_USERS);let a=A.body.email.toLowerCase();if(!y.email().safeParse(a).success)throw g.E.from("BAD_REQUEST",eI.f.INVALID_EMAIL);if(A.body.password&&eC(A,A.body.password),await A.context.internalAdapter.findUserByEmail(a))throw g.E.from("BAD_REQUEST",id.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL);let s=await A.context.internalAdapter.createUser({...i,email:a,name:A.body.name,role:void 0!==n?ip(n):e?.defaultRole??"user"},{method:"admin"});if(!s)throw g.E.from("INTERNAL_SERVER_ERROR",id.FAILED_TO_CREATE_USER);if(A.body.password){let e=await A.context.password.hash(A.body.password);await A.context.internalAdapter.linkAccount({providerId:"credential",accountId:s.id,password:e,userId:s.id})}return A.json({user:(0,m.$)(A.context.options,s)})}),adminUpdateUser:(0,l.g)("/admin/update-user",{method:"POST",body:iw,use:[iI],metadata:{openapi:{operationId:"adminUpdateUser",summary:"Update a user",description:"Update a user's details",responses:{200:{description:"User updated",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async A=>{if(!ig({userId:A.context.session.user.id,role:A.context.session.user.role,options:e,permissions:{user:["update"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS);if(0===Object.keys(A.body.data).length)throw g.E.from("BAD_REQUEST",id.NO_DATA_TO_UPDATE);let t=A.body.data,r=A=>Object.prototype.hasOwnProperty.call(t,A);if(r("password"))throw g.E.from("BAD_REQUEST",id.PASSWORD_CANNOT_BE_UPDATED_VIA_UPDATE_USER);if(r("id"))throw g.E.from("BAD_REQUEST",id.USER_ID_CANNOT_BE_UPDATED);if(Object.prototype.hasOwnProperty.call(A.body.data,"role")){if(!ig({userId:A.context.session.user.id,role:A.context.session.user.role,options:e,permissions:{user:["set-role"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE);let t=A.body.data.role,r=Array.isArray(t)?t:[t];for(let A of r){if("string"!=typeof A)throw g.E.from("BAD_REQUEST",id.INVALID_ROLE_TYPE);if(e.roles&&!e.roles[A])throw g.E.from("BAD_REQUEST",id.YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE)}A.body.data.role=ip(r)}if(["banned","banReason","banExpires"].some(r)){if(!ig({userId:A.context.session.user.id,role:A.context.session.user.role,options:e,permissions:{user:["ban"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_BAN_USERS);if(!0===t.banned&&A.body.userId===A.context.session.user.id)throw g.E.from("BAD_REQUEST",id.YOU_CANNOT_BAN_YOURSELF)}if(r("email")||r("emailVerified")){if(!ig({userId:A.context.session.user.id,role:A.context.session.user.role,options:e,permissions:{user:["set-email"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_SET_USERS_EMAIL);if(r("email")){let e=String(t.email).toLowerCase();if(!y.email().safeParse(e).success)throw g.E.from("BAD_REQUEST",eI.f.INVALID_EMAIL);let r=await A.context.internalAdapter.findUserByEmail(e);if(r&&r.user.id!==A.body.userId)throw g.E.from("BAD_REQUEST",id.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL);t.email=e}}if((r("phoneNumber")||r("phoneNumberVerified"))&&!ig({userId:A.context.session.user.id,role:A.context.session.user.role,options:e,permissions:{user:["set-phone"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PHONE_NUMBER);if(!await A.context.internalAdapter.findUserById(A.body.userId))throw g.E.from("NOT_FOUND",eI.f.USER_NOT_FOUND);let i=await A.context.internalAdapter.updateUser(A.body.userId,A.body.data);return!0===t.banned&&await A.context.internalAdapter.deleteUserSessions(A.body.userId),A.json((0,m.$)(A.context.options,i))}),listUsers:(0,l.g)("/admin/list-users",{method:"GET",use:[iI],query:iy,metadata:{openapi:{operationId:"listUsers",summary:"List users",description:"List users",responses:{200:{description:"List of users",content:{"application/json":{schema:{type:"object",properties:{users:{type:"array",items:{$ref:"#/components/schemas/User"}},total:{type:"number"},limit:{type:"number"},offset:{type:"number"}},required:["users","total"]}}}}}}}},async A=>{let t=A.context.session;if(!ig({userId:A.context.session.user.id,role:t.user.role,options:e,permissions:{user:["list"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_LIST_USERS);let r=[];A.query?.searchValue&&r.push({field:A.query.searchField||"email",operator:A.query.searchOperator||"contains",value:A.query.searchValue}),A.query?.filterValue!==void 0&&r.push({field:A.query.filterField||"email",operator:A.query.filterOperator||"eq",value:A.query.filterValue});try{let e=await A.context.internalAdapter.listUsers(Number(A.query?.limit)||void 0,Number(A.query?.offset)||void 0,A.query?.sortBy?{field:A.query.sortBy,direction:A.query.sortDirection||"asc"}:void 0,r.length?r:void 0),t=await A.context.internalAdapter.countTotalUsers(r.length?r:void 0);return A.json({users:e.map(e=>(0,m.$)(A.context.options,e)),total:t,limit:Number(A.query?.limit)||void 0,offset:Number(A.query?.offset)||void 0})}catch{return A.json({users:[],total:0})}}),listUserSessions:(0,l.g)("/admin/list-user-sessions",{method:"POST",use:[iI],body:iQ,metadata:{openapi:{operationId:"adminListUserSessions",summary:"List user sessions",description:"List user sessions",responses:{200:{description:"List of user sessions",content:{"application/json":{schema:{type:"object",properties:{sessions:{type:"array",items:{$ref:"#/components/schemas/Session"}}}}}}}}}}},async A=>{let t=A.context.session;if(!ig({userId:A.context.session.user.id,role:t.user.role,options:e,permissions:{session:["list"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS);let r=await A.context.internalAdapter.listSessions(A.body.userId);return A.json({sessions:r.map(e=>(0,m.Q)(A.context.options,e))})}),unbanUser:(0,l.g)("/admin/unban-user",{method:"POST",body:iB,use:[iI],metadata:{openapi:{operationId:"unbanUser",summary:"Unban a user",description:"Unban a user",responses:{200:{description:"User unbanned",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async A=>{let t=A.context.session;if(!ig({userId:A.context.session.user.id,role:t.user.role,options:e,permissions:{user:["ban"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_BAN_USERS);if(!await A.context.internalAdapter.findUserById(A.body.userId))throw g.E.from("NOT_FOUND",eI.f.USER_NOT_FOUND);let r=await A.context.internalAdapter.updateUser(A.body.userId,{banned:!1,banExpires:null,banReason:null,updatedAt:new Date});return A.json({user:(0,m.$)(A.context.options,r)})}),banUser:(0,l.g)("/admin/ban-user",{method:"POST",body:iD,use:[iI],metadata:{openapi:{operationId:"banUser",summary:"Ban a user",description:"Ban a user",responses:{200:{description:"User banned",content:{"application/json":{schema:{type:"object",properties:{user:{$ref:"#/components/schemas/User"}}}}}}}}}},async A=>{let t=A.context.session;if(!ig({userId:A.context.session.user.id,role:t.user.role,options:e,permissions:{user:["ban"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_BAN_USERS);if(!await A.context.internalAdapter.findUserById(A.body.userId))throw g.E.from("NOT_FOUND",eI.f.USER_NOT_FOUND);if(A.body.userId===A.context.session.user.id)throw g.E.from("BAD_REQUEST",id.YOU_CANNOT_BAN_YOURSELF);let r=await A.context.internalAdapter.updateUser(A.body.userId,{banned:!0,banReason:A.body.banReason||e?.defaultBanReason||"No reason",banExpires:A.body.banExpiresIn?(0,A8.f)(A.body.banExpiresIn,"sec"):e?.defaultBanExpiresIn?(0,A8.f)(e.defaultBanExpiresIn,"sec"):null,updatedAt:new Date});return await A.context.internalAdapter.deleteUserSessions(A.body.userId),A.json({user:(0,m.$)(A.context.options,r)})}),impersonateUser:(0,l.g)("/admin/impersonate-user",{method:"POST",body:ik,use:[iI],metadata:{openapi:{operationId:"impersonateUser",summary:"Impersonate a user",description:"Impersonate a user",responses:{200:{description:"Impersonation session created",content:{"application/json":{schema:{type:"object",properties:{session:{$ref:"#/components/schemas/Session"},user:{$ref:"#/components/schemas/User"}}}}}}}}}},async A=>{if(!ig({userId:A.context.session.user.id,role:A.context.session.user.role,options:e,permissions:{user:["impersonate"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS);let t=await A.context.internalAdapter.findUserById(A.body.userId);if(!t)throw g.E.from("NOT_FOUND",eI.f.USER_NOT_FOUND);let r=(Array.isArray(e.adminRoles)?e.adminRoles:e.adminRoles?.split(",")||[]).map(A=>A.trim());if(((t.role||e.defaultRole||"user").split(",").some(A=>r.includes(A))||e.adminUserIds?.includes(t.id))&&!(!0===e.allowImpersonatingAdmins||ig({userId:A.context.session.user.id,role:A.context.session.user.role,options:e,permissions:{user:["impersonate-admins"]}})))throw g.E.from("FORBIDDEN",id.YOU_CANNOT_IMPERSONATE_ADMINS);let i=await A.context.internalAdapter.createSession(t.id,!0,{impersonatedBy:A.context.session.user.id,expiresAt:e?.impersonationSessionDuration?(0,A8.f)(e.impersonationSessionDuration,"sec"):(0,A8.f)(3600,"sec")},!0);if(!i)throw g.E.from("INTERNAL_SERVER_ERROR",id.FAILED_TO_CREATE_USER);let n=A.context.authCookies;(0,A4.Q)(A);let a=await A.getSignedCookie(A.context.authCookies.dontRememberToken.name,A.context.secret),s=A.context.createAuthCookie("admin_session");return await A.setSignedCookie(s.name,`${A.context.session.session.token}:${a||""}`,A.context.secret,n.sessionToken.attributes),await (0,A4.V)(A,{session:i,user:t},!0),A.json({session:i,user:(0,m.$)(A.context.options,t)})}),stopImpersonating:(0,l.g)("/admin/stop-impersonating",{method:"POST",requireHeaders:!0},async A=>{let e=await (0,h.D)(A);if(!e)throw g.E.fromStatus("UNAUTHORIZED");if(!e.session.impersonatedBy)throw g.E.fromStatus("BAD_REQUEST",{message:"You are not impersonating anyone"});let t=await A.context.internalAdapter.findUserById(e.session.impersonatedBy);if(!t)throw g.E.fromStatus("INTERNAL_SERVER_ERROR",{message:"Failed to find user"});let r=A.context.createAuthCookie("admin_session"),i=await A.getSignedCookie(r.name,A.context.secret);if(!i)throw g.E.fromStatus("INTERNAL_SERVER_ERROR",{message:"Failed to find admin session"});let[n,a]=i?.split(":"),s=await A.context.internalAdapter.findSession(n);if(!s||s.session.userId!==t.id)throw g.E.fromStatus("INTERNAL_SERVER_ERROR",{message:"Failed to find admin session"});return await A.context.internalAdapter.deleteSession(e.session.token),await (0,A4.V)(A,s,!!a),(0,A4.c)(A,r),A.json({session:(0,m.Q)(A.context.options,s.session),user:(0,m.$)(A.context.options,s.user)})}),revokeUserSession:(0,l.g)("/admin/revoke-user-session",{method:"POST",body:iS,use:[iI],metadata:{openapi:{operationId:"revokeUserSession",summary:"Revoke a user session",description:"Revoke a user session",responses:{200:{description:"Session revoked",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async A=>{let t=A.context.session;if(!ig({userId:A.context.session.user.id,role:t.user.role,options:e,permissions:{session:["revoke"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS);return await A.context.internalAdapter.deleteSession(A.body.sessionToken),A.json({success:!0})}),revokeUserSessions:(0,l.g)("/admin/revoke-user-sessions",{method:"POST",body:ib,use:[iI],metadata:{openapi:{operationId:"revokeUserSessions",summary:"Revoke all user sessions",description:"Revoke all user sessions",responses:{200:{description:"Sessions revoked",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async A=>{let t=A.context.session;if(!ig({userId:A.context.session.user.id,role:t.user.role,options:e,permissions:{session:["revoke"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS);return await A.context.internalAdapter.deleteUserSessions(A.body.userId),A.json({success:!0})}),removeUser:(0,l.g)("/admin/remove-user",{method:"POST",body:iM,use:[iI],metadata:{openapi:{operationId:"removeUser",summary:"Remove a user",description:"Delete a user and all their sessions and accounts. Cannot be undone.",responses:{200:{description:"User removed",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean"}}}}}}}}}},async A=>{let t=A.context.session;if(!ig({userId:A.context.session.user.id,role:t.user.role,options:e,permissions:{user:["delete"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS);if(A.body.userId===A.context.session.user.id)throw g.E.from("BAD_REQUEST",id.YOU_CANNOT_REMOVE_YOURSELF);if(!await A.context.internalAdapter.findUserById(A.body.userId))throw g.E.from("NOT_FOUND",eI.f.USER_NOT_FOUND);return await A.context.internalAdapter.deleteUserSessions(A.body.userId),await A.context.internalAdapter.deleteUser(A.body.userId),A.json({success:!0})}),setUserPassword:(0,l.g)("/admin/set-user-password",{method:"POST",body:iO,use:[iI],metadata:{openapi:{operationId:"setUserPassword",summary:"Set a user's password",description:"Set a user's password",responses:{200:{description:"Password set",content:{"application/json":{schema:{type:"object",properties:{status:{type:"boolean"}}}}}}}}}},async A=>{if(!ig({userId:A.context.session.user.id,role:A.context.session.user.role,options:e,permissions:{user:["set-password"]}}))throw g.E.from("FORBIDDEN",id.YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD);let{newPassword:t,userId:r}=A.body;ep(A,t),eC(A,t);let i=await A.context.internalAdapter.findUserById(r);if(!i)throw g.E.from("NOT_FOUND",eI.f.USER_NOT_FOUND);let n=await A.context.password.hash(t);return await A.context.internalAdapter.findCredentialAccount(r)?await A.context.internalAdapter.updatePassword(r,n):await A.context.internalAdapter.createAccount({userId:r,providerId:"credential",accountId:i.id,password:n}),A.json({status:!0})}),userHasPermission:(0,l.g)("/admin/has-permission",{method:"POST",body:iv,metadata:{openapi:{description:"Check if the user has permission",requestBody:{content:{"application/json":{schema:{type:"object",properties:{permissions:{type:"object",description:"The permission to check"}},required:["permissions"]}}}},responses:{200:{description:"Success",content:{"application/json":{schema:{type:"object",properties:{error:{type:"string"},success:{type:"boolean"}},required:["success"]}}}}}},$Infer:{body:{}}}},async A=>{if(!A.body?.permissions)throw new g.E("BAD_REQUEST",{message:"invalid permission check. no permission(s) were passed."});let t=await (0,h.M)(A);if(!t&&(A.request||A.headers))throw new g.E("UNAUTHORIZED");if(!t&&!A.body.userId&&!A.body.role)throw new g.E("BAD_REQUEST",{message:"user id or role is required"});let r=t?.user||(A.body.role?{id:A.body.userId||"",role:A.body.role}:null)||(A.body.userId?await A.context.internalAdapter.findUserById(A.body.userId):null);if(!r)throw new g.E("BAD_REQUEST",{message:"user not found"});let i=ig({userId:r.id,role:r.role,options:e,permissions:A.body.permissions});return A.json({error:null,success:i})})},$ERROR_CODES:id,schema:(0,m.C)(iR,e.schema),options:A}})({ac:n1,roles:{user:n4},defaultRole:"user",adminRoles:["user"]}),{setRole:e,banUser:t,unbanUser:r,impersonateUser:i,stopImpersonating:n,removeUser:a,...s}=A.endpoints;return{...A,endpoints:s}}(),function(A){if(Array.isArray(A)&&A.length>0){if(!A.every(A=>A.configId))throw new g.p("configId is required for each API key configuration in the api-key plugin.");let e=A.map(A=>A.configId);if(new Set(e).size!==e.length)throw new g.p("configId must be unique for each API key configuration in the api-key plugin.")}let e=(void 0)??{schema:Array.isArray(A)?void 0:A?.schema},t=[...(Array.isArray(A)?A:[A]).map(A=>({...A,apiKeyHeaders:A?.apiKeyHeaders??"x-api-key",defaultKeyLength:A?.defaultKeyLength||64,maximumPrefixLength:A?.maximumPrefixLength??32,minimumPrefixLength:A?.minimumPrefixLength??1,maximumNameLength:A?.maximumNameLength??32,minimumNameLength:A?.minimumNameLength??1,enableMetadata:A?.enableMetadata??!1,disableKeyHashing:A?.disableKeyHashing??!1,requireName:A?.requireName??!1,storage:A?.storage??"database",rateLimit:{enabled:A?.rateLimit?.enabled===void 0||A?.rateLimit?.enabled,timeWindow:A?.rateLimit?.timeWindow??864e5,maxRequests:A?.rateLimit?.maxRequests??10},keyExpiration:{defaultExpiresIn:A?.keyExpiration?.defaultExpiresIn??null,disableCustomExpiresTime:A?.keyExpiration?.disableCustomExpiresTime??!1,maxExpiresIn:A?.keyExpiration?.maxExpiresIn??365,minExpiresIn:A?.keyExpiration?.minExpiresIn??1},startingCharactersConfig:{shouldStore:A?.startingCharactersConfig?.shouldStore??!0,charactersLength:A?.startingCharactersConfig?.charactersLength??6},enableSessionForAPIKeys:A?.enableSessionForAPIKeys??!1,fallbackToDatabase:A?.fallbackToDatabase??!1,customStorage:A?.customStorage,deferUpdates:A?.deferUpdates??!1}))],r=(0,m.C)((({defaultRateLimitMax:A,defaultTimeWindow:e})=>({apikey:{fields:{configId:{type:"string",required:!0,defaultValue:"default",input:!1,index:!0},name:{type:"string",required:!1,input:!1},start:{type:"string",required:!1,input:!1},referenceId:{type:"string",required:!0,input:!1,index:!0},prefix:{type:"string",required:!1,input:!1},key:{type:"string",required:!0,input:!1,index:!0},refillInterval:{type:"number",required:!1,input:!1},refillAmount:{type:"number",required:!1,input:!1},lastRefillAt:{type:"date",required:!1,input:!1},enabled:{type:"boolean",required:!1,input:!1,defaultValue:!0},rateLimitEnabled:{type:"boolean",required:!1,input:!1,defaultValue:!0},rateLimitTimeWindow:{type:"number",required:!1,input:!1,defaultValue:e},rateLimitMax:{type:"number",required:!1,input:!1,defaultValue:A},requestCount:{type:"number",required:!1,input:!1,defaultValue:0},remaining:{type:"number",required:!1,input:!1},lastRequest:{type:"date",required:!1,input:!1},expiresAt:{type:"date",required:!1,input:!1},createdAt:{type:"date",required:!0,input:!1},updatedAt:{type:"date",required:!0,input:!1},permissions:{type:"string",required:!1,input:!1},metadata:{type:"string",required:!1,input:!0,transform:{input:A=>JSON.stringify(A),output:A=>A?(0,k.f)(A):null}}}}}))({defaultRateLimitMax:(1===t.length?t[0]?.rateLimit.maxRequests:void 0)??10,defaultTimeWindow:(1===t.length?t[0]?.rateLimit.timeWindow:void 0)??864e5}),e.schema);function i(A){for(let e of t){if(!e.enableSessionForAPIKeys)continue;let t=function(A,e){if(e.customAPIKeyGetter)return e.customAPIKeyGetter(A);if(Array.isArray(e.apiKeyHeaders)){for(let t of e.apiKeyHeaders){let e=A.headers?.get(t);if(e)return e}return null}return A.headers?.get(e.apiKeyHeaders)??null}(A,e);if(t)return{key:t,config:e}}return null}let n=function({defaultKeyGenerator:A,configurations:e,schema:t}){return{createApiKey:function({defaultKeyGenerator:A,configurations:e,schema:t,deleteAllExpiredApiKeys:r}){return(0,l.g)("/api-key/create",{method:"POST",body:Z,metadata:{openapi:{description:"Create a new API key for a user",responses:{200:{description:"API key created successfully",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string",description:"Unique identifier of the API key"},createdAt:{type:"string",format:"date-time",description:"Creation timestamp"},updatedAt:{type:"string",format:"date-time",description:"Last update timestamp"},name:{type:"string",nullable:!0,description:"Name of the API key"},prefix:{type:"string",nullable:!0,description:"Prefix of the API key"},start:{type:"string",nullable:!0,description:"Starting characters of the key (if configured)"},key:{type:"string",description:"The full API key (only returned on creation)"},enabled:{type:"boolean",description:"Whether the key is enabled"},expiresAt:{type:"string",format:"date-time",nullable:!0,description:"Expiration timestamp"},referenceId:{type:"string",description:"ID of the reference owning the key"},lastRefillAt:{type:"string",format:"date-time",nullable:!0,description:"Last refill timestamp"},lastRequest:{type:"string",format:"date-time",nullable:!0,description:"Last request timestamp"},metadata:{type:"object",nullable:!0,additionalProperties:!0,description:"Metadata associated with the key"},rateLimitMax:{type:"number",nullable:!0,description:"Maximum requests in time window"},rateLimitTimeWindow:{type:"number",nullable:!0,description:"Rate limit time window in milliseconds"},remaining:{type:"number",nullable:!0,description:"Remaining requests"},refillAmount:{type:"number",nullable:!0,description:"Amount to refill"},refillInterval:{type:"number",nullable:!0,description:"Refill interval in milliseconds"},rateLimitEnabled:{type:"boolean",description:"Whether rate limiting is enabled"},requestCount:{type:"number",description:"Current request count in window"},permissions:{type:"object",nullable:!0,additionalProperties:{type:"array",items:{type:"string"}},description:"Permissions associated with the key"}},required:["id","createdAt","updatedAt","key","enabled","referenceId","rateLimitEnabled","requestCount"]}}}}}}}},async t=>{let i,n,{configId:a,name:s,expiresIn:l,prefix:c,remaining:d,metadata:u,refillAmount:I,refillInterval:p,permissions:C,rateLimitMax:f,rateLimitTimeWindow:m,rateLimitEnabled:y}=t.body,Q=Ac(t.context,e,a),B=Q.customKeyGenerator||A,D=await (0,h.D)(t,{disableCookieCache:!0}),k=t.request||t.headers;if(k&&(void 0!==I||void 0!==p||void 0!==f||void 0!==m||void 0!==y||void 0!==C||null!==d))throw g.E.from("BAD_REQUEST",o.SERVER_ONLY_PROPERTY);if(t.request&&void 0!==t.body.userId)throw g.E.from("UNAUTHORIZED",o.UNAUTHORIZED_SESSION);if("organization"===(Q.references??"user")){let A=t.body.organizationId;if(!A){let A=o.ORGANIZATION_ID_REQUIRED;throw g.E.from("BAD_REQUEST",A)}let e=D?.user.id||t.body.userId;if(!e)throw g.E.from("UNAUTHORIZED",o.UNAUTHORIZED_SESSION);await K(t,e,A,"create"),i=A}else if(k){if(!D?.user.id){let A=o.UNAUTHORIZED_SESSION;throw g.E.from("UNAUTHORIZED",A)}i=D.user.id}else{let A=t.body.userId,e=D?.user.id;if(!e&&!A||D&&A&&e!==A){let A=o.UNAUTHORIZED_SESSION;throw g.E.from("UNAUTHORIZED",A)}i=e||A}if(u){if(!1===Q.enableMetadata)throw g.E.from("BAD_REQUEST",o.METADATA_DISABLED);if("object"!=typeof u)throw g.E.from("BAD_REQUEST",o.INVALID_METADATA_TYPE)}if(I&&!p){let A=o.REFILL_AMOUNT_AND_INTERVAL_REQUIRED;throw g.E.from("BAD_REQUEST",A)}if(p&&!I){let A=o.REFILL_INTERVAL_AND_AMOUNT_REQUIRED;throw g.E.from("BAD_REQUEST",A)}if(l){if(!0===Q.keyExpiration.disableCustomExpiresTime){let A=o.KEY_DISABLED_EXPIRATION;throw g.E.from("BAD_REQUEST",A)}let A=l/86400;if(Q.keyExpiration.minExpiresIn>A){let A=o.EXPIRES_IN_IS_TOO_SMALL;throw g.E.from("BAD_REQUEST",A)}if(Q.keyExpiration.maxExpiresIn<A){let A=o.EXPIRES_IN_IS_TOO_LARGE;throw g.E.from("BAD_REQUEST",A)}}if(c&&(c.length<Q.minimumPrefixLength||c.length>Q.maximumPrefixLength))throw g.E.from("BAD_REQUEST",o.INVALID_PREFIX_LENGTH);if(s){if(s.length<Q.minimumNameLength||s.length>Q.maximumNameLength)throw g.E.from("BAD_REQUEST",o.INVALID_NAME_LENGTH)}else if(Q.requireName)throw g.E.from("BAD_REQUEST",o.NAME_REQUIRED);r(t.context);let S=await B({length:Q.defaultKeyLength,prefix:c||Q.defaultPrefix}),b=Q.disableKeyHashing?S:await AI(S),M=null;Q.startingCharactersConfig.shouldStore&&(M=S.substring(0,Q.startingCharactersConfig.charactersLength));let O=Q.permissions?.defaultPermissions?"function"==typeof Q.permissions.defaultPermissions?await Q.permissions.defaultPermissions(i,t):Q.permissions.defaultPermissions:void 0,v=C?JSON.stringify(C):O?JSON.stringify(O):void 0,R={configId:Q.configId??"default",createdAt:new Date,updatedAt:new Date,name:s??null,prefix:c??Q.defaultPrefix??null,start:M,key:b,enabled:!0,expiresAt:l?$(l,"sec"):Q.keyExpiration.defaultExpiresIn?$(Q.keyExpiration.defaultExpiresIn,"sec"):null,referenceId:i,lastRefillAt:null,lastRequest:null,metadata:null,rateLimitMax:f??Q.rateLimit.maxRequests??null,rateLimitTimeWindow:m??Q.rateLimit.timeWindow??null,remaining:null===d?d:d??I??null,refillAmount:I??null,refillInterval:p??null,rateLimitEnabled:void 0===y?Q.rateLimit.enabled??!0:y,requestCount:0,permissions:v};if(u&&(R.metadata=u),"secondary-storage"===Q.storage&&Q.fallbackToDatabase)n=await t.context.adapter.create({model:Ap,data:R}),await F(t,n,Q);else if("secondary-storage"===Q.storage){let A=t.context.generateId({model:"apikey"})||(0,E.f)();n={...R,id:A},await F(t,n,Q)}else n=await t.context.adapter.create({model:Ap,data:R});return t.json({...n,key:S,metadata:u??null,permissions:n.permissions?(0,w.f)(n.permissions):null})})}({defaultKeyGenerator:A,configurations:e,schema:t,deleteAllExpiredApiKeys:Ah}),verifyApiKey:function({configurations:A,schema:e,deleteAllExpiredApiKeys:t}){return l.g.serverOnly({method:"POST",body:Al},async r=>{let i,{configId:n,key:a}=r.body,s=Ac(r.context,A,n);if(void 0!==n&&s.customAPIKeyValidator&&!await s.customAPIKeyValidator({ctx:r,key:a}))return r.json({valid:!1,error:{message:o.INVALID_API_KEY,code:"KEY_NOT_FOUND"},key:null});let l=null;try{let o=await Ai({key:a,permissions:r.body.permissions,ctx:r,lookupOpts:s,configurations:A,schema:e,expectedConfigId:n,runCustomValidator:void 0===n});l=o.apiKey,(i=o.opts).deferUpdates&&r.context.runInBackground(t(r.context).catch(A=>{r.context.logger.error("Failed to delete expired API keys:",A)}))}catch(A){if(r.context.logger.error("Failed to validate API key:",A),A instanceof g.E||A instanceof g.E||A?.name==="APIError")return r.json({valid:!1,error:{...A.body,message:A.body?.message,code:A.body?.code},key:null});return r.json({valid:!1,error:{message:o.INVALID_API_KEY,code:"INVALID_API_KEY"},key:null})}let{key:c,...d}=l??{key:1,permissions:void 0},u=null;return l&&(u=await O(r,l,i)),d.permissions=d.permissions?(0,w.f)(d.permissions):null,r.json({valid:!0,error:null,key:null===l?null:{...d,metadata:u}})})}({configurations:e,schema:t,deleteAllExpiredApiKeys:Ah}),getApiKey:function({configurations:A,schema:e,deleteAllExpiredApiKeys:t}){return(0,l.g)("/api-key/get",{method:"GET",query:AA,use:[h.Z],metadata:{openapi:{description:"Retrieve an existing API key by ID",responses:{200:{description:"API key retrieved successfully",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string",description:"ID"},name:{type:"string",nullable:!0,description:"The name of the key"},start:{type:"string",nullable:!0,description:"Shows the first few characters of the API key, including the prefix. This allows you to show those few characters in the UI to make it easier for users to identify the API key."},prefix:{type:"string",nullable:!0,description:"The API Key prefix. Stored as plain text."},userId:{type:"string",description:"The owner of the user id"},refillInterval:{type:"number",nullable:!0,description:"The interval in milliseconds between refills of the `remaining` count. Example: 3600000 // refill every hour (3600000ms = 1h)"},refillAmount:{type:"number",nullable:!0,description:"The amount to refill"},lastRefillAt:{type:"string",format:"date-time",nullable:!0,description:"The last refill date"},enabled:{type:"boolean",description:"Sets if key is enabled or disabled",default:!0},rateLimitEnabled:{type:"boolean",description:"Whether the key has rate limiting enabled"},rateLimitTimeWindow:{type:"number",nullable:!0,description:"The duration in milliseconds"},rateLimitMax:{type:"number",nullable:!0,description:"Maximum amount of requests allowed within a window"},requestCount:{type:"number",description:"The number of requests made within the rate limit time window"},remaining:{type:"number",nullable:!0,description:"Remaining requests (every time api key is used this should updated and should be updated on refill as well)"},lastRequest:{type:"string",format:"date-time",nullable:!0,description:"When last request occurred"},expiresAt:{type:"string",format:"date-time",nullable:!0,description:"Expiry date of a key"},createdAt:{type:"string",format:"date-time",description:"created at"},updatedAt:{type:"string",format:"date-time",description:"updated at"},metadata:{type:"object",nullable:!0,additionalProperties:!0,description:"Extra metadata about the apiKey"},permissions:{type:"string",nullable:!0,description:"Permissions for the api key (stored as JSON string)"}},required:["id","userId","enabled","rateLimitEnabled","requestCount","createdAt","updatedAt"]}}}}}}}},async e=>{let{configId:r,id:i}=e.query,n=e.context.session,a=Ac(e.context,A,r),s=null;if(!(s=await Y(e,i,a))||!Au(s.configId,a.configId))throw g.E.from("NOT_FOUND",o.KEY_NOT_FOUND);let l=Ac(e.context,A,s.configId);if((l.references??"user")==="organization")await K(e,n.user.id,s.referenceId,"read");else if(s.referenceId!==n.user.id)throw g.E.from("NOT_FOUND",o.KEY_NOT_FOUND);t(e.context);let c=await O(e,s,l),{key:d,...u}=s;return e.json({...u,metadata:c,permissions:u.permissions?(0,w.f)(u.permissions):null})})}({configurations:e,schema:t,deleteAllExpiredApiKeys:Ah}),updateApiKey:function({configurations:A,schema:e,deleteAllExpiredApiKeys:t}){return(0,l.g)("/api-key/update",{method:"POST",body:At,metadata:{openapi:{description:"Update an existing API key by ID",responses:{200:{description:"API key updated successfully",content:{"application/json":{schema:{type:"object",properties:{id:{type:"string",description:"ID"},name:{type:"string",nullable:!0,description:"The name of the key"},start:{type:"string",nullable:!0,description:"Shows the first few characters of the API key, including the prefix. This allows you to show those few characters in the UI to make it easier for users to identify the API key."},prefix:{type:"string",nullable:!0,description:"The API Key prefix. Stored as plain text."},userId:{type:"string",description:"The owner of the user id"},refillInterval:{type:"number",nullable:!0,description:"The interval in milliseconds between refills of the `remaining` count. Example: 3600000 // refill every hour (3600000ms = 1h)"},refillAmount:{type:"number",nullable:!0,description:"The amount to refill"},lastRefillAt:{type:"string",format:"date-time",nullable:!0,description:"The last refill date"},enabled:{type:"boolean",description:"Sets if key is enabled or disabled",default:!0},rateLimitEnabled:{type:"boolean",description:"Whether the key has rate limiting enabled"},rateLimitTimeWindow:{type:"number",nullable:!0,description:"The duration in milliseconds"},rateLimitMax:{type:"number",nullable:!0,description:"Maximum amount of requests allowed within a window"},requestCount:{type:"number",description:"The number of requests made within the rate limit time window"},remaining:{type:"number",nullable:!0,description:"Remaining requests (every time api key is used this should updated and should be updated on refill as well)"},lastRequest:{type:"string",format:"date-time",nullable:!0,description:"When last request occurred"},expiresAt:{type:"string",format:"date-time",nullable:!0,description:"Expiry date of a key"},createdAt:{type:"string",format:"date-time",description:"created at"},updatedAt:{type:"string",format:"date-time",description:"updated at"},metadata:{type:"object",nullable:!0,additionalProperties:!0,description:"Extra metadata about the apiKey"},permissions:{type:"string",nullable:!0,description:"Permissions for the api key (stored as JSON string)"}},required:["id","userId","enabled","rateLimitEnabled","requestCount","createdAt","updatedAt"]}}}}}}}},async e=>{let{configId:r,keyId:i,expiresIn:n,enabled:a,metadata:s,refillAmount:l,refillInterval:c,remaining:d,name:u,permissions:I,rateLimitEnabled:p,rateLimitTimeWindow:C,rateLimitMax:f}=e.body,m=await (0,h.D)(e,{disableCookieCache:!0}),E=e.request||e.headers,y=E&&!m?null:m?.user||{id:e.body.userId};if(!y?.id||m&&e.body.userId&&m?.user.id!==e.body.userId)throw g.E.from("UNAUTHORIZED",o.UNAUTHORIZED_SESSION);if(E&&(void 0!==l||void 0!==c||void 0!==f||void 0!==C||void 0!==p||void 0!==d||void 0!==I))throw g.E.from("BAD_REQUEST",o.SERVER_ONLY_PROPERTY);let Q=Ac(e.context,A,r),B=null;if(!(B=await Y(e,i,Q))||!Au(B.configId,Q.configId))throw g.E.from("NOT_FOUND",o.KEY_NOT_FOUND);let D=Ac(e.context,A,B.configId);if((D.references??"user")==="organization")await K(e,y.id,B.referenceId,"update");else if(B.referenceId!==y.id)throw g.E.from("NOT_FOUND",o.KEY_NOT_FOUND);let k={};if(void 0!==u){if(u.length<D.minimumNameLength||u.length>D.maximumNameLength)throw g.E.from("BAD_REQUEST",o.INVALID_NAME_LENGTH);k.name=u}if(void 0!==a&&(k.enabled=a),void 0!==n){if(!0===D.keyExpiration.disableCustomExpiresTime)throw g.E.from("BAD_REQUEST",o.KEY_DISABLED_EXPIRATION);if(null!==n){let A=n/86400;if(A<D.keyExpiration.minExpiresIn)throw g.E.from("BAD_REQUEST",o.EXPIRES_IN_IS_TOO_SMALL);if(A>D.keyExpiration.maxExpiresIn)throw g.E.from("BAD_REQUEST",o.EXPIRES_IN_IS_TOO_LARGE)}k.expiresAt=n?$(n,"sec"):null}if(void 0!==s&&!0===D.enableMetadata){if("object"!=typeof s)throw g.E.from("BAD_REQUEST",o.INVALID_METADATA_TYPE);k.metadata=s}if(void 0!==d&&(k.remaining=d),void 0!==l||void 0!==c){if(void 0!==l&&void 0===c)throw g.E.from("BAD_REQUEST",o.REFILL_AMOUNT_AND_INTERVAL_REQUIRED);if(void 0!==c&&void 0===l)throw g.E.from("BAD_REQUEST",o.REFILL_INTERVAL_AND_AMOUNT_REQUIRED);k.refillAmount=l,k.refillInterval=c}if(void 0!==p&&(k.rateLimitEnabled=p),void 0!==C&&(k.rateLimitTimeWindow=C),void 0!==f&&(k.rateLimitMax=f),void 0!==I&&(k.permissions=JSON.stringify(I)),0===Object.keys(k).length)throw g.E.from("BAD_REQUEST",o.NO_VALUES_TO_UPDATE);let S=B;try{if("secondary-storage"===D.storage&&D.fallbackToDatabase){let A=await e.context.adapter.update({model:Ap,where:[{field:"id",value:B.id}],update:k});A&&(await F(e,A,D),S=A)}else if("database"===D.storage){let A=await e.context.adapter.update({model:Ap,where:[{field:"id",value:B.id}],update:k});A&&(S=A)}else{let A={...B,...k,updatedAt:new Date};await F(e,A,D),S=A}}catch(A){throw g.E.fromStatus("INTERNAL_SERVER_ERROR",{message:A?.message})}t(e.context);let b=await O(e,S,D),{key:M,...v}=S;return e.json({...v,metadata:b,permissions:v.permissions?(0,w.f)(v.permissions):null})})}({configurations:e,schema:t,deleteAllExpiredApiKeys:Ah}),deleteApiKey:function({configurations:A,schema:e,deleteAllExpiredApiKeys:t}){return(0,l.g)("/api-key/delete",{method:"POST",body:X,use:[h.Z],metadata:{openapi:{description:"Delete an existing API key",requestBody:{content:{"application/json":{schema:{type:"object",properties:{keyId:{type:"string",description:"The id of the API key to delete"}},required:["keyId"]}}}},responses:{200:{description:"API key deleted successfully",content:{"application/json":{schema:{type:"object",properties:{success:{type:"boolean",description:"Indicates if the API key was successfully deleted"}},required:["success"]}}}}}}}},async e=>{let{configId:r,keyId:i}=e.body,n=e.context.session;if(!0===n.user.banned)throw g.E.from("UNAUTHORIZED",o.USER_BANNED);let a=Ac(e.context,A,r),s=null;if(!(s=await Y(e,i,a))||!Au(s.configId,a.configId))throw g.E.from("NOT_FOUND",o.KEY_NOT_FOUND);let l=Ac(e.context,A,s.configId);if((l.references??"user")==="organization")await K(e,n.user.id,s.referenceId,"delete");else if(s.referenceId!==n.user.id)throw g.E.from("NOT_FOUND",o.KEY_NOT_FOUND);try{"secondary-storage"===l.storage&&l.fallbackToDatabase?(await z(e,s,l),await e.context.adapter.delete({model:Ap,where:[{field:"id",value:s.id}]})):"database"===l.storage?await e.context.adapter.delete({model:Ap,where:[{field:"id",value:s.id}]}):await z(e,s,l)}catch(A){throw g.E.fromStatus("INTERNAL_SERVER_ERROR",{message:A?.message})}return t(e.context),e.json({success:!0})})}({configurations:e,schema:t,deleteAllExpiredApiKeys:Ah}),listApiKeys:function({configurations:A,schema:e,deleteAllExpiredApiKeys:t}){return(0,l.g)("/api-key/list",{method:"GET",use:[h.Z],query:Ae,metadata:{openapi:{description:"List all API keys for the authenticated user or for a specific organization",responses:{200:{description:"API keys retrieved successfully",content:{"application/json":{schema:{type:"object",properties:{apiKeys:{type:"array",items:{type:"object",properties:{id:{type:"string",description:"ID"},name:{type:"string",nullable:!0,description:"The name of the key"},start:{type:"string",nullable:!0,description:"Shows the first few characters of the API key, including the prefix. This allows you to show those few characters in the UI to make it easier for users to identify the API key."},prefix:{type:"string",nullable:!0,description:"The API Key prefix. Stored as plain text."},userId:{type:"string",description:"The owner of the user id"},refillInterval:{type:"number",nullable:!0,description:"The interval in milliseconds between refills of the `remaining` count. Example: 3600000 // refill every hour (3600000ms = 1h)"},refillAmount:{type:"number",nullable:!0,description:"The amount to refill"},lastRefillAt:{type:"string",format:"date-time",nullable:!0,description:"The last refill date"},enabled:{type:"boolean",description:"Sets if key is enabled or disabled",default:!0},rateLimitEnabled:{type:"boolean",description:"Whether the key has rate limiting enabled"},rateLimitTimeWindow:{type:"number",nullable:!0,description:"The duration in milliseconds"},rateLimitMax:{type:"number",nullable:!0,description:"Maximum amount of requests allowed within a window"},requestCount:{type:"number",description:"The number of requests made within the rate limit time window"},remaining:{type:"number",nullable:!0,description:"Remaining requests (every time api key is used this should updated and should be updated on refill as well)"},lastRequest:{type:"string",format:"date-time",nullable:!0,description:"When last request occurred"},expiresAt:{type:"string",format:"date-time",nullable:!0,description:"Expiry date of a key"},createdAt:{type:"string",format:"date-time",description:"created at"},updatedAt:{type:"string",format:"date-time",description:"updated at"},metadata:{type:"object",nullable:!0,additionalProperties:!0,description:"Extra metadata about the apiKey"},permissions:{type:"string",nullable:!0,description:"Permissions for the api key (stored as JSON string)"}},required:["id","userId","enabled","rateLimitEnabled","requestCount","createdAt","updatedAt"]}},total:{type:"number",description:"Total number of API keys"},limit:{type:"number",nullable:!0,description:"The limit used for pagination"},offset:{type:"number",nullable:!0,description:"The offset used for pagination"}},required:["apiKeys","total"]}}}}}}}},async e=>{let r=e.context.session,i=e.query?.configId,n=e.query?.organizationId,a=e.query?.limit!=null?Number(e.query.limit):void 0,s=e.query?.offset!=null?Number(e.query.offset):void 0;n&&await K(e,r.user.id,n,"read");let o=n??r.user.id,l=n?"organization":"user",c=[];if(i){let{apiKeys:t}=await V(e,o,Ac(e.context,A,i),{limit:void 0,offset:void 0,sortBy:e.query?.sortBy,sortDirection:e.query?.sortDirection});c=t}else{let t=new Map;for(let e of A){let A="database"===e.storage?"database":e.customStorage?`custom:${e.configId??"default"}`:e.fallbackToDatabase?"secondary-storage-with-fallback":"secondary-storage";t.has(A)||t.set(A,e)}let r=await Promise.all([...t.values()].map(A=>V(e,o,A,{limit:void 0,offset:void 0,sortBy:e.query?.sortBy,sortDirection:e.query?.sortDirection}))),i=new Set;for(let{apiKeys:A}of r)for(let e of A)i.has(e.id)||(i.add(e.id),c.push(e))}let d=c.filter(e=>(A.find(A=>Ad(e.configId)?Ad(A.configId):A.configId===e.configId)?.references??"user")===l&&e.referenceId===o);i&&(d=d.filter(A=>Au(A.configId,i)));let u=d.length,g=d;void 0!==s&&(g=g.slice(s)),void 0!==a&&(g=g.slice(0,a)),t(e.context);let h=g.map(A=>{let{key:e,...t}=A;return{...t,metadata:S(A.metadata),permissions:t.permissions?(0,w.f)(t.permissions):null}}),I=A.find(A=>"database"===A.storage||A.fallbackToDatabase);return I&&await e.context.runInBackgroundOrAwait(M(e,g,I)),e.json({apiKeys:h,total:u,limit:a,offset:s})})}({configurations:e,schema:t,deleteAllExpiredApiKeys:Ah}),deleteAllExpiredApiKeys:function({deleteAllExpiredApiKeys:A}){return l.g.serverOnly({method:"POST"},async e=>{try{await A(e.context,!0)}catch(A){return e.context.logger.error("[API KEY PLUGIN] Failed to delete expired API keys:",A),e.json({success:!1,error:A})}return e.json({success:!0,error:null})})}({deleteAllExpiredApiKeys:Ah})}}({defaultKeyGenerator:async A=>{let e=(0,f.f)(A.length,"a-z","A-Z");return`${A.prefix||""}${e}`},configurations:t,schema:r});return{id:"api-key",version:"1.7.16",$ERROR_CODES:o,hooks:{before:[{matcher:A=>!!i(A),handler:(0,l.a)(async A=>{let{key:e,config:n}=i(A);if("string"!=typeof e)throw g.E.from("BAD_REQUEST",o.INVALID_API_KEY_GETTER_RETURN_TYPE);if(e.length<n.defaultKeyLength||n.customAPIKeyValidator&&!await n.customAPIKeyValidator({ctx:A,key:e}))throw g.E.from("FORBIDDEN",o.INVALID_API_KEY);let{apiKey:a}=await Ai({key:e,ctx:A,lookupOpts:n,configurations:t,schema:r,expectedConfigId:n.configId}),s=Ah(A.context).catch(e=>{A.context.logger.error("Failed to delete expired API keys:",e)});if(n.deferUpdates&&A.context.runInBackground(s),(n.references??"user")!=="user"){let A=o.INVALID_REFERENCE_ID_FROM_API_KEY;throw g.E.from("UNAUTHORIZED",A)}let l=await A.context.internalAdapter.findUserById(a.referenceId);if(!l){let A=o.INVALID_REFERENCE_ID_FROM_API_KEY;throw g.E.from("UNAUTHORIZED",A)}let d={user:l,session:{id:a.id,token:e,userId:a.referenceId,userAgent:A.request?.headers.get("user-agent")??null,ipAddress:A.request?(0,c.M)(A.request,A.context.options):null,createdAt:new Date,updatedAt:new Date,expiresAt:a.expiresAt||$(A.context.options.session?.expiresIn||604800,"ms")}};return(await C(e),A.context.session=d,"/get-session"===A.path)?d:{context:A}})}]},endpoints:{createApiKey:n.createApiKey,verifyApiKey:n.verifyApiKey,getApiKey:n.getApiKey,updateApiKey:n.updateApiKey,deleteApiKey:n.deleteApiKey,listApiKeys:n.listApiKeys,deleteAllExpiredApiKeys:n.deleteAllExpiredApiKeys},schema:r}}({schema:{apikey:{modelName:"apiKey"}},defaultPrefix:"aide_",requireName:!0,startingCharactersConfig:{shouldStore:!0,charactersLength:12},keyExpiration:{defaultExpiresIn:null,disableCustomExpiresTime:!1,minExpiresIn:1,maxExpiresIn:3650},rateLimit:{enabled:!1},enableSessionForAPIKeys:!1}),{id:"bearer",version:is.f,hooks:{before:[{matcher:A=>!!(A.request?.headers.get("authorization")||A.headers?.get("authorization")),handler:(0,l.a)(async A=>{let e,t=A.request?.headers.get("authorization")||A.headers?.get("Authorization");if(!t||"bearer "!==t.slice(0,7).toLowerCase())return;let r=t.slice(7).trim();if(!r)return;e=r.includes(".")?r.includes("%")?iT(r):r:iT((await (0,iH.k)("",r,A.context.secret)).replace("=",""));try{if(!await (0,iN.f)("SHA-256","base64urlnopad").verify(A.context.secret,e.split(".")[0],e.split(".")[1]))return}catch{return}let i=A.request?.headers||A.headers,n=new Headers({...Object.fromEntries(i?.entries())});return(0,ia.K)(n,A.context.authCookies.sessionToken.name,e),{context:{headers:n}}})}],after:[{matcher:A=>!0,handler:(0,l.a)(async A=>{let e=A.context.responseHeaders?.get("set-cookie");if(!e)return;let t=(0,ia.p)(e),r=A.context.authCookies.sessionToken.name,i=t.get(r);if(!i||!i.value||0===i["max-age"])return;let n=i.value,a=new Set((A.context.responseHeaders?.get("access-control-expose-headers")||"").split(",").map(A=>A.trim()).filter(Boolean));a.add("set-auth-token"),A.setHeader("set-auth-token",n),A.setHeader("Access-Control-Expose-Headers",Array.from(a).join(", "))})}]},options:void 0},iJ(nX),...Q?[Q]:[],...t?nZ(A,t):[],(d=!1,{id:"next-cookies",version:is.f,hooks:{before:[{matcher:A=>"/get-session"===A.path,handler:(0,l.a)(async A=>{let e;if(d||(!function(A,e){let t=A.options.plugins||[];if(0===t.length)return;let r=t.findIndex(A=>A.id===e);-1===r||t.slice(r+1).some(A=>A.hooks&&Array.isArray(A.hooks.after)&&A.hooks.after.length>0)&&A.logger.warn(`[better-auth] Cookie integration plugin "${e}" should be placed last in the plugins array. Plugins with \`hooks.after\` running after it may set cookies that are not forwarded to the framework cookie store. Move your cookie integration plugin to the end of the \`plugins\` array to avoid missing \`Set-Cookie\` headers.`)}(A.context,"next-cookies"),d=!0),"_flag"in A&&"router"===A._flag)return;try{let{headers:A}=await io();e=await A()}catch{return}let t="1"===e.get("RSC"),r=!!e.get("next-action");t&&!r&&await (0,eU.w)(!0)})}],after:[{matcher:A=>!0,handler:(0,l.a)(async A=>{let e=A.context.responseHeaders;if((!("_flag"in A)||"router"!==A._flag)&&e instanceof Headers){let A,t=e?.get("set-cookie");if(!t)return;let r=(0,ia.p)(t);try{let{cookies:e}=await io();A=await e()}catch(A){if(A instanceof Error&&(A.message.startsWith("`cookies` was called outside a request scope.")||A.message.includes("Cannot find module")))return;throw A}r.forEach((e,t)=>{if(t)try{A.set(t,e.value,(0,ia.n)(e))}catch{}});return}})}]}})]},ii)})(A))),n8}A.s(["f",0,n5],792116);class n2 extends Error{status;constructor(A,e=401){super(A),this.status=e,this.name="PrincipalResolutionError"}}function n9(A){return/(?:^|;\s*)(?:__Secure-)?better-auth\.session_token=/.test(A.get("cookie")??"")}async function n6(A,e){if(Number(!!A.get("x-api-key")?.trim())+Number(!!A.get("authorization")?.trim())+Number(n9(A))>1)throw new n2("Provide exactly one application credential.",400);let t=A.get("x-api-key")?.trim()||null,r=function(A){let e=A.get("authorization");if(!e)return null;if(!e.startsWith("Bearer "))throw new n2("Authorization must use the Bearer scheme.");let t=e.slice(7).trim();if(!t)throw new n2("The bearer credential is empty.");return t}(A),i=n9(A);if(t){let A=await n5(),e=await A.api.verifyApiKey({body:{key:t}});if(!e.valid||!e.key)throw new n2("The API key is invalid or inactive.");return{kind:"apiKey",apiKeyId:e.key.id,userId:e.key.referenceId,name:e.key.name??null}}if(r?.startsWith("agent_")){if(!e)throw new n2("Agent credentials are not accepted by this endpoint.");let A=await e.authenticate(r);if(!A)throw new n2("The agent credential is invalid.");return{kind:"agent",agentId:A}}if(r||i){if(r&&3===r.split(".").length)throw new n2("OAuth access tokens are accepted only by the MCP endpoint.");let e=await n5(),t=await e.api.getSession({headers:A});if(!t?.session||!t.user)throw new n2("The session is invalid or expired.");return{kind:"user",userId:t.user.id,email:t.user.email,sessionId:t.session.id}}return{kind:"anonymous"}}A.s(["f",0,n6],847435)},914710,A=>{"use strict";A.i(792116),A.i(658978),A.i(847435),A.i(525796),A.s([],914710)},908323,A=>{"use strict";var e=A.i(135475);async function t(A){let t=await (0,e.U)(),r=await t.mcpAuthorization.findFirst({where:{id:A.authorizationId,userId:A.userId,clientId:A.clientId,revokedAt:null,user:{is:{id:A.userId}}}});return!!(r&&A.scopes.every(A=>r.scopes.split(" ").includes(A)))}A.i(792116),A.i(9416),A.i(847435),A.s(["f",0,t])},597812,A=>{"use strict";var e=A.i(666680),t=A.i(268573),r=A.i(845414),i=A.i(135475);A.i(256554);var n=A.i(118387),a=A.i(848201),s=A.i(520962),o=A.i(988438),l=A.i(682884);let c=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT","INVALID"]),d={agents:{include:{agent:!0}},jobs:{orderBy:{createdAt:"asc"}}};function u(A){return null!==A.lastSeenAt&&Date.now()-A.lastSeenAt.getTime()<=(0,n.z)(A)&&null===A.disconnectedAt}function g(A){try{let e=JSON.parse(A.capabilitiesJson);return Array.isArray(e)?e.filter(A=>"string"==typeof A):[]}catch{return[]}}function h(A){return null===A?null:JSON.parse(A)}function I(A){let e=h(A.payloadJson);return(A.kind===r.t?(0,r.A)(e).targets:(0,r.T)(e).targets).map(A=>A.path)}function p(A,e){let t=A===r.t?"delete":"size";return`Invalid Build Data ${t} result: ${e instanceof Error?e.message:String(e)}`}function C(A,e,t){try{for(let r of I(e)){let i=A.get(f(e.agentId,r));i&&(i.error=t)}}catch{}}function f(A,t){return(0,e.createHash)("sha256").update(A).update("\0").update(t).digest("base64url")}A.s(["f",0,class{agentControlService;initialized;nextHistoryPruneAt;historyPrune;constructor(A){this.agentControlService=A,this.initialized=!1,this.nextHistoryPruneAt=0,this.historyPrune=null,this.agentControlService.registerCompletionHandler(r.t,A=>this.projectDeletion(A))}async initialize(){this.initialized||(await this.pruneHistory(),this.initialized=!0)}async refresh(A){await this.initialize();let t=A?.trim()||(0,e.randomUUID)();return await this.ensureCollection(t),await this.getCollection(t)}async getCollection(A){await this.initialize();let e=await this.loadCollection(A);if(!e)return null;!e.finishedAt&&e.deadlineAt.getTime()<=Date.now()&&(await this.expireCollection(e),e=await this.loadCollection(A)??e);let t=await this.snapshot(e);if("COMPLETED"===t.status&&!e.finishedAt){let e=new Date,r=await (0,i.U)();await r.buildDataCollection.updateMany({where:{id:A,finishedAt:null},data:{finishedAt:e}}),t.finishedAt=e.toISOString()}return t}async *subscribe(A){await this.initialize();let e=a._H.iterate((0,a.I2)(A));try{let t=await this.getCollection(A);for(t&&(yield t);;){if((await e.next()).done)return;let t=await this.getCollection(A);t&&(yield t)}}finally{await e.return?.()}}async calculateSizes(A,e,t){let i=await this.requireCollection(A);return await this.createTargetJobs(i,e,t,r.G),await this.getCollection(A)}async deleteEntries(A,e,t,i=!1){let n=await this.requireCollection(A);return await this.createTargetJobs(n,e,t,r.t,i),await this.getCollection(A)}async history(A=100,e){await this.initialize(),await this.pruneHistory();let t=Math.max(1,Math.min(A,200)),r=await (0,i.U)(),n=e?await r.buildDataDeletionHistory.findUnique({where:{id:e},select:{id:!0,deletedAt:!0}}):null,a=await r.buildDataDeletionHistory.findMany({where:{deletedAt:{gte:new Date(Date.now()-7776e6)},...n?{OR:[{deletedAt:{lt:n.deletedAt}},{deletedAt:n.deletedAt,id:{lt:n.id}}]}:{}},orderBy:[{deletedAt:"desc"},{id:"desc"}],take:t+1}),s=a.length>t,o=a.slice(0,t);return{items:o,nextCursor:s?o.at(-1)?.id??null:null}}async clearHistory(){await this.initialize();let A=await (0,i.U)();return(await A.buildDataDeletionHistory.deleteMany()).count}async ensureCollection(A){let e=await (0,i.U)(),t=await e.buildDataCollection.findUnique({where:{id:A},select:{id:!0}});if(!t){let i=await this.agentControlService.listAgents();try{t=await e.buildDataCollection.create({data:{id:A,deadlineAt:new Date(Date.now()+6e4),agents:{create:i.map(A=>({agentId:A.id,initialStatus:u(A)?g(A).includes(r.F)?"QUEUING":"UNSUPPORTED":"OFFLINE"}))}},select:{id:!0}}),this.publish(A)}catch(r){if(!(t=await e.buildDataCollection.findUnique({where:{id:A},select:{id:!0}})))throw r}}await this.ensureScanJobs(A)}async ensureScanJobs(A){let e=await (0,i.U)(),n=await e.buildDataCollection.findUnique({where:{id:A},select:{deadlineAt:!0,finishedAt:!0}});if(!n||n.finishedAt||n.deadlineAt<=new Date)return;let a=await e.buildDataCollectionAgent.findMany({where:{collectionId:A,initialStatus:"QUEUING"},include:{agent:!0}}),s=new Set((await e.agentJob.findMany({where:{buildDataCollectionId:A,kind:r.F},select:{agentId:!0}})).map(A=>A.agentId));for(let i of a)if(!s.has(i.agentId))try{let n=await e.worktree.findMany({where:{missingAt:null,codebase:{agentId:i.agentId}},select:{id:!0,folder:!0}});await this.agentControlService.createJob({agentId:i.agentId,kind:r.F,payload:{mode:i.agent.derivedDataLocationMode,path:i.agent.derivedDataPath,...g(i.agent).includes(t.r)?{managedRoot:(0,o.j)(i.agent)?(0,o.T)((0,o.j)(i.agent)):null}:{},worktrees:n},idempotencyKey:`build-data:scan:${A}`,timeoutSeconds:45,buildDataCollectionId:A,visibility:"SYSTEM"})}catch(t){await e.buildDataCollectionAgent.update({where:{collectionId_agentId:{collectionId:A,agentId:i.agentId}},data:{initialStatus:"FAILED",error:t instanceof Error?t.message:String(t)}}),this.publish(A)}}async createTargetJobs(A,e,t,n,a=!1){let s=[...new Set(e)];if(!s.length)throw Error("Select at least one Derived Data entry");let o=new Map(A.entries.map(A=>[A.id,A])),l=s.map(A=>{let e=o.get(A);if(!e)throw Error("A selected Derived Data entry is no longer available");return e});if(n===r.t&&!a){let A=l.filter(A=>A.locked||A.activeResources.length>0);if(A.length)throw Error(`Explicit override confirmation is required to delete protected Derived Data: ${A.map(A=>A.name).join(", ")}`)}let c=new Map;for(let A of l){let e=c.get(A.agent.id)??[];e.push(A),c.set(A.agent.id,e)}let d=await (0,i.U)(),h=[];for(let[A,e]of c){let t=e[0].agent,r=await d.agent.findUnique({where:{id:A}});if(!r||!u(r))throw Error(`${t.name} is offline; reconnect it before running this operation`);if(!g(r).includes(n))throw Error(`${t.name} must be updated before this operation can run`);h.push({agentId:A,entries:e})}for(let{agentId:e,entries:i}of h){let a=n===r.t?[...new Map(i.filter(A=>!!A.worktreeId).map(A=>[A.worktreeId,A])).values()]:[],s=[];try{for(let A of a)await d.derivedDataCleanupLease.create({data:{worktreeId:A.worktreeId,agentId:e,path:A.path,source:"USER",expiresAt:new Date(Date.now()+6048e5)}}),s.push(A.worktreeId);let r=await this.agentControlService.createJob({agentId:e,kind:n,payload:{targets:i.map(({path:A,rootPath:e})=>({path:A,rootPath:e}))},idempotencyKey:`${n}:${A.id}:${t}:${e}`,timeoutSeconds:604800,buildDataCollectionId:A.id,visibility:"SYSTEM"});a.length&&await d.derivedDataCleanupLease.updateMany({where:{worktreeId:{in:a.map(A=>A.worktreeId)},jobId:null},data:{jobId:r.id}})}catch(A){throw s.length&&await d.derivedDataCleanupLease.deleteMany({where:{worktreeId:{in:s},source:"USER",jobId:null}}),A}}}async requireCollection(A){let e=await this.getCollection(A);if(!e)throw Error("Derived Data collection not found");if("COMPLETED"!==e.status)throw Error("Wait for the Derived Data scan to finish");return e}async loadCollection(A){return(await (0,i.U)()).buildDataCollection.findUnique({where:{id:A},include:d})}progress(A){let e=new Map(A.jobs.filter(A=>A.kind===r.F).map(A=>[A.agentId,A])),t=A.agents.map(A=>{let t=e.get(A.agentId),i=A.initialStatus,n=A.error,a=[];if("QUEUING"===A.initialStatus&&t&&(i=t.status,n=t.error,"SUCCEEDED"===t.status))try{a=(0,r.e)(h(t.resultJson)).warnings}catch(A){i="INVALID",n=A instanceof Error?A.message:String(A)}return{agent:A.agent,status:i,jobId:t?.id??null,error:n,warnings:a}}),i=t.filter(({status:A})=>"OFFLINE"!==A&&"UNSUPPORTED"!==A),n=i.filter(({status:A})=>c.has(A));return{agents:t,eligibleCount:i.length,finishedCount:n.length,successfulCount:i.filter(({status:A})=>"SUCCEEDED"===A).length}}async snapshot(A){let e=this.progress(A),t=await this.entries(A,!1);return{id:A.id,status:e.finishedCount===e.eligibleCount?"COMPLETED":"COLLECTING",createdAt:A.createdAt.toISOString(),deadlineAt:A.deadlineAt.toISOString(),finishedAt:A.finishedAt?.toISOString()??null,progress:e,entries:t}}async entries(A,e){let t=await (0,i.U)(),n=new Map(A.agents.map(A=>[A.agentId,A.agent])),a=await t.worktree.findMany({where:{missingAt:null,codebase:{agentId:{in:[...n.keys()]}}},include:{codebase:{select:{agentId:!0}}}}),o=new Map;for(let A of a){let e=o.get(A.codebase.agentId)??[];e.push(A),o.set(A.codebase.agentId,e)}let d=new Map;for(let e of A.jobs){let A;if(e.kind!==r.F||"SUCCEEDED"!==e.status)continue;let t=n.get(e.agentId);if(t){try{A=(0,r.e)(h(e.resultJson))}catch{continue}for(let r of A.entries){let A=(r.workspacePath?(o.get(e.agentId)??[]).filter(A=>(function(A,e){let t="/"===A?A:A.replace(/\/+$/,"");return e===t||e.startsWith(`${t}/`)})(A.folder,r.workspacePath)).sort((A,e)=>e.folder.length-A.folder.length):[])[0]??null,i=f(e.agentId,r.path);d.set(i,{id:i,name:r.name,kind:r.kind,status:"DEVICE_SUPPORT"===r.kind?"READY":"PENDING"===r.kind?"PENDING":"SHARED_CACHE"===r.kind?"SHARED_CACHE":A?"READY":"UNLINKED",workspacePath:r.workspacePath,worktreeId:A?.id??null,worktreePath:A?(0,s.b)(A.folder,t.baseRepoDirectory):null,sizeBytes:null,operation:"IDLE",error:null,agent:t,path:r.path,rootPath:r.rootPath,modifiedAt:r.modifiedAt,volumeId:r.volumeId,locked:!1,activeResources:[]})}}}for(let t of A.jobs){if(t.kind===r.G&&"SUCCEEDED"===t.status)try{for(let A of(0,r.i)(h(t.resultJson)).sizes){let e=d.get(f(t.agentId,A.path));e&&(e.sizeBytes=A.sizeBytes,e.error=A.error)}}catch(A){C(d,t,p(r.G,A))}if(t.kind===r.t&&"SUCCEEDED"===t.status)try{for(let A of(0,r.X)(h(t.resultJson)).deleted){let r=f(t.agentId,A.path),i=d.get(r);i&&(A.deleted&&!e?d.delete(r):i.error=A.error)}}catch(A){C(d,t,p(r.t,A))}if("QUEUED"===t.status||"RUNNING"===t.status){if(t.kind!==r.G&&t.kind!==r.t)continue;try{for(let A of I(t)){let e=d.get(f(t.agentId,A));e&&(e.operation=t.kind===r.t?"DELETING":"SIZING")}}catch{}}if("SUCCEEDED"!==t.status&&c.has(t.status)&&(t.kind===r.G||t.kind===r.t))try{for(let A of I(t)){let e=d.get(f(t.agentId,A));e&&(e.error=t.error||"Build Data operation failed")}}catch{}}let u=[...d.values()],g=u.map(A=>A.worktreeId).filter(A=>!!A),[m,E]=await Promise.all([t.derivedDataLock.findMany({where:{OR:u.map(A=>({agentId:A.agent.id,path:A.path}))},select:{agentId:!0,path:!0}}),(0,l.f)(g)]),w=new Set(m.map(A=>`${A.agentId}\0${A.path}`));for(let A of u)A.locked=w.has(`${A.agent.id}\0${A.path}`),A.activeResources=A.worktreeId?E.get(A.worktreeId)??[]:[];return u.sort((A,e)=>A.agent.name.localeCompare(e.agent.name)||(null===A.modifiedAt?1:null===e.modifiedAt?-1:new Date(A.modifiedAt).getTime()-new Date(e.modifiedAt).getTime())||A.name.localeCompare(e.name))}async setEntryLocked(A,t,r){let n=(await this.requireCollection(A)).entries.find(A=>A.id===t);if(!n)throw Error("Derived Data entry not found");let a=await (0,i.U)();return r?await a.derivedDataLock.upsert({where:{agentId_path:{agentId:n.agent.id,path:n.path}},create:{id:(0,e.randomUUID)(),agentId:n.agent.id,path:n.path},update:{}}):await a.derivedDataLock.deleteMany({where:{agentId:n.agent.id,path:n.path}}),this.publish(A),await this.getCollection(A)}async expireCollection(A){let e=await (0,i.U)(),t=new Set(A.jobs.filter(A=>A.kind===r.F).map(A=>A.agentId));await e.buildDataCollectionAgent.updateMany({where:{collectionId:A.id,initialStatus:"QUEUING",agentId:{notIn:[...t]}},data:{initialStatus:"TIMED_OUT"}}),await this.agentControlService.timeoutBuildDataCollectionJobs(A.id),this.publish(A.id)}async projectDeletion(A){let t;if("SUCCEEDED"!==A.status||!A.resultJson)return;await this.pruneHistory();let n=await (0,i.U)();if(await n.buildDataDeleteProjection.findUnique({where:{jobId:A.id}}))return;try{t=(0,r.X)(h(A.resultJson)).deleted.filter(A=>A.deleted)}catch(t){let e=p(r.t,t);try{await n.buildDataDeleteProjection.create({data:{jobId:A.id,error:e}})}catch(e){if(!await n.buildDataDeleteProjection.findUnique({where:{jobId:A.id}}))throw e}return}if(!t.length)return void await n.buildDataDeleteProjection.create({data:{jobId:A.id}});let a=(0,r.A)(h(A.payloadJson)),s=A.buildDataCollectionId?await this.loadCollection(A.buildDataCollectionId):null,o=new Map((s?await this.entries(s,!0):[]).filter(e=>e.agent.id===A.agentId).map(A=>[A.path,A])),l=new Map(a.targets.map(A=>[A.path,A])),c=await n.agent.findUnique({where:{id:A.agentId}});if(c)try{await n.$transaction(async r=>{if(!await r.buildDataDeleteProjection.findUnique({where:{jobId:A.id}}))for(let i of(await r.buildDataDeleteProjection.create({data:{jobId:A.id}}),t)){let t=o.get(i.path),n=l.get(i.path),s=n?.worktreeId??t?.worktreeId??null,d=s?(await r.worktree.findUnique({where:{id:s},select:{id:!0}}))?.id??null:null;await r.buildDataDeletionHistory.create({data:{id:(0,e.randomUUID)(),agentId:A.agentId,agentName:c.name,folderName:n?.name??t?.name??i.path,worktreeId:d,worktreePath:n?.worktreePath??t?.worktreePath??null,source:a.source,entryKind:n?.kind??t?.kind??"PROJECT",jobId:A.id,targetKey:t?.id??f(A.agentId,i.path)}})}})}catch(e){if(!await n.buildDataDeleteProjection.findUnique({where:{jobId:A.id}}))throw e}}async pruneHistory(){if(this.historyPrune)return this.historyPrune;if(!(Date.now()<this.nextHistoryPruneAt)){this.historyPrune=(async()=>{let A=await (0,i.U)();await A.buildDataDeletionHistory.deleteMany({where:{deletedAt:{lt:new Date(Date.now()-7776e6)}}}),this.nextHistoryPruneAt=Date.now()+6e4})();try{await this.historyPrune}finally{this.historyPrune=null}}}publish(A){let t={id:A,changeId:(0,e.randomUUID)()};a._H.publish(a.oz,{buildDataCollectionChanged:t}),a._H.publish((0,a.I2)(A),{buildDataCollectionChanged:t})}}])},46208,A=>{"use strict";A.i(597812),A.s([])},354473,A=>A.a(async(e,t)=>{try{A.s(["cachedArtifact",()=>I,"materializeArtifact",()=>f]);var r=A.i(666680),i=A.i(912714),n=A.i(660526),a=A.i(750227),s=A.i(135475),o=A.i(826587),l=A.i(604104),c=e([l]);[l]=c.then?(await c)():c;let m=process.env.ARTIFACT_CACHE_DIRECTORY?.trim()||(0,a.join)((0,n.tmpdir)(),"ade-build-artifact-cache"),E=Number(process.env.ARTIFACT_CACHE_MAX_BYTES)||0x140000000,w=globalThis,y=w.buildArtifactMaterializations??(w.buildArtifactMaterializations=new Map);async function d(A,e){try{await (0,i.rename)(A,e);return}catch(A){if("EXDEV"!==A.code)throw A}let t=`${e}.${(0,r.randomUUID)()}.incoming`;try{await (0,i.copyFile)(A,t),await (0,i.rename)(t,e),await (0,i.rm)(A,{force:!0})}finally{await (0,i.rm)(t,{force:!0}).catch(()=>{})}}async function u(A){try{let e=JSON.parse(await (0,i.readFile)(A,"utf8"));if(!e||"object"!=typeof e)return null;let{filename:t,contentType:r,size:n}=e;if("string"!=typeof t||"string"!=typeof r||"number"!=typeof n)return null;return{filename:t,contentType:r,size:n}}catch{return null}}async function g(A){let e=(0,a.join)(m,A),t=await u(`${e}.json`);if(!t)return null;try{let r=await (0,i.stat)(e);if(!r.isFile()||r.size!==t.size)return null;let n=new Date;return await (0,i.utimes)(e,n,n).catch(()=>{}),{path:e,etag:`"${A}"`,...t}}catch{return null}}async function h(A,e){var t;let i=(0,l.f)(),n=await i.buildsService.artifactForInstall(A,e);if(!n)throw Error("Build artifact not found");return{artifact:n,key:(t=n.checksum??n.createdAt,(0,r.createHash)("sha1").update(`${e}:${t}`).digest("hex"))}}async function I(A,e){let{key:t}=await h(A,e);return g(t)}async function p(A){let e,t=new Set;try{let A=await (0,s.U)();for(let e of(await A.buildArtifactTransfer.findMany({where:{status:{in:["READY","DOWNLOADING"]},expiresAt:{gt:new Date},stagingPath:{not:null}},select:{stagingPath:!0}})))e.stagingPath&&t.add(e.stagingPath)}catch{}try{e=await (0,i.readdir)(m)}catch{return}let r=[],n=Date.now()-216e5;for(let s of e){if(s.endsWith(".json"))continue;let e=(0,a.join)(m,s);try{let a=await (0,i.stat)(e);if(!a.isFile())continue;if(s.endsWith(".incoming")){a.mtimeMs<n&&await (0,i.rm)(e,{force:!0}).catch(()=>{});continue}r.push({path:e,size:a.size,mtimeMs:a.mtimeMs,keep:s===A||t.has(e)})}catch{continue}}r.sort((A,e)=>A.mtimeMs-e.mtimeMs);let o=r.reduce((A,e)=>A+e.size,0);for(let A of r)!A.keep&&(o<=E&&A.mtimeMs>=n||(await (0,i.rm)(A.path,{force:!0}).catch(()=>{}),await (0,i.rm)(`${A.path}.json`,{force:!0}).catch(()=>{}),o-=A.size))}async function C(A,e,t,n){let s=(0,r.randomUUID)(),c=(0,l.f)(),u=await c.buildsService.getBuild(A);if(!u?.agentId)throw Error("Build agent is unavailable");let g=Math.min(18e5,12e4+(n??0)/1e3),h=null;try{let[r]=await Promise.all([(0,o.e)(s,u.agentId,g),c.buildsService.prepareArtifactDownload(A,e,s,g)]);h=r.path,await (0,i.mkdir)(m,{recursive:!0,mode:448});let n=(0,a.join)(m,t);await d(r.path,n),h=null;let l=(await (0,i.stat)(n)).size,I={filename:r.filename,contentType:r.contentType,size:l};return await (0,i.writeFile)(`${n}.json`,JSON.stringify(I),{mode:384}),await p(t).catch(()=>{}),{path:n,etag:`"${t}"`,...I}}catch(A){throw(0,o.L)(s,A),h&&await (0,i.rm)(h,{force:!0}).catch(()=>{}),A}}async function f(A,e){let{artifact:t,key:r}=await h(A,e),i=await g(r);if(i)return i;let n=y.get(r);if(n)return n;let a=C(A,e,r,t.sizeBytes).finally(()=>{y.delete(r)});return y.set(r,a),a}t()}catch(A){t(A)}},!1),250746,A=>A.a(async(e,t)=>{try{A.s(["buildArtifactFileChecksum",()=>u,"failBuildArtifactTransferForJob",()=>g,"writeArtifactTransferBytes",()=>d]);var r=A.i(666680),i=A.i(902157);A.i(912714);var n=A.i(660526),a=A.i(750227),s=A.i(135475);A.i(256554);var o=A.i(848201),l=A.i(354473),c=e([l]);[l]=c.then?(await c)():c,process.env.ARTIFACT_TRANSFER_MAX_BYTES,process.env.ARTIFACT_TRANSFER_DIRECTORY?.trim()||(0,a.join)((0,n.tmpdir)(),"ade-build-artifact-transfers");let h=globalThis;async function d(A,e,t){let r=0;for(;r<e.byteLength;){let i=e.byteLength-r,{bytesWritten:n}=await A.write(e,r,i,t+r);if(!Number.isSafeInteger(n)||n<=0||n>i)throw Error("Artifact transfer file write made no progress");r+=n}}async function u(A){let e=(0,r.createHash)("sha256");for await(let t of(0,i.createReadStream)(A))e.update(t);return e.digest("hex")}async function g(A,e){let t=await (0,s.U)(),r=await t.buildArtifactTransfer.findFirst({where:{OR:[{sourceJobId:A},{targetJobId:A}]},include:{artifact:!0}});if(!(!r||["SUCCEEDED","FAILED"].includes(r.status))){var i;await t.$transaction([t.buildArtifactTransfer.update({where:{id:r.id},data:{status:"FAILED",error:e,finishedAt:new Date}}),t.buildDeployment.updateMany({where:{transferId:r.id,status:{in:["QUEUED","TRANSFERRING"]}},data:{status:"FAILED",error:e,finishedAt:new Date}})]),i=r.artifact.buildId,o._H.publish((0,o.cm)(i),{buildChanged:{id:i}}),o._H.publish(o.$A,{buildsChanged:{id:i}})}}h.buildArtifactTransferLocks??(h.buildArtifactTransferLocks=new Map),t()}catch(A){t(A)}},!1),826587,A=>{"use strict";A.i(902157),A.i(912714),A.i(660526),A.i(750227),A.i(81111),A.i(188646);let e=globalThis,t=e.buildArtifactTransfers??(e.buildArtifactTransfers=new Map);A.s(["L",0,function(A,e){let r=t.get(A);r&&(t.delete(A),clearTimeout(r.timeout),r.reject(e instanceof Error?e:Error(String(e))))},"e",0,function(A,e,r=17e4){return new Promise((i,n)=>{let a=setTimeout(()=>{t.delete(A),n(Error("The agent did not upload the artifact in time"))},r);a.unref(),t.set(A,{agentId:e,resolve:i,reject:n,timeout:a})})}])},988438,A=>{"use strict";var e=A.i(750227);function t(A){return(/^[a-z]:[\\/]/i.test(A)||A.startsWith("\\\\")?e.win32:e.posix).join(A,".worktree-derived-data")}A.s(["j",0,function(A){var t;return A.buildsDirectory??((t=A.baseRepoDirectory)?/^[a-z]:[\\/]/i.test(t)||t.startsWith("\\\\")?e.win32.join(t,"Builds"):e.posix.join(t,"Builds"):null)},"T",0,t,"r",0,function(A,r){if(!r||"."===r||".."===r||/[\\/\0]/.test(r))throw Error("Worktree identifier cannot be used as a Derived Data directory");return(/^[a-z]:[\\/]/i.test(A)||A.startsWith("\\\\")?e.win32:e.posix).join(t(A),r)}])},13666,A=>{"use strict";A.i(790142);var e=A.i(824236),t=A.i(861034);let r=A=>e.f.sql`
822
822
  1 = 1
823
823
  ${A.repositoryId?e.f.sql`AND b.repositoryId = ${A.repositoryId}`:t.f.empty}
824
824
  ${A.configurationId?e.f.sql`AND b.configurationId = ${A.configurationId}`:t.f.empty}