@ai-development-environment/server 0.0.103 → 0.0.105

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 (677) hide show
  1. package/package.json +1 -1
  2. package/standalone/.next/BUILD_ID +1 -1
  3. package/standalone/.next/build-manifest.json +3 -3
  4. package/standalone/.next/prerender-manifest.json +3 -3
  5. package/standalone/.next/server/app/[locale]/(auth)/register/page.js +1 -1
  6. package/standalone/.next/server/app/[locale]/(auth)/register/page.js.nft.json +1 -1
  7. package/standalone/.next/server/app/[locale]/(auth)/register/page_client-reference-manifest.js +1 -1
  8. package/standalone/.next/server/app/[locale]/(auth)/sign-in/page.js +1 -1
  9. package/standalone/.next/server/app/[locale]/(auth)/sign-in/page.js.nft.json +1 -1
  10. package/standalone/.next/server/app/[locale]/(auth)/sign-in/page_client-reference-manifest.js +1 -1
  11. package/standalone/.next/server/app/[locale]/(dashboard)/actions/page.js +1 -1
  12. package/standalone/.next/server/app/[locale]/(dashboard)/actions/page.js.nft.json +1 -1
  13. package/standalone/.next/server/app/[locale]/(dashboard)/actions/page_client-reference-manifest.js +1 -1
  14. package/standalone/.next/server/app/[locale]/(dashboard)/actions-cache/page.js +1 -1
  15. package/standalone/.next/server/app/[locale]/(dashboard)/actions-cache/page.js.nft.json +1 -1
  16. package/standalone/.next/server/app/[locale]/(dashboard)/actions-cache/page_client-reference-manifest.js +1 -1
  17. package/standalone/.next/server/app/[locale]/(dashboard)/agents/[id]/page.js +1 -1
  18. package/standalone/.next/server/app/[locale]/(dashboard)/agents/[id]/page.js.nft.json +1 -1
  19. package/standalone/.next/server/app/[locale]/(dashboard)/agents/[id]/page_client-reference-manifest.js +1 -1
  20. package/standalone/.next/server/app/[locale]/(dashboard)/agents/page.js +1 -1
  21. package/standalone/.next/server/app/[locale]/(dashboard)/agents/page.js.nft.json +1 -1
  22. package/standalone/.next/server/app/[locale]/(dashboard)/agents/page_client-reference-manifest.js +1 -1
  23. package/standalone/.next/server/app/[locale]/(dashboard)/analytics-events/page.js +1 -1
  24. package/standalone/.next/server/app/[locale]/(dashboard)/analytics-events/page.js.nft.json +1 -1
  25. package/standalone/.next/server/app/[locale]/(dashboard)/analytics-events/page_client-reference-manifest.js +1 -1
  26. package/standalone/.next/server/app/[locale]/(dashboard)/api-keys/page.js +1 -1
  27. package/standalone/.next/server/app/[locale]/(dashboard)/api-keys/page.js.nft.json +1 -1
  28. package/standalone/.next/server/app/[locale]/(dashboard)/api-keys/page_client-reference-manifest.js +1 -1
  29. package/standalone/.next/server/app/[locale]/(dashboard)/apps/[appId]/page.js +1 -1
  30. package/standalone/.next/server/app/[locale]/(dashboard)/apps/[appId]/page.js.nft.json +1 -1
  31. package/standalone/.next/server/app/[locale]/(dashboard)/apps/[appId]/page_client-reference-manifest.js +1 -1
  32. package/standalone/.next/server/app/[locale]/(dashboard)/apps/page.js +1 -1
  33. package/standalone/.next/server/app/[locale]/(dashboard)/apps/page.js.nft.json +1 -1
  34. package/standalone/.next/server/app/[locale]/(dashboard)/apps/page_client-reference-manifest.js +1 -1
  35. package/standalone/.next/server/app/[locale]/(dashboard)/build-data/page.js +1 -1
  36. package/standalone/.next/server/app/[locale]/(dashboard)/build-data/page.js.nft.json +1 -1
  37. package/standalone/.next/server/app/[locale]/(dashboard)/build-data/page_client-reference-manifest.js +1 -1
  38. package/standalone/.next/server/app/[locale]/(dashboard)/builds/[buildId]/coverage/page.js +1 -1
  39. package/standalone/.next/server/app/[locale]/(dashboard)/builds/[buildId]/coverage/page.js.nft.json +1 -1
  40. package/standalone/.next/server/app/[locale]/(dashboard)/builds/[buildId]/coverage/page_client-reference-manifest.js +1 -1
  41. package/standalone/.next/server/app/[locale]/(dashboard)/builds/[buildId]/output/route.js +1 -1
  42. package/standalone/.next/server/app/[locale]/(dashboard)/builds/[buildId]/output/route.js.nft.json +1 -1
  43. package/standalone/.next/server/app/[locale]/(dashboard)/builds/[buildId]/page.js +1 -1
  44. package/standalone/.next/server/app/[locale]/(dashboard)/builds/[buildId]/page.js.nft.json +1 -1
  45. package/standalone/.next/server/app/[locale]/(dashboard)/builds/[buildId]/page_client-reference-manifest.js +1 -1
  46. package/standalone/.next/server/app/[locale]/(dashboard)/builds/page.js +1 -1
  47. package/standalone/.next/server/app/[locale]/(dashboard)/builds/page.js.nft.json +1 -1
  48. package/standalone/.next/server/app/[locale]/(dashboard)/builds/page_client-reference-manifest.js +1 -1
  49. package/standalone/.next/server/app/[locale]/(dashboard)/changes/page.js +1 -1
  50. package/standalone/.next/server/app/[locale]/(dashboard)/changes/page.js.nft.json +1 -1
  51. package/standalone/.next/server/app/[locale]/(dashboard)/changes/page_client-reference-manifest.js +1 -1
  52. package/standalone/.next/server/app/[locale]/(dashboard)/codebases/[codebaseId]/page.js +1 -1
  53. package/standalone/.next/server/app/[locale]/(dashboard)/codebases/[codebaseId]/page.js.nft.json +1 -1
  54. package/standalone/.next/server/app/[locale]/(dashboard)/codebases/[codebaseId]/page_client-reference-manifest.js +1 -1
  55. package/standalone/.next/server/app/[locale]/(dashboard)/codebases/page.js +1 -1
  56. package/standalone/.next/server/app/[locale]/(dashboard)/codebases/page.js.nft.json +1 -1
  57. package/standalone/.next/server/app/[locale]/(dashboard)/codebases/page_client-reference-manifest.js +1 -1
  58. package/standalone/.next/server/app/[locale]/(dashboard)/codebases/repositories/[repositoryId]/page.js +1 -1
  59. package/standalone/.next/server/app/[locale]/(dashboard)/codebases/repositories/[repositoryId]/page.js.nft.json +1 -1
  60. package/standalone/.next/server/app/[locale]/(dashboard)/codebases/repositories/[repositoryId]/page_client-reference-manifest.js +1 -1
  61. package/standalone/.next/server/app/[locale]/(dashboard)/commands/[commandId]/edit/page.js +1 -1
  62. package/standalone/.next/server/app/[locale]/(dashboard)/commands/[commandId]/edit/page.js.nft.json +1 -1
  63. package/standalone/.next/server/app/[locale]/(dashboard)/commands/[commandId]/edit/page_client-reference-manifest.js +1 -1
  64. package/standalone/.next/server/app/[locale]/(dashboard)/commands/new/page.js +1 -1
  65. package/standalone/.next/server/app/[locale]/(dashboard)/commands/new/page.js.nft.json +1 -1
  66. package/standalone/.next/server/app/[locale]/(dashboard)/commands/new/page_client-reference-manifest.js +1 -1
  67. package/standalone/.next/server/app/[locale]/(dashboard)/commands/page.js +1 -1
  68. package/standalone/.next/server/app/[locale]/(dashboard)/commands/page.js.nft.json +1 -1
  69. package/standalone/.next/server/app/[locale]/(dashboard)/commands/page_client-reference-manifest.js +1 -1
  70. package/standalone/.next/server/app/[locale]/(dashboard)/commands/runs/[runId]/output/route.js +1 -1
  71. package/standalone/.next/server/app/[locale]/(dashboard)/commands/runs/[runId]/output/route.js.nft.json +1 -1
  72. package/standalone/.next/server/app/[locale]/(dashboard)/commands/runs/[runId]/page.js +1 -1
  73. package/standalone/.next/server/app/[locale]/(dashboard)/commands/runs/[runId]/page.js.nft.json +1 -1
  74. package/standalone/.next/server/app/[locale]/(dashboard)/commands/runs/[runId]/page_client-reference-manifest.js +1 -1
  75. package/standalone/.next/server/app/[locale]/(dashboard)/comments/page.js +1 -1
  76. package/standalone/.next/server/app/[locale]/(dashboard)/comments/page.js.nft.json +1 -1
  77. package/standalone/.next/server/app/[locale]/(dashboard)/comments/page_client-reference-manifest.js +1 -1
  78. package/standalone/.next/server/app/[locale]/(dashboard)/console-logs/page.js +1 -1
  79. package/standalone/.next/server/app/[locale]/(dashboard)/console-logs/page.js.nft.json +1 -1
  80. package/standalone/.next/server/app/[locale]/(dashboard)/console-logs/page_client-reference-manifest.js +1 -1
  81. package/standalone/.next/server/app/[locale]/(dashboard)/costs/page.js +1 -1
  82. package/standalone/.next/server/app/[locale]/(dashboard)/costs/page.js.nft.json +1 -1
  83. package/standalone/.next/server/app/[locale]/(dashboard)/costs/page_client-reference-manifest.js +1 -1
  84. package/standalone/.next/server/app/[locale]/(dashboard)/credentials/page.js +1 -1
  85. package/standalone/.next/server/app/[locale]/(dashboard)/credentials/page.js.nft.json +1 -1
  86. package/standalone/.next/server/app/[locale]/(dashboard)/credentials/page_client-reference-manifest.js +1 -1
  87. package/standalone/.next/server/app/[locale]/(dashboard)/devices/[id]/page.js +1 -1
  88. package/standalone/.next/server/app/[locale]/(dashboard)/devices/[id]/page.js.nft.json +1 -1
  89. package/standalone/.next/server/app/[locale]/(dashboard)/devices/[id]/page_client-reference-manifest.js +1 -1
  90. package/standalone/.next/server/app/[locale]/(dashboard)/devices/enroll/page.js +1 -1
  91. package/standalone/.next/server/app/[locale]/(dashboard)/devices/enroll/page.js.nft.json +1 -1
  92. package/standalone/.next/server/app/[locale]/(dashboard)/devices/enroll/page_client-reference-manifest.js +1 -1
  93. package/standalone/.next/server/app/[locale]/(dashboard)/devices/page.js +1 -1
  94. package/standalone/.next/server/app/[locale]/(dashboard)/devices/page.js.nft.json +1 -1
  95. package/standalone/.next/server/app/[locale]/(dashboard)/devices/page_client-reference-manifest.js +1 -1
  96. package/standalone/.next/server/app/[locale]/(dashboard)/drafts/page.js +1 -1
  97. package/standalone/.next/server/app/[locale]/(dashboard)/drafts/page.js.nft.json +1 -1
  98. package/standalone/.next/server/app/[locale]/(dashboard)/drafts/page_client-reference-manifest.js +1 -1
  99. package/standalone/.next/server/app/[locale]/(dashboard)/github-cache/entries/[id]/page.js +1 -1
  100. package/standalone/.next/server/app/[locale]/(dashboard)/github-cache/entries/[id]/page.js.nft.json +1 -1
  101. package/standalone/.next/server/app/[locale]/(dashboard)/github-cache/entries/[id]/page_client-reference-manifest.js +1 -1
  102. package/standalone/.next/server/app/[locale]/(dashboard)/github-cache/page.js +1 -1
  103. package/standalone/.next/server/app/[locale]/(dashboard)/github-cache/page.js.nft.json +1 -1
  104. package/standalone/.next/server/app/[locale]/(dashboard)/github-cache/page_client-reference-manifest.js +1 -1
  105. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/cache/page.js +1 -1
  106. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/cache/page.js.nft.json +1 -1
  107. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/cache/page_client-reference-manifest.js +1 -1
  108. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/comments/page.js +1 -1
  109. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/comments/page.js.nft.json +1 -1
  110. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/comments/page_client-reference-manifest.js +1 -1
  111. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/merge-requests/[projectId]/[iid]/page.js +1 -1
  112. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/merge-requests/[projectId]/[iid]/page.js.nft.json +1 -1
  113. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/merge-requests/[projectId]/[iid]/page_client-reference-manifest.js +1 -1
  114. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/merge-requests/page.js +1 -1
  115. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/merge-requests/page.js.nft.json +1 -1
  116. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/merge-requests/page_client-reference-manifest.js +1 -1
  117. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/pipelines/page.js +1 -1
  118. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/pipelines/page.js.nft.json +1 -1
  119. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/pipelines/page_client-reference-manifest.js +1 -1
  120. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/webhooks/page.js +1 -1
  121. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/webhooks/page.js.nft.json +1 -1
  122. package/standalone/.next/server/app/[locale]/(dashboard)/gitlab/webhooks/page_client-reference-manifest.js +1 -1
  123. package/standalone/.next/server/app/[locale]/(dashboard)/jira/tickets/[issueKey]/page.js +1 -1
  124. package/standalone/.next/server/app/[locale]/(dashboard)/jira/tickets/[issueKey]/page.js.nft.json +1 -1
  125. package/standalone/.next/server/app/[locale]/(dashboard)/jira/tickets/[issueKey]/page_client-reference-manifest.js +1 -1
  126. package/standalone/.next/server/app/[locale]/(dashboard)/jira/tickets/page.js +1 -1
  127. package/standalone/.next/server/app/[locale]/(dashboard)/jira/tickets/page.js.nft.json +1 -1
  128. package/standalone/.next/server/app/[locale]/(dashboard)/jira/tickets/page_client-reference-manifest.js +1 -1
  129. package/standalone/.next/server/app/[locale]/(dashboard)/jira-cache/page.js +1 -1
  130. package/standalone/.next/server/app/[locale]/(dashboard)/jira-cache/page.js.nft.json +1 -1
  131. package/standalone/.next/server/app/[locale]/(dashboard)/jira-cache/page_client-reference-manifest.js +1 -1
  132. package/standalone/.next/server/app/[locale]/(dashboard)/jira-cache/tickets/[issueKey]/page.js +1 -1
  133. package/standalone/.next/server/app/[locale]/(dashboard)/jira-cache/tickets/[issueKey]/page.js.nft.json +1 -1
  134. package/standalone/.next/server/app/[locale]/(dashboard)/jira-cache/tickets/[issueKey]/page_client-reference-manifest.js +1 -1
  135. package/standalone/.next/server/app/[locale]/(dashboard)/jira-webhooks/page.js +1 -1
  136. package/standalone/.next/server/app/[locale]/(dashboard)/jira-webhooks/page.js.nft.json +1 -1
  137. package/standalone/.next/server/app/[locale]/(dashboard)/jira-webhooks/page_client-reference-manifest.js +1 -1
  138. package/standalone/.next/server/app/[locale]/(dashboard)/jobs/[jobId]/page.js +1 -1
  139. package/standalone/.next/server/app/[locale]/(dashboard)/jobs/[jobId]/page.js.nft.json +1 -1
  140. package/standalone/.next/server/app/[locale]/(dashboard)/jobs/[jobId]/page_client-reference-manifest.js +1 -1
  141. package/standalone/.next/server/app/[locale]/(dashboard)/notifications/page.js +1 -1
  142. package/standalone/.next/server/app/[locale]/(dashboard)/notifications/page.js.nft.json +1 -1
  143. package/standalone/.next/server/app/[locale]/(dashboard)/notifications/page_client-reference-manifest.js +1 -1
  144. package/standalone/.next/server/app/[locale]/(dashboard)/page.js +1 -1
  145. package/standalone/.next/server/app/[locale]/(dashboard)/page.js.nft.json +1 -1
  146. package/standalone/.next/server/app/[locale]/(dashboard)/page_client-reference-manifest.js +1 -1
  147. package/standalone/.next/server/app/[locale]/(dashboard)/plans/[runId]/page.js +1 -1
  148. package/standalone/.next/server/app/[locale]/(dashboard)/plans/[runId]/page.js.nft.json +1 -1
  149. package/standalone/.next/server/app/[locale]/(dashboard)/plans/[runId]/page_client-reference-manifest.js +1 -1
  150. package/standalone/.next/server/app/[locale]/(dashboard)/plans/page.js +1 -1
  151. package/standalone/.next/server/app/[locale]/(dashboard)/plans/page.js.nft.json +1 -1
  152. package/standalone/.next/server/app/[locale]/(dashboard)/plans/page_client-reference-manifest.js +1 -1
  153. package/standalone/.next/server/app/[locale]/(dashboard)/polling/page.js +1 -1
  154. package/standalone/.next/server/app/[locale]/(dashboard)/polling/page.js.nft.json +1 -1
  155. package/standalone/.next/server/app/[locale]/(dashboard)/polling/page_client-reference-manifest.js +1 -1
  156. package/standalone/.next/server/app/[locale]/(dashboard)/prepare/page.js +1 -1
  157. package/standalone/.next/server/app/[locale]/(dashboard)/prepare/page.js.nft.json +1 -1
  158. package/standalone/.next/server/app/[locale]/(dashboard)/prepare/page_client-reference-manifest.js +1 -1
  159. package/standalone/.next/server/app/[locale]/(dashboard)/provisioning-profiles/[profileId]/page.js +1 -1
  160. package/standalone/.next/server/app/[locale]/(dashboard)/provisioning-profiles/[profileId]/page.js.nft.json +1 -1
  161. package/standalone/.next/server/app/[locale]/(dashboard)/provisioning-profiles/[profileId]/page_client-reference-manifest.js +1 -1
  162. package/standalone/.next/server/app/[locale]/(dashboard)/provisioning-profiles/page.js +1 -1
  163. package/standalone/.next/server/app/[locale]/(dashboard)/provisioning-profiles/page.js.nft.json +1 -1
  164. package/standalone/.next/server/app/[locale]/(dashboard)/provisioning-profiles/page_client-reference-manifest.js +1 -1
  165. package/standalone/.next/server/app/[locale]/(dashboard)/pull-requests/[owner]/[repository]/[number]/page.js +1 -1
  166. package/standalone/.next/server/app/[locale]/(dashboard)/pull-requests/[owner]/[repository]/[number]/page.js.nft.json +1 -1
  167. package/standalone/.next/server/app/[locale]/(dashboard)/pull-requests/[owner]/[repository]/[number]/page_client-reference-manifest.js +1 -1
  168. package/standalone/.next/server/app/[locale]/(dashboard)/pull-requests/page.js +1 -1
  169. package/standalone/.next/server/app/[locale]/(dashboard)/pull-requests/page.js.nft.json +1 -1
  170. package/standalone/.next/server/app/[locale]/(dashboard)/pull-requests/page_client-reference-manifest.js +1 -1
  171. package/standalone/.next/server/app/[locale]/(dashboard)/push-notifications/page.js +1 -1
  172. package/standalone/.next/server/app/[locale]/(dashboard)/push-notifications/page.js.nft.json +1 -1
  173. package/standalone/.next/server/app/[locale]/(dashboard)/push-notifications/page_client-reference-manifest.js +1 -1
  174. package/standalone/.next/server/app/[locale]/(dashboard)/runs/new/page.js +1 -1
  175. package/standalone/.next/server/app/[locale]/(dashboard)/runs/new/page.js.nft.json +1 -1
  176. package/standalone/.next/server/app/[locale]/(dashboard)/runs/new/page_client-reference-manifest.js +1 -1
  177. package/standalone/.next/server/app/[locale]/(dashboard)/sessions/[runId]/page.js +1 -1
  178. package/standalone/.next/server/app/[locale]/(dashboard)/sessions/[runId]/page.js.nft.json +1 -1
  179. package/standalone/.next/server/app/[locale]/(dashboard)/sessions/[runId]/page_client-reference-manifest.js +1 -1
  180. package/standalone/.next/server/app/[locale]/(dashboard)/sessions/page.js +1 -1
  181. package/standalone/.next/server/app/[locale]/(dashboard)/sessions/page.js.nft.json +1 -1
  182. package/standalone/.next/server/app/[locale]/(dashboard)/sessions/page_client-reference-manifest.js +1 -1
  183. package/standalone/.next/server/app/[locale]/(dashboard)/settings/page.js +1 -1
  184. package/standalone/.next/server/app/[locale]/(dashboard)/settings/page.js.nft.json +1 -1
  185. package/standalone/.next/server/app/[locale]/(dashboard)/settings/page_client-reference-manifest.js +1 -1
  186. package/standalone/.next/server/app/[locale]/(dashboard)/skills/[skillId]/page.js +1 -1
  187. package/standalone/.next/server/app/[locale]/(dashboard)/skills/[skillId]/page.js.nft.json +1 -1
  188. package/standalone/.next/server/app/[locale]/(dashboard)/skills/[skillId]/page_client-reference-manifest.js +1 -1
  189. package/standalone/.next/server/app/[locale]/(dashboard)/skills/groups/[groupId]/page.js +1 -1
  190. package/standalone/.next/server/app/[locale]/(dashboard)/skills/groups/[groupId]/page.js.nft.json +1 -1
  191. package/standalone/.next/server/app/[locale]/(dashboard)/skills/groups/[groupId]/page_client-reference-manifest.js +1 -1
  192. package/standalone/.next/server/app/[locale]/(dashboard)/skills/groups/page.js +1 -1
  193. package/standalone/.next/server/app/[locale]/(dashboard)/skills/groups/page.js.nft.json +1 -1
  194. package/standalone/.next/server/app/[locale]/(dashboard)/skills/groups/page_client-reference-manifest.js +1 -1
  195. package/standalone/.next/server/app/[locale]/(dashboard)/skills/page.js +1 -1
  196. package/standalone/.next/server/app/[locale]/(dashboard)/skills/page.js.nft.json +1 -1
  197. package/standalone/.next/server/app/[locale]/(dashboard)/skills/page_client-reference-manifest.js +1 -1
  198. package/standalone/.next/server/app/[locale]/(dashboard)/skills/sync/[runId]/page.js +1 -1
  199. package/standalone/.next/server/app/[locale]/(dashboard)/skills/sync/[runId]/page.js.nft.json +1 -1
  200. package/standalone/.next/server/app/[locale]/(dashboard)/skills/sync/[runId]/page_client-reference-manifest.js +1 -1
  201. package/standalone/.next/server/app/[locale]/(dashboard)/sse/[endpointId]/mocks/page.js +1 -1
  202. package/standalone/.next/server/app/[locale]/(dashboard)/sse/[endpointId]/mocks/page.js.nft.json +1 -1
  203. package/standalone/.next/server/app/[locale]/(dashboard)/sse/[endpointId]/mocks/page_client-reference-manifest.js +1 -1
  204. package/standalone/.next/server/app/[locale]/(dashboard)/sse/[endpointId]/page.js +1 -1
  205. package/standalone/.next/server/app/[locale]/(dashboard)/sse/[endpointId]/page.js.nft.json +1 -1
  206. package/standalone/.next/server/app/[locale]/(dashboard)/sse/[endpointId]/page_client-reference-manifest.js +1 -1
  207. package/standalone/.next/server/app/[locale]/(dashboard)/sse/breakpoints/page.js +1 -1
  208. package/standalone/.next/server/app/[locale]/(dashboard)/sse/breakpoints/page.js.nft.json +1 -1
  209. package/standalone/.next/server/app/[locale]/(dashboard)/sse/breakpoints/page_client-reference-manifest.js +1 -1
  210. package/standalone/.next/server/app/[locale]/(dashboard)/sse/history/[requestId]/page.js +1 -1
  211. package/standalone/.next/server/app/[locale]/(dashboard)/sse/history/[requestId]/page.js.nft.json +1 -1
  212. package/standalone/.next/server/app/[locale]/(dashboard)/sse/history/[requestId]/page_client-reference-manifest.js +1 -1
  213. package/standalone/.next/server/app/[locale]/(dashboard)/sse/history/page.js +1 -1
  214. package/standalone/.next/server/app/[locale]/(dashboard)/sse/history/page.js.nft.json +1 -1
  215. package/standalone/.next/server/app/[locale]/(dashboard)/sse/history/page_client-reference-manifest.js +1 -1
  216. package/standalone/.next/server/app/[locale]/(dashboard)/sse/new/page.js +1 -1
  217. package/standalone/.next/server/app/[locale]/(dashboard)/sse/new/page.js.nft.json +1 -1
  218. package/standalone/.next/server/app/[locale]/(dashboard)/sse/new/page_client-reference-manifest.js +1 -1
  219. package/standalone/.next/server/app/[locale]/(dashboard)/sse/page.js +1 -1
  220. package/standalone/.next/server/app/[locale]/(dashboard)/sse/page.js.nft.json +1 -1
  221. package/standalone/.next/server/app/[locale]/(dashboard)/sse/page_client-reference-manifest.js +1 -1
  222. package/standalone/.next/server/app/[locale]/(dashboard)/sse/storage/page.js +1 -1
  223. package/standalone/.next/server/app/[locale]/(dashboard)/sse/storage/page.js.nft.json +1 -1
  224. package/standalone/.next/server/app/[locale]/(dashboard)/sse/storage/page_client-reference-manifest.js +1 -1
  225. package/standalone/.next/server/app/[locale]/(dashboard)/status/page.js +1 -1
  226. package/standalone/.next/server/app/[locale]/(dashboard)/status/page.js.nft.json +1 -1
  227. package/standalone/.next/server/app/[locale]/(dashboard)/status/page_client-reference-manifest.js +1 -1
  228. package/standalone/.next/server/app/[locale]/(dashboard)/tailscale/page.js +1 -1
  229. package/standalone/.next/server/app/[locale]/(dashboard)/tailscale/page.js.nft.json +1 -1
  230. package/standalone/.next/server/app/[locale]/(dashboard)/tailscale/page_client-reference-manifest.js +1 -1
  231. package/standalone/.next/server/app/[locale]/(dashboard)/tools/page.js +1 -1
  232. package/standalone/.next/server/app/[locale]/(dashboard)/tools/page.js.nft.json +1 -1
  233. package/standalone/.next/server/app/[locale]/(dashboard)/tools/page_client-reference-manifest.js +1 -1
  234. package/standalone/.next/server/app/[locale]/(dashboard)/unified-events/page.js +1 -1
  235. package/standalone/.next/server/app/[locale]/(dashboard)/unified-events/page.js.nft.json +1 -1
  236. package/standalone/.next/server/app/[locale]/(dashboard)/unified-events/page_client-reference-manifest.js +1 -1
  237. package/standalone/.next/server/app/[locale]/(dashboard)/usage/page.js +1 -1
  238. package/standalone/.next/server/app/[locale]/(dashboard)/usage/page.js.nft.json +1 -1
  239. package/standalone/.next/server/app/[locale]/(dashboard)/usage/page_client-reference-manifest.js +1 -1
  240. package/standalone/.next/server/app/[locale]/(dashboard)/users/page.js +1 -1
  241. package/standalone/.next/server/app/[locale]/(dashboard)/users/page.js.nft.json +1 -1
  242. package/standalone/.next/server/app/[locale]/(dashboard)/users/page_client-reference-manifest.js +1 -1
  243. package/standalone/.next/server/app/[locale]/(dashboard)/webhooks/page.js +1 -1
  244. package/standalone/.next/server/app/[locale]/(dashboard)/webhooks/page.js.nft.json +1 -1
  245. package/standalone/.next/server/app/[locale]/(dashboard)/webhooks/page_client-reference-manifest.js +1 -1
  246. package/standalone/.next/server/app/[locale]/(dashboard)/workflows/[workflowId]/edit/page.js +1 -1
  247. package/standalone/.next/server/app/[locale]/(dashboard)/workflows/[workflowId]/edit/page.js.nft.json +1 -1
  248. package/standalone/.next/server/app/[locale]/(dashboard)/workflows/[workflowId]/edit/page_client-reference-manifest.js +1 -1
  249. package/standalone/.next/server/app/[locale]/(dashboard)/workflows/[workflowId]/page.js +1 -1
  250. package/standalone/.next/server/app/[locale]/(dashboard)/workflows/[workflowId]/page.js.nft.json +1 -1
  251. package/standalone/.next/server/app/[locale]/(dashboard)/workflows/[workflowId]/page_client-reference-manifest.js +1 -1
  252. package/standalone/.next/server/app/[locale]/(dashboard)/workflows/new/page.js +1 -1
  253. package/standalone/.next/server/app/[locale]/(dashboard)/workflows/new/page.js.nft.json +1 -1
  254. package/standalone/.next/server/app/[locale]/(dashboard)/workflows/new/page_client-reference-manifest.js +1 -1
  255. package/standalone/.next/server/app/[locale]/(dashboard)/workflows/page.js +1 -1
  256. package/standalone/.next/server/app/[locale]/(dashboard)/workflows/page.js.nft.json +1 -1
  257. package/standalone/.next/server/app/[locale]/(dashboard)/workflows/page_client-reference-manifest.js +1 -1
  258. package/standalone/.next/server/app/[locale]/(dashboard)/workflows/runs/[runId]/page.js +1 -1
  259. package/standalone/.next/server/app/[locale]/(dashboard)/workflows/runs/[runId]/page.js.nft.json +1 -1
  260. package/standalone/.next/server/app/[locale]/(dashboard)/workflows/runs/[runId]/page_client-reference-manifest.js +1 -1
  261. package/standalone/.next/server/app/[locale]/(dashboard)/worktrees/[worktreeId]/page.js +1 -1
  262. package/standalone/.next/server/app/[locale]/(dashboard)/worktrees/[worktreeId]/page.js.nft.json +1 -1
  263. package/standalone/.next/server/app/[locale]/(dashboard)/worktrees/[worktreeId]/page_client-reference-manifest.js +1 -1
  264. package/standalone/.next/server/app/[locale]/(dashboard)/worktrees/page.js +1 -1
  265. package/standalone/.next/server/app/[locale]/(dashboard)/worktrees/page.js.nft.json +1 -1
  266. package/standalone/.next/server/app/[locale]/(dashboard)/worktrees/page_client-reference-manifest.js +1 -1
  267. package/standalone/.next/server/app/_global-error.html +1 -1
  268. package/standalone/.next/server/app/_global-error.rsc +1 -1
  269. package/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  270. package/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  271. package/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  272. package/standalone/.next/server/app/_not-found.html +1 -1
  273. package/standalone/.next/server/app/_not-found.rsc +1 -1
  274. package/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  275. package/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  276. package/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  277. package/standalone/.next/server/app/api/agent/build-artifact-transfers/[transferId]/complete/route.js +1 -1
  278. package/standalone/.next/server/app/api/agent/build-artifact-transfers/[transferId]/complete/route.js.nft.json +1 -1
  279. package/standalone/.next/server/app/api/agent/build-artifact-transfers/[transferId]/download/route.js +1 -1
  280. package/standalone/.next/server/app/api/agent/build-artifact-transfers/[transferId]/download/route.js.nft.json +1 -1
  281. package/standalone/.next/server/app/api/agent/build-artifact-transfers/[transferId]/route.js +1 -1
  282. package/standalone/.next/server/app/api/agent/build-artifact-transfers/[transferId]/route.js.nft.json +1 -1
  283. package/standalone/.next/server/app/api/agent/build-artifact-transfers/[transferId]/upload/route.js +1 -1
  284. package/standalone/.next/server/app/api/agent/build-artifact-transfers/[transferId]/upload/route.js.nft.json +1 -1
  285. package/standalone/.next/server/app/api/agent/run-attachments/[attachmentId]/route.js +1 -1
  286. package/standalone/.next/server/app/api/agent/run-attachments/[attachmentId]/route.js.nft.json +1 -1
  287. package/standalone/.next/server/app/api/auth/[...all]/route.js +1 -1
  288. package/standalone/.next/server/app/api/auth/[...all]/route.js.nft.json +1 -1
  289. package/standalone/.next/server/app/api/auth/config/route.js +1 -1
  290. package/standalone/.next/server/app/api/auth/config/route.js.nft.json +1 -1
  291. package/standalone/.next/server/app/api/auth/management/api-keys/[keyId]/route.js +1 -1
  292. package/standalone/.next/server/app/api/auth/management/api-keys/[keyId]/route.js.nft.json +1 -1
  293. package/standalone/.next/server/app/api/auth/management/api-keys/route.js +1 -1
  294. package/standalone/.next/server/app/api/auth/management/api-keys/route.js.nft.json +1 -1
  295. package/standalone/.next/server/app/api/auth/management/registration/route.js +1 -1
  296. package/standalone/.next/server/app/api/auth/management/registration/route.js.nft.json +1 -1
  297. package/standalone/.next/server/app/api/auth/management/sessions/[sessionId]/route.js +1 -1
  298. package/standalone/.next/server/app/api/auth/management/sessions/[sessionId]/route.js.nft.json +1 -1
  299. package/standalone/.next/server/app/api/auth/management/users/[userId]/route.js +1 -1
  300. package/standalone/.next/server/app/api/auth/management/users/[userId]/route.js.nft.json +1 -1
  301. package/standalone/.next/server/app/api/auth/management/users/route.js +1 -1
  302. package/standalone/.next/server/app/api/auth/management/users/route.js.nft.json +1 -1
  303. package/standalone/.next/server/app/api/auth/mobile/oauth/complete/route.js +1 -1
  304. package/standalone/.next/server/app/api/auth/mobile/oauth/complete/route.js.nft.json +1 -1
  305. package/standalone/.next/server/app/api/auth/mobile/oauth/start/route.js +1 -1
  306. package/standalone/.next/server/app/api/auth/mobile/oauth/start/route.js.nft.json +1 -1
  307. package/standalone/.next/server/app/api/auth/mobile/redeem/route.js +1 -1
  308. package/standalone/.next/server/app/api/auth/mobile/redeem/route.js.nft.json +1 -1
  309. package/standalone/.next/server/app/api/build-artifact-uploads/[uploadId]/route.js +1 -1
  310. package/standalone/.next/server/app/api/build-artifact-uploads/[uploadId]/route.js.nft.json +1 -1
  311. package/standalone/.next/server/app/api/codebases/by-path/route.js +1 -1
  312. package/standalone/.next/server/app/api/codebases/by-path/route.js.nft.json +1 -1
  313. package/standalone/.next/server/app/api/codebases/route.js +1 -1
  314. package/standalone/.next/server/app/api/codebases/route.js.nft.json +1 -1
  315. package/standalone/.next/server/app/api/graphql/route.js +1 -1
  316. package/standalone/.next/server/app/api/graphql/route.js.nft.json +1 -1
  317. package/standalone/.next/server/app/api/ios/apns-devices/route.js +1 -1
  318. package/standalone/.next/server/app/api/ios/apns-devices/route.js.nft.json +1 -1
  319. package/standalone/.next/server/app/api/ios/devices/export.tsv/route.js +1 -1
  320. package/standalone/.next/server/app/api/ios/devices/export.tsv/route.js.nft.json +1 -1
  321. package/standalone/.next/server/app/api/ios/enrollment/start/route.js +1 -1
  322. package/standalone/.next/server/app/api/ios/enrollment/start/route.js.nft.json +1 -1
  323. package/standalone/.next/server/app/api/ios/notification-devices/route.js +1 -1
  324. package/standalone/.next/server/app/api/ios/notification-devices/route.js.nft.json +1 -1
  325. package/standalone/.next/server/app/api/mcp/route.js +1 -1
  326. package/standalone/.next/server/app/api/mcp/route.js.nft.json +1 -1
  327. package/standalone/.next/server/app/api/public/builds/[buildId]/artifacts/[artifactId]/manifest.plist/route.js +1 -1
  328. package/standalone/.next/server/app/api/public/builds/[buildId]/artifacts/[artifactId]/manifest.plist/route.js.nft.json +1 -1
  329. package/standalone/.next/server/app/api/public/builds/[buildId]/artifacts/[artifactId]/route.js +1 -1
  330. package/standalone/.next/server/app/api/public/builds/[buildId]/artifacts/[artifactId]/route.js.nft.json +1 -1
  331. package/standalone/.next/server/app/api/public/github/webhook/route.js +1 -1
  332. package/standalone/.next/server/app/api/public/github/webhook/route.js.nft.json +1 -1
  333. package/standalone/.next/server/app/api/public/gitlab/webhook/route.js +1 -1
  334. package/standalone/.next/server/app/api/public/gitlab/webhook/route.js.nft.json +1 -1
  335. package/standalone/.next/server/app/api/public/ios/enrollment-profile/route.js +1 -1
  336. package/standalone/.next/server/app/api/public/ios/enrollment-profile/route.js.nft.json +1 -1
  337. package/standalone/.next/server/app/api/public/ios/profile-response/route.js +1 -1
  338. package/standalone/.next/server/app/api/public/ios/profile-response/route.js.nft.json +1 -1
  339. package/standalone/.next/server/app/api/public/jira/webhook/route.js +1 -1
  340. package/standalone/.next/server/app/api/public/jira/webhook/route.js.nft.json +1 -1
  341. package/standalone/.next/server/app/api/public/sse/[token]/route.js +1 -1
  342. package/standalone/.next/server/app/api/public/sse/[token]/route.js.nft.json +1 -1
  343. package/standalone/.next/server/app/api/run-attachments/[attachmentId]/route.js +1 -1
  344. package/standalone/.next/server/app/api/run-attachments/[attachmentId]/route.js.nft.json +1 -1
  345. package/standalone/.next/server/app/api/run-attachments/route.js +1 -1
  346. package/standalone/.next/server/app/api/run-attachments/route.js.nft.json +1 -1
  347. package/standalone/.next/server/app/api/sse/history/export/route.js +1 -1
  348. package/standalone/.next/server/app/api/sse/history/export/route.js.nft.json +1 -1
  349. package/standalone/.next/server/app/api/telemetry/analytics-events/route.js +1 -1
  350. package/standalone/.next/server/app/api/telemetry/analytics-events/route.js.nft.json +1 -1
  351. package/standalone/.next/server/app/api/telemetry/console-logs/route.js +1 -1
  352. package/standalone/.next/server/app/api/telemetry/console-logs/route.js.nft.json +1 -1
  353. package/standalone/.next/server/app/api/telemetry/export/route.js +1 -1
  354. package/standalone/.next/server/app/api/telemetry/export/route.js.nft.json +1 -1
  355. package/standalone/.next/server/app/api/tools/call/route.js +1 -1
  356. package/standalone/.next/server/app/api/tools/call/route.js.nft.json +1 -1
  357. package/standalone/.next/server/app/api/tools/catalog/route.js +1 -1
  358. package/standalone/.next/server/app/api/tools/catalog/route.js.nft.json +1 -1
  359. package/standalone/.next/server/app/api/worktrees/[worktreeId]/diff-image/route.js +1 -1
  360. package/standalone/.next/server/app/api/worktrees/[worktreeId]/diff-image/route.js.nft.json +1 -1
  361. package/standalone/.next/server/chunks/{[root-of-the-server]__0pftx4_._.js → [root-of-the-server]__0-1z315._.js} +2 -2
  362. package/standalone/.next/server/chunks/{[root-of-the-server]__008-2eh._.js → [root-of-the-server]__0-h6hod._.js} +2 -2
  363. package/standalone/.next/server/chunks/{[root-of-the-server]__06alvfk._.js → [root-of-the-server]__0-u03f1._.js} +1 -1
  364. package/standalone/.next/server/chunks/{[root-of-the-server]__0-uklj2._.js → [root-of-the-server]__008w201._.js} +1 -1
  365. package/standalone/.next/server/chunks/{[root-of-the-server]__0-5-ijj._.js → [root-of-the-server]__017u6vp._.js} +1 -1
  366. package/standalone/.next/server/chunks/{[root-of-the-server]__0-__aom._.js → [root-of-the-server]__026n72c._.js} +1 -1
  367. package/standalone/.next/server/chunks/{[root-of-the-server]__05b0yhe._.js → [root-of-the-server]__02gan7e._.js} +1 -1
  368. package/standalone/.next/server/chunks/{[root-of-the-server]__1u8650_._.js → [root-of-the-server]__031mdlw._.js} +2 -2
  369. package/standalone/.next/server/chunks/{[root-of-the-server]__0-jt09-._.js → [root-of-the-server]__03fzm17._.js} +1 -1
  370. package/standalone/.next/server/chunks/{[root-of-the-server]__0-nblo_._.js → [root-of-the-server]__03l9kl3._.js} +1 -1
  371. package/standalone/.next/server/chunks/{[root-of-the-server]__03nqlt_._.js → [root-of-the-server]__05drfty._.js} +1 -1
  372. package/standalone/.next/server/chunks/{[root-of-the-server]__05td-p5._.js → [root-of-the-server]__05l5pw9._.js} +1 -1
  373. package/standalone/.next/server/chunks/[root-of-the-server]__05lax__._.js +3 -0
  374. package/standalone/.next/server/chunks/{[root-of-the-server]__0-l7oai._.js → [root-of-the-server]__06p9h4h._.js} +1 -1
  375. package/standalone/.next/server/chunks/[root-of-the-server]__06ss11_._.js +3 -0
  376. package/standalone/.next/server/chunks/{[root-of-the-server]__016rrtq._.js → [root-of-the-server]__07_ap71._.js} +1 -1
  377. package/standalone/.next/server/chunks/[root-of-the-server]__07jo7cq._.js +3 -0
  378. package/standalone/.next/server/chunks/[root-of-the-server]__08bhgy2._.js +3 -0
  379. package/standalone/.next/server/chunks/{[root-of-the-server]__0418l7g._.js → [root-of-the-server]__091i6h5._.js} +1 -1
  380. package/standalone/.next/server/chunks/[root-of-the-server]__09_iley._.js +3 -0
  381. package/standalone/.next/server/chunks/[root-of-the-server]__09ip98g._.js +3 -0
  382. package/standalone/.next/server/chunks/{[root-of-the-server]__003a_z1._.js → [root-of-the-server]__09lxrbf._.js} +1 -1
  383. package/standalone/.next/server/chunks/{[root-of-the-server]__082iwcf._.js → [root-of-the-server]__09xml_-._.js} +1 -1
  384. package/standalone/.next/server/chunks/{[root-of-the-server]__04d42w9._.js → [root-of-the-server]__0a2-sb-._.js} +2 -2
  385. package/standalone/.next/server/chunks/{[root-of-the-server]__02aif-e._.js → [root-of-the-server]__0a3nt0c._.js} +1 -1
  386. package/standalone/.next/server/chunks/{[root-of-the-server]__1moxr-1._.js → [root-of-the-server]__0a4ns45._.js} +2 -2
  387. package/standalone/.next/server/chunks/{[root-of-the-server]__1adx_n3._.js → [root-of-the-server]__0a_bt4t._.js} +2 -2
  388. package/standalone/.next/server/chunks/{[root-of-the-server]__08fe1t5._.js → [root-of-the-server]__0abcqvc._.js} +1 -1
  389. package/standalone/.next/server/chunks/[root-of-the-server]__0ah_x0d._.js +3 -0
  390. package/standalone/.next/server/chunks/[root-of-the-server]__0c2l-2l._.js +3 -0
  391. package/standalone/.next/server/chunks/{[root-of-the-server]__0som2ah._.js → [root-of-the-server]__0ccuegb._.js} +2 -2
  392. package/standalone/.next/server/chunks/{[root-of-the-server]__01gh89w._.js → [root-of-the-server]__0cdvbhy._.js} +1 -1
  393. package/standalone/.next/server/chunks/{[root-of-the-server]__1m98kvc._.js → [root-of-the-server]__0ciq1bb._.js} +2 -2
  394. package/standalone/.next/server/chunks/{[root-of-the-server]__0bl1lat._.js → [root-of-the-server]__0cpnota._.js} +1 -1
  395. package/standalone/.next/server/chunks/[root-of-the-server]__0d4j-k8._.js +3 -0
  396. package/standalone/.next/server/chunks/[root-of-the-server]__0ds-nea._.js +3 -0
  397. package/standalone/.next/server/chunks/{[root-of-the-server]__19a3tcu._.js → [root-of-the-server]__0euccqa._.js} +1 -1
  398. package/standalone/.next/server/chunks/{[root-of-the-server]__0meqeo0._.js → [root-of-the-server]__0fi-6hj._.js} +1 -1
  399. package/standalone/.next/server/chunks/{[root-of-the-server]__0ynwgfc._.js → [root-of-the-server]__0gdquzc._.js} +2 -2
  400. package/standalone/.next/server/chunks/{[root-of-the-server]__03xyftj._.js → [root-of-the-server]__0gowrk2._.js} +1 -1
  401. package/standalone/.next/server/chunks/[root-of-the-server]__0gvjl5i._.js +3 -0
  402. package/standalone/.next/server/chunks/[root-of-the-server]__0gzp60j._.js +3 -0
  403. package/standalone/.next/server/chunks/[root-of-the-server]__0h5uq70._.js +3 -0
  404. package/standalone/.next/server/chunks/[root-of-the-server]__0i6co60._.js +1 -1
  405. package/standalone/.next/server/chunks/[root-of-the-server]__0ix1ahr._.js +3 -0
  406. package/standalone/.next/server/chunks/[root-of-the-server]__0jaiizx._.js +3 -0
  407. package/standalone/.next/server/chunks/[root-of-the-server]__0jbthmv._.js +3 -0
  408. package/standalone/.next/server/chunks/[root-of-the-server]__0kjbziu._.js +3 -0
  409. package/standalone/.next/server/chunks/[root-of-the-server]__0kpcc3r._.js +3 -0
  410. package/standalone/.next/server/chunks/[root-of-the-server]__0kwguoc._.js +3 -0
  411. package/standalone/.next/server/chunks/[root-of-the-server]__0l_rmbb._.js +3 -0
  412. package/standalone/.next/server/chunks/[root-of-the-server]__0m-8xhj._.js +3 -0
  413. package/standalone/.next/server/chunks/[root-of-the-server]__0mkq5nf._.js +3 -0
  414. package/standalone/.next/server/chunks/{[root-of-the-server]__1d2ytms._.js → [root-of-the-server]__0mlidx7._.js} +2 -2
  415. package/standalone/.next/server/chunks/{[root-of-the-server]__0esm0f-._.js → [root-of-the-server]__0mtdzeh._.js} +2 -2
  416. package/standalone/.next/server/chunks/{[root-of-the-server]__0km8fy0._.js → [root-of-the-server]__0n-sidi._.js} +2 -2
  417. package/standalone/.next/server/chunks/[root-of-the-server]__0n9a48o._.js +3 -0
  418. package/standalone/.next/server/chunks/[root-of-the-server]__0ndxzjb._.js +3 -0
  419. package/standalone/.next/server/chunks/[root-of-the-server]__0oxg83m._.js +3 -0
  420. package/standalone/.next/server/chunks/{[root-of-the-server]__1goyat3._.js → [root-of-the-server]__0pjv_oq._.js} +2 -2
  421. package/standalone/.next/server/chunks/[root-of-the-server]__0py42vf._.js +3 -0
  422. package/standalone/.next/server/chunks/[root-of-the-server]__0q2u5vf._.js +3 -0
  423. package/standalone/.next/server/chunks/[root-of-the-server]__0q6wif7._.js +3 -0
  424. package/standalone/.next/server/chunks/{[root-of-the-server]__10wri77._.js → [root-of-the-server]__0qb75r2._.js} +2 -2
  425. package/standalone/.next/server/chunks/[root-of-the-server]__0qp0un9._.js +3 -0
  426. package/standalone/.next/server/chunks/[root-of-the-server]__0sf6zxl._.js +3 -0
  427. package/standalone/.next/server/chunks/[root-of-the-server]__0t8gllb._.js +3 -0
  428. package/standalone/.next/server/chunks/[root-of-the-server]__0tpjilm._.js +3 -0
  429. package/standalone/.next/server/chunks/[root-of-the-server]__0umogw3._.js +3 -0
  430. package/standalone/.next/server/chunks/[root-of-the-server]__0uzqpro._.js +3 -0
  431. package/standalone/.next/server/chunks/[root-of-the-server]__0vvc984._.js +3 -0
  432. package/standalone/.next/server/chunks/[root-of-the-server]__0w3ozyh._.js +3 -0
  433. package/standalone/.next/server/chunks/{[root-of-the-server]__1hwt2p2._.js → [root-of-the-server]__0wljfol._.js} +2 -2
  434. package/standalone/.next/server/chunks/[root-of-the-server]__0x-posm._.js +3 -0
  435. package/standalone/.next/server/chunks/[root-of-the-server]__0x2gige._.js +3 -0
  436. package/standalone/.next/server/chunks/[root-of-the-server]__0xkrt2c._.js +3 -0
  437. package/standalone/.next/server/chunks/[root-of-the-server]__0xqlfuq._.js +3 -0
  438. package/standalone/.next/server/chunks/[root-of-the-server]__0yd7pt7._.js +3 -0
  439. package/standalone/.next/server/chunks/[root-of-the-server]__0z6i23o._.js +3 -0
  440. package/standalone/.next/server/chunks/[root-of-the-server]__0z7raqx._.js +3 -0
  441. package/standalone/.next/server/chunks/[root-of-the-server]__1-6mk9r._.js +3 -0
  442. package/standalone/.next/server/chunks/[root-of-the-server]__1-o7if-._.js +3 -0
  443. package/standalone/.next/server/chunks/[root-of-the-server]__1-t49h_._.js +3 -0
  444. package/standalone/.next/server/chunks/[root-of-the-server]__104z1gt._.js +3 -0
  445. package/standalone/.next/server/chunks/[root-of-the-server]__10cko7c._.js +3 -0
  446. package/standalone/.next/server/chunks/[root-of-the-server]__10z41pf._.js +3 -0
  447. package/standalone/.next/server/chunks/{[root-of-the-server]__0zhffo0._.js → [root-of-the-server]__117qim2._.js} +2 -2
  448. package/standalone/.next/server/chunks/[root-of-the-server]__11_pg0_._.js +3 -0
  449. package/standalone/.next/server/chunks/[root-of-the-server]__12-zogr._.js +3 -0
  450. package/standalone/.next/server/chunks/[root-of-the-server]__12s9_gv._.js +3 -0
  451. package/standalone/.next/server/chunks/[root-of-the-server]__139ypjb._.js +3 -0
  452. package/standalone/.next/server/chunks/[root-of-the-server]__13fuxw1._.js +3 -0
  453. package/standalone/.next/server/chunks/[root-of-the-server]__14jdhch._.js +3 -0
  454. package/standalone/.next/server/chunks/[root-of-the-server]__154rhq6._.js +3 -0
  455. package/standalone/.next/server/chunks/[root-of-the-server]__15f0kzr._.js +3 -0
  456. package/standalone/.next/server/chunks/[root-of-the-server]__16529yo._.js +3 -0
  457. package/standalone/.next/server/chunks/{[root-of-the-server]__1jmg8g6._.js → [root-of-the-server]__173ds9r._.js} +2 -2
  458. package/standalone/.next/server/chunks/[root-of-the-server]__177edxq._.js +3 -0
  459. package/standalone/.next/server/chunks/[root-of-the-server]__17d5k-p._.js +3 -0
  460. package/standalone/.next/server/chunks/[root-of-the-server]__18-5hbn._.js +3 -0
  461. package/standalone/.next/server/chunks/[root-of-the-server]__180d_8r._.js +3 -0
  462. package/standalone/.next/server/chunks/[root-of-the-server]__197242j._.js +3 -0
  463. package/standalone/.next/server/chunks/[root-of-the-server]__19c1-0o._.js +3 -0
  464. package/standalone/.next/server/chunks/{[root-of-the-server]__0ybzlg-._.js → [root-of-the-server]__1_3t6gq._.js} +2 -2
  465. package/standalone/.next/server/chunks/[root-of-the-server]__1_dqx4a._.js +3 -0
  466. package/standalone/.next/server/chunks/[root-of-the-server]__1a4tskl._.js +3 -0
  467. package/standalone/.next/server/chunks/[root-of-the-server]__1a75jia._.js +3 -0
  468. package/standalone/.next/server/chunks/[root-of-the-server]__1a9xwwe._.js +3 -0
  469. package/standalone/.next/server/chunks/[root-of-the-server]__1bb79ej._.js +3 -0
  470. package/standalone/.next/server/chunks/[root-of-the-server]__1cgyjel._.js +3 -0
  471. package/standalone/.next/server/chunks/[root-of-the-server]__1d5-kei._.js +3 -0
  472. package/standalone/.next/server/chunks/[root-of-the-server]__1d5f3go._.js +3 -0
  473. package/standalone/.next/server/chunks/[root-of-the-server]__1dmaupm._.js +3 -0
  474. package/standalone/.next/server/chunks/[root-of-the-server]__1dzpyeo._.js +3 -0
  475. package/standalone/.next/server/chunks/[root-of-the-server]__1e4h_8d._.js +3 -0
  476. package/standalone/.next/server/chunks/[root-of-the-server]__1e55xu8._.js +3 -0
  477. package/standalone/.next/server/chunks/[root-of-the-server]__1e7boqc._.js +3 -0
  478. package/standalone/.next/server/chunks/[root-of-the-server]__1ejanf7._.js +3 -0
  479. package/standalone/.next/server/chunks/[root-of-the-server]__1fj0u0h._.js +3 -0
  480. package/standalone/.next/server/chunks/{[root-of-the-server]__00bayt8._.js → [root-of-the-server]__1fj4i62._.js} +2 -2
  481. package/standalone/.next/server/chunks/[root-of-the-server]__1fz50a_._.js +3 -0
  482. package/standalone/.next/server/chunks/[root-of-the-server]__1i70gon._.js +3 -0
  483. package/standalone/.next/server/chunks/[root-of-the-server]__1i9dwgw._.js +3 -0
  484. package/standalone/.next/server/chunks/[root-of-the-server]__1j5wr_0._.js +3 -0
  485. package/standalone/.next/server/chunks/{[root-of-the-server]__0h5xzi0._.js → [root-of-the-server]__1j634q7._.js} +1 -1
  486. package/standalone/.next/server/chunks/[root-of-the-server]__1j_bo3h._.js +3 -0
  487. package/standalone/.next/server/chunks/[root-of-the-server]__1jcuws5._.js +3 -0
  488. package/standalone/.next/server/chunks/[root-of-the-server]__1jmechu._.js +3 -0
  489. package/standalone/.next/server/chunks/[root-of-the-server]__1jwm3ay._.js +3 -0
  490. package/standalone/.next/server/chunks/[root-of-the-server]__1k9ljk0._.js +3 -0
  491. package/standalone/.next/server/chunks/[root-of-the-server]__1kqw3ze._.js +3 -0
  492. package/standalone/.next/server/chunks/[root-of-the-server]__1lrrnrk._.js +3 -0
  493. package/standalone/.next/server/chunks/{[root-of-the-server]__14ufav8._.js → [root-of-the-server]__1mndrc5._.js} +2 -2
  494. package/standalone/.next/server/chunks/[root-of-the-server]__1nddo_-._.js +3 -0
  495. package/standalone/.next/server/chunks/[root-of-the-server]__1nvx4a7._.js +3 -0
  496. package/standalone/.next/server/chunks/[root-of-the-server]__1o74gxl._.js +3 -0
  497. package/standalone/.next/server/chunks/[root-of-the-server]__1oc76co._.js +3 -0
  498. package/standalone/.next/server/chunks/[root-of-the-server]__1odtl8q._.js +3 -0
  499. package/standalone/.next/server/chunks/[root-of-the-server]__1p0eko0._.js +3 -0
  500. package/standalone/.next/server/chunks/[root-of-the-server]__1p64w7c._.js +3 -0
  501. package/standalone/.next/server/chunks/[root-of-the-server]__1pdbrg4._.js +3 -0
  502. package/standalone/.next/server/chunks/[root-of-the-server]__1pguxgt._.js +3 -0
  503. package/standalone/.next/server/chunks/[root-of-the-server]__1pnlbrp._.js +3 -0
  504. package/standalone/.next/server/chunks/[root-of-the-server]__1q0w-ke._.js +3 -0
  505. package/standalone/.next/server/chunks/[root-of-the-server]__1qu9ubp._.js +3 -0
  506. package/standalone/.next/server/chunks/[root-of-the-server]__1rppuo1._.js +3 -0
  507. package/standalone/.next/server/chunks/{[root-of-the-server]__043sxkt._.js → [root-of-the-server]__1s-hz4e._.js} +3 -3
  508. package/standalone/.next/server/chunks/{[root-of-the-server]__17twz-k._.js → [root-of-the-server]__1spt-bt._.js} +2 -2
  509. package/standalone/.next/server/chunks/[root-of-the-server]__1st4e7h._.js +3 -0
  510. package/standalone/.next/server/chunks/[root-of-the-server]__1t_yij3._.js +3 -0
  511. package/standalone/.next/server/chunks/[root-of-the-server]__1upboky._.js +3 -0
  512. package/standalone/.next/server/chunks/[root-of-the-server]__1utlkew._.js +3 -0
  513. package/standalone/.next/server/chunks/[root-of-the-server]__1uvwps7._.js +3 -0
  514. package/standalone/.next/server/chunks/[root-of-the-server]__1uwx47q._.js +3 -0
  515. package/standalone/.next/server/chunks/[root-of-the-server]__1uzi6wy._.js +3 -0
  516. package/standalone/.next/server/chunks/[root-of-the-server]__1v3_h_8._.js +3 -0
  517. package/standalone/.next/server/chunks/[root-of-the-server]__1v_x3-z._.js +3 -0
  518. package/standalone/.next/server/chunks/[root-of-the-server]__1vu4utg._.js +3 -0
  519. package/standalone/.next/server/chunks/[root-of-the-server]__1vzhk1o._.js +3 -0
  520. package/standalone/.next/server/chunks/[root-of-the-server]__1wn46m4._.js +3 -0
  521. package/standalone/.next/server/chunks/[root-of-the-server]__1xb6a9r._.js +3 -0
  522. package/standalone/.next/server/chunks/[root-of-the-server]__1y6nfsc._.js +3 -0
  523. package/standalone/.next/server/chunks/[root-of-the-server]__1y9qp5e._.js +3 -0
  524. package/standalone/.next/server/chunks/[root-of-the-server]__1z-oj-a._.js +3 -0
  525. package/standalone/.next/server/chunks/[root-of-the-server]__1zc9ssi._.js +3 -0
  526. package/standalone/.next/server/chunks/{[root-of-the-server]__07qtgl8._.js → [root-of-the-server]__1zz6g62._.js} +2 -2
  527. package/standalone/.next/server/chunks/[root-of-the-server]__20glztx._.js +3 -0
  528. package/standalone/.next/server/chunks/[root-of-the-server]__20wae87._.js +3 -0
  529. package/standalone/.next/server/chunks/[root-of-the-server]__216fzje._.js +3 -0
  530. package/standalone/.next/server/chunks/_05hmt-3._.js +2 -2
  531. package/standalone/.next/server/chunks/_07hehic._.js +2 -2
  532. package/standalone/.next/server/chunks/_10r2rsn._.js +2 -2
  533. package/standalone/.next/server/chunks/ssr/{[root-of-the-server]__1mb4-7-._.js → [root-of-the-server]__0ix-rxo._.js} +1 -1
  534. package/standalone/.next/server/chunks/ssr/{[root-of-the-server]__0v8tcdf._.js → [root-of-the-server]__15yzrti._.js} +1 -1
  535. package/standalone/.next/server/chunks/ssr/{_0922cgb._.js → _01uthe5._.js} +29 -22
  536. package/standalone/.next/server/chunks/ssr/{_0wzxel4._.js → _04pqmk5._.js} +29 -22
  537. package/standalone/.next/server/chunks/ssr/{_16qls8q._.js → _0qn0zlz._.js} +29 -22
  538. package/standalone/.next/server/chunks/ssr/messages_de_json_[json]_cjs_1uig1ud._.js +1 -1
  539. package/standalone/.next/server/chunks/ssr/messages_en_json_[json]_cjs_206072-._.js +1 -1
  540. package/standalone/.next/server/chunks/ssr/messages_es_json_[json]_cjs_082yukd._.js +1 -1
  541. package/standalone/.next/server/chunks/ssr/messages_fr_json_[json]_cjs_0j6-w0i._.js +1 -1
  542. package/standalone/.next/server/chunks/ssr/src_services_auth_index_ts_05c0kh-._.js +1 -1
  543. package/standalone/.next/server/middleware-build-manifest.js +3 -3
  544. package/standalone/.next/server/pages/404.html +1 -1
  545. package/standalone/.next/server/pages/500.html +1 -1
  546. package/standalone/.next/server/server-reference-manifest.js +1 -1
  547. package/standalone/.next/server/server-reference-manifest.json +1 -1
  548. package/standalone/.next/static/chunks/178wtl_ig0bxa.js +153 -0
  549. package/standalone/.next/static/chunks/21wyivb86q7ph.css +1 -0
  550. package/standalone/.next/server/chunks/[root-of-the-server]__04p8581._.js +0 -3
  551. package/standalone/.next/server/chunks/[root-of-the-server]__05jd11-._.js +0 -3
  552. package/standalone/.next/server/chunks/[root-of-the-server]__062_bno._.js +0 -3
  553. package/standalone/.next/server/chunks/[root-of-the-server]__06r_-xl._.js +0 -3
  554. package/standalone/.next/server/chunks/[root-of-the-server]__06vwuo3._.js +0 -3
  555. package/standalone/.next/server/chunks/[root-of-the-server]__07xpqyi._.js +0 -3
  556. package/standalone/.next/server/chunks/[root-of-the-server]__08wxa83._.js +0 -3
  557. package/standalone/.next/server/chunks/[root-of-the-server]__08ztaf_._.js +0 -3
  558. package/standalone/.next/server/chunks/[root-of-the-server]__0a4j1ds._.js +0 -3
  559. package/standalone/.next/server/chunks/[root-of-the-server]__0b3iuip._.js +0 -3
  560. package/standalone/.next/server/chunks/[root-of-the-server]__0b97vxr._.js +0 -3
  561. package/standalone/.next/server/chunks/[root-of-the-server]__0cdtdje._.js +0 -3
  562. package/standalone/.next/server/chunks/[root-of-the-server]__0cf34kz._.js +0 -3
  563. package/standalone/.next/server/chunks/[root-of-the-server]__0cxkc3c._.js +0 -3
  564. package/standalone/.next/server/chunks/[root-of-the-server]__0cxxmh3._.js +0 -3
  565. package/standalone/.next/server/chunks/[root-of-the-server]__0dcm3nf._.js +0 -3
  566. package/standalone/.next/server/chunks/[root-of-the-server]__0dilfdy._.js +0 -3
  567. package/standalone/.next/server/chunks/[root-of-the-server]__0dk5jt9._.js +0 -3
  568. package/standalone/.next/server/chunks/[root-of-the-server]__0dqc0rm._.js +0 -3
  569. package/standalone/.next/server/chunks/[root-of-the-server]__0e2s52m._.js +0 -3
  570. package/standalone/.next/server/chunks/[root-of-the-server]__0ezjalw._.js +0 -3
  571. package/standalone/.next/server/chunks/[root-of-the-server]__0fgzust._.js +0 -3
  572. package/standalone/.next/server/chunks/[root-of-the-server]__0k2q1d1._.js +0 -3
  573. package/standalone/.next/server/chunks/[root-of-the-server]__0kq6eoe._.js +0 -3
  574. package/standalone/.next/server/chunks/[root-of-the-server]__0mf6_9x._.js +0 -3
  575. package/standalone/.next/server/chunks/[root-of-the-server]__0mhjccg._.js +0 -3
  576. package/standalone/.next/server/chunks/[root-of-the-server]__0nixrwu._.js +0 -3
  577. package/standalone/.next/server/chunks/[root-of-the-server]__0o0xm1k._.js +0 -3
  578. package/standalone/.next/server/chunks/[root-of-the-server]__0ogs635._.js +0 -3
  579. package/standalone/.next/server/chunks/[root-of-the-server]__0oxto54._.js +0 -3
  580. package/standalone/.next/server/chunks/[root-of-the-server]__0p0bsa8._.js +0 -3
  581. package/standalone/.next/server/chunks/[root-of-the-server]__0peyklm._.js +0 -3
  582. package/standalone/.next/server/chunks/[root-of-the-server]__0q9to62._.js +0 -3
  583. package/standalone/.next/server/chunks/[root-of-the-server]__0qrt0w5._.js +0 -3
  584. package/standalone/.next/server/chunks/[root-of-the-server]__0r8dwbh._.js +0 -3
  585. package/standalone/.next/server/chunks/[root-of-the-server]__0rwzt-k._.js +0 -3
  586. package/standalone/.next/server/chunks/[root-of-the-server]__0t9oinq._.js +0 -3
  587. package/standalone/.next/server/chunks/[root-of-the-server]__0ulnqrl._.js +0 -3
  588. package/standalone/.next/server/chunks/[root-of-the-server]__0vghu8d._.js +0 -3
  589. package/standalone/.next/server/chunks/[root-of-the-server]__0vqv2zr._.js +0 -3
  590. package/standalone/.next/server/chunks/[root-of-the-server]__0vv_6ul._.js +0 -3
  591. package/standalone/.next/server/chunks/[root-of-the-server]__0xnclqh._.js +0 -3
  592. package/standalone/.next/server/chunks/[root-of-the-server]__0xzk664._.js +0 -3
  593. package/standalone/.next/server/chunks/[root-of-the-server]__0y_6jzi._.js +0 -3
  594. package/standalone/.next/server/chunks/[root-of-the-server]__0yjjcha._.js +0 -3
  595. package/standalone/.next/server/chunks/[root-of-the-server]__0z59tfa._.js +0 -3
  596. package/standalone/.next/server/chunks/[root-of-the-server]__1-0j27x._.js +0 -3
  597. package/standalone/.next/server/chunks/[root-of-the-server]__1-3u-vv._.js +0 -3
  598. package/standalone/.next/server/chunks/[root-of-the-server]__1-ag6yt._.js +0 -3
  599. package/standalone/.next/server/chunks/[root-of-the-server]__10cu5d3._.js +0 -3
  600. package/standalone/.next/server/chunks/[root-of-the-server]__11335q6._.js +0 -3
  601. package/standalone/.next/server/chunks/[root-of-the-server]__116p1rw._.js +0 -3
  602. package/standalone/.next/server/chunks/[root-of-the-server]__11yhge_._.js +0 -3
  603. package/standalone/.next/server/chunks/[root-of-the-server]__15h6xh0._.js +0 -3
  604. package/standalone/.next/server/chunks/[root-of-the-server]__16fqyzc._.js +0 -3
  605. package/standalone/.next/server/chunks/[root-of-the-server]__16h141k._.js +0 -3
  606. package/standalone/.next/server/chunks/[root-of-the-server]__16mnn4k._.js +0 -3
  607. package/standalone/.next/server/chunks/[root-of-the-server]__16mpo3a._.js +0 -3
  608. package/standalone/.next/server/chunks/[root-of-the-server]__16pv_6h._.js +0 -3
  609. package/standalone/.next/server/chunks/[root-of-the-server]__16ukpx-._.js +0 -3
  610. package/standalone/.next/server/chunks/[root-of-the-server]__17ekdtz._.js +0 -3
  611. package/standalone/.next/server/chunks/[root-of-the-server]__17jb4he._.js +0 -3
  612. package/standalone/.next/server/chunks/[root-of-the-server]__1895ivc._.js +0 -3
  613. package/standalone/.next/server/chunks/[root-of-the-server]__18o0ikj._.js +0 -3
  614. package/standalone/.next/server/chunks/[root-of-the-server]__196z3of._.js +0 -3
  615. package/standalone/.next/server/chunks/[root-of-the-server]__198nwkl._.js +0 -3
  616. package/standalone/.next/server/chunks/[root-of-the-server]__19e6vuq._.js +0 -3
  617. package/standalone/.next/server/chunks/[root-of-the-server]__1__3q-v._.js +0 -3
  618. package/standalone/.next/server/chunks/[root-of-the-server]__1abc-59._.js +0 -3
  619. package/standalone/.next/server/chunks/[root-of-the-server]__1b5a49d._.js +0 -3
  620. package/standalone/.next/server/chunks/[root-of-the-server]__1c-p2s8._.js +0 -3
  621. package/standalone/.next/server/chunks/[root-of-the-server]__1c3qnaz._.js +0 -3
  622. package/standalone/.next/server/chunks/[root-of-the-server]__1c8iukt._.js +0 -3
  623. package/standalone/.next/server/chunks/[root-of-the-server]__1cix51m._.js +0 -3
  624. package/standalone/.next/server/chunks/[root-of-the-server]__1d-klok._.js +0 -3
  625. package/standalone/.next/server/chunks/[root-of-the-server]__1dbbl79._.js +0 -3
  626. package/standalone/.next/server/chunks/[root-of-the-server]__1dnwm-k._.js +0 -3
  627. package/standalone/.next/server/chunks/[root-of-the-server]__1dxwek3._.js +0 -3
  628. package/standalone/.next/server/chunks/[root-of-the-server]__1e50aaz._.js +0 -3
  629. package/standalone/.next/server/chunks/[root-of-the-server]__1frlfm3._.js +0 -3
  630. package/standalone/.next/server/chunks/[root-of-the-server]__1g5_4f9._.js +0 -3
  631. package/standalone/.next/server/chunks/[root-of-the-server]__1g86_ue._.js +0 -3
  632. package/standalone/.next/server/chunks/[root-of-the-server]__1geww_b._.js +0 -3
  633. package/standalone/.next/server/chunks/[root-of-the-server]__1glg2tz._.js +0 -3
  634. package/standalone/.next/server/chunks/[root-of-the-server]__1gw6v6o._.js +0 -3
  635. package/standalone/.next/server/chunks/[root-of-the-server]__1hdtvl0._.js +0 -3
  636. package/standalone/.next/server/chunks/[root-of-the-server]__1hfal7_._.js +0 -3
  637. package/standalone/.next/server/chunks/[root-of-the-server]__1inimim._.js +0 -3
  638. package/standalone/.next/server/chunks/[root-of-the-server]__1k1bf2v._.js +0 -3
  639. package/standalone/.next/server/chunks/[root-of-the-server]__1kuazva._.js +0 -3
  640. package/standalone/.next/server/chunks/[root-of-the-server]__1lfohni._.js +0 -3
  641. package/standalone/.next/server/chunks/[root-of-the-server]__1m-netn._.js +0 -3
  642. package/standalone/.next/server/chunks/[root-of-the-server]__1moiz3h._.js +0 -3
  643. package/standalone/.next/server/chunks/[root-of-the-server]__1n8ng5_._.js +0 -3
  644. package/standalone/.next/server/chunks/[root-of-the-server]__1no55fg._.js +0 -3
  645. package/standalone/.next/server/chunks/[root-of-the-server]__1o_sbot._.js +0 -3
  646. package/standalone/.next/server/chunks/[root-of-the-server]__1odu2n8._.js +0 -3
  647. package/standalone/.next/server/chunks/[root-of-the-server]__1p15dyu._.js +0 -3
  648. package/standalone/.next/server/chunks/[root-of-the-server]__1pdleyb._.js +0 -3
  649. package/standalone/.next/server/chunks/[root-of-the-server]__1ps_qb8._.js +0 -3
  650. package/standalone/.next/server/chunks/[root-of-the-server]__1q2v-1q._.js +0 -3
  651. package/standalone/.next/server/chunks/[root-of-the-server]__1q7-v7k._.js +0 -3
  652. package/standalone/.next/server/chunks/[root-of-the-server]__1qc5z3r._.js +0 -3
  653. package/standalone/.next/server/chunks/[root-of-the-server]__1qp97bd._.js +0 -3
  654. package/standalone/.next/server/chunks/[root-of-the-server]__1sfakwk._.js +0 -3
  655. package/standalone/.next/server/chunks/[root-of-the-server]__1swibaz._.js +0 -3
  656. package/standalone/.next/server/chunks/[root-of-the-server]__1szcyzk._.js +0 -3
  657. package/standalone/.next/server/chunks/[root-of-the-server]__1t7_imx._.js +0 -3
  658. package/standalone/.next/server/chunks/[root-of-the-server]__1u8jx07._.js +0 -3
  659. package/standalone/.next/server/chunks/[root-of-the-server]__1ucwigt._.js +0 -3
  660. package/standalone/.next/server/chunks/[root-of-the-server]__1udnxa1._.js +0 -3
  661. package/standalone/.next/server/chunks/[root-of-the-server]__1ugepal._.js +0 -3
  662. package/standalone/.next/server/chunks/[root-of-the-server]__1upx00h._.js +0 -3
  663. package/standalone/.next/server/chunks/[root-of-the-server]__1wo0s5w._.js +0 -3
  664. package/standalone/.next/server/chunks/[root-of-the-server]__1wznu0j._.js +0 -3
  665. package/standalone/.next/server/chunks/[root-of-the-server]__1xg-wjp._.js +0 -3
  666. package/standalone/.next/server/chunks/[root-of-the-server]__1xgjawn._.js +0 -3
  667. package/standalone/.next/server/chunks/[root-of-the-server]__1xo35gr._.js +0 -3
  668. package/standalone/.next/server/chunks/[root-of-the-server]__1xunj2b._.js +0 -3
  669. package/standalone/.next/server/chunks/[root-of-the-server]__1y_c0qs._.js +0 -3
  670. package/standalone/.next/server/chunks/[root-of-the-server]__1ypncrq._.js +0 -3
  671. package/standalone/.next/server/chunks/[root-of-the-server]__1yv-lzg._.js +0 -3
  672. package/standalone/.next/server/chunks/[root-of-the-server]__20_nqsg._.js +0 -3
  673. package/standalone/.next/static/chunks/08tqkboq7jldl.css +0 -1
  674. package/standalone/.next/static/chunks/2llenynsmogfu.js +0 -146
  675. /package/standalone/.next/static/{I0dfaEEIvfubol4R1MwUX → xkUaHnpvpggDLECvJ6z6y}/_buildManifest.js +0 -0
  676. /package/standalone/.next/static/{I0dfaEEIvfubol4R1MwUX → xkUaHnpvpggDLECvJ6z6y}/_clientMiddlewareManifest.js +0 -0
  677. /package/standalone/.next/static/{I0dfaEEIvfubol4R1MwUX → xkUaHnpvpggDLECvJ6z6y}/_ssgManifest.js +0 -0
@@ -993,7 +993,7 @@ To resolve this, you can:
993
993
  1. Use only one of the conflicting plugins
994
994
  2. Configure the plugins to use different paths (if supported)
995
995
  3. Ensure plugins use different HTTP methods for the same path
996
- `)}}(A={...A,secret:r,baseURL:u?A.baseURL:c?new URL(c).origin:"",basePath:A.basePath||"/api/auth",plugins:s.concat(l)},d);let w=A.advanced?.ipAddress?.trustedProxies;if(w&&w.length>0){let e=w.filter(e=>null===Q(e));e.length>0&&d.warn(`Ignoring invalid \`advanced.ipAddress.trustedProxies\` entries: ${e.join(", ")}. Each entry must be an IP address or CIDR range.`)}let m=(0,An.getCookies)(A),E=(0,eT.getAuthTables)(A),y=(await Promise.all(Object.entries(A.socialProviders||{}).map(async([e,A])=>{let t="function"==typeof A?await A():A;if(null==t||!1===t.enabled)return null;t.clientId||d.warn(`Social provider ${e} is missing clientId or clientSecret`);let r=iD[e](t);return r.disableImplicitSignUp=t.disableImplicitSignUp,r}))).filter(e=>null!==e),B=({model:e,size:t})=>{if("function"==typeof A.advanced?.generateId)return A.advanced.generateId({model:e,size:t});let r=A?.advanced?.database?.generateId;return"function"==typeof r?r({model:e,size:t}):"uuid"===r?crypto.randomUUID():"serial"!==r&&!1!==r&&(0,N.generateId)(t)},{publish:D}=await nO(A,{adapter:e.id,database:"function"==typeof A.database?"adapter":t(A.database)}),b=new Set(A.plugins.map(e=>e.id)),S=await AM(A),k=await AU(A),v={appName:A.appName||"Better Auth",baseURL:c||"",version:(0,nc.getBetterAuthVersion)(),socialProviders:y,options:A,oauthConfig:{storeStateStrategy:A.account?.storeStateStrategy||(o?"database":"cookie"),skipStateCookieCheck:!!A.account?.skipStateCookieCheck},tables:E,trustedOrigins:S,trustedProviders:k,isTrustedOrigin(e,A){return this.trustedOrigins.some(t=>e5(e,t,A))},sessionConfig:{updateAge:A.session?.updateAge!==void 0?A.session.updateAge:86400,expiresIn:A.session?.expiresIn||604800,freshAge:A.session?.freshAge===void 0?86400:A.session.freshAge,cookieRefreshCache:(n=A.session?.cookieCache?.refreshCache,a=A.session?.cookieCache?.maxAge||300,o&&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:{...A.rateLimit,enabled:A.rateLimit?.enabled??p.isProduction,window:A.rateLimit?.window||10,max:A.rateLimit?.max||100,storage:A.rateLimit?.storage||(A.secondaryStorage?"secondary-storage":"memory")},authCookies:m,logger:d,generateId:B,session:null,secondaryStorage:A.secondaryStorage,password:{hash:A.emailAndPassword?.password?.hash||At,verify:A.emailAndPassword?.password?.verify||Ai,config:{minPasswordLength:A.emailAndPassword?.minPasswordLength||8,maxPasswordLength:A.emailAndPassword?.maxPasswordLength||128},checkPassword:AL},setNewSession(e){this.newSession=e},newSession:null,adapter:e,internalAdapter:Ay(e,{options:A,logger:d,hooks:A.databaseHooks?[{source:"user",hooks:A.databaseHooks}]:[],generateId:B}),createAuthCookie:(0,An.createCookieGetter)(A),async runMigrations(){throw new R.BetterAuthError("runMigrations will be set by the specific init implementation")},publishTelemetry:D,skipCSRFCheck:!!A.advanced?.disableCSRFCheck,skipOriginCheck:A.advanced?.disableOriginCheck!==void 0?A.advanced.disableOriginCheck:!!(0,p.isTest)(),runInBackground:A.advanced?.backgroundTasks?.handler??(e=>{e.catch(()=>{})}),async runInBackgroundOrAwait(e){try{A.advanced?.backgroundTasks?.handler?e instanceof Promise&&A.advanced.backgroundTasks.handler(e.catch(e=>{d.error("Failed to run background task:",e)})):await e}catch(e){d.error("Failed to run background task:",e)}},getPlugin:e=>A.plugins.find(A=>A.id===e)??null,hasPlugin:e=>b.has(e)},G=AT(v);return(0,e7.isPromise)(G)&&await G,v}let nU=async e=>{let A=await eO(e),t=await nH(A,e,e=>(0,eU.getKyselyDatabaseType)(e)||"unknown");return t.runMigrations=async function(){if(!e.database||"updateMany"in e.database)throw new R.BetterAuthError("Database is not provided or it's an adapter. Migrations are only supported with a database instance.");let{runMigrations:A}=await e0(e);await A()},t};var n_=e.i(779198),nx=e.i(595544);let nL=()=>n??=e.A(162916).catch(e=>{throw n=void 0,e}),nP=(0,_.createAccessControl)({user:["create","list","set-role","ban","impersonate","impersonate-admins","delete","set-password","set-email","get","update"],session:["list","revoke","delete"]}),nq={admin:nP.newRole({user:["create","list","set-role","ban","impersonate","delete","set-password","set-email","get","update"],session:["list","revoke","delete"]}),user:nP.newRole({user:[],session:[]})},nK=(0,c.defineErrorCodes)({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",PASSWORD_CANNOT_BE_UPDATED_VIA_UPDATE_USER:"Password cannot be updated through update-user. Use the set-user-password endpoint instead"}),nJ=async e=>{let A=e.context.returned;return A?A instanceof Response?200!==A.status?null:await A.clone().json():(0,AP.isAPIError)(A)?null:A:null},nF=e=>{if(e.userId&&e.options?.adminUserIds?.includes(e.userId))return!0;if(!e.permissions)return!1;let A=(e.role||e.options?.defaultRole||"user").split(","),t=e.options?.roles||nq;for(let r of A)if(t[r]?.authorize(e.permissions)?.success)return!0;return!1};var nj=e.i(752067);let nz=(0,g.createAuthMiddleware)(async e=>{let A=await (0,v.getAuthoritativeSessionFromCtx)(e);if(!A)throw R.APIError.fromStatus("UNAUTHORIZED");return{session:A}});function nY(e){return Array.isArray(e)?e.join(","):e}let nZ=C.object({userId:H.coerce.string().meta({description:"The user id"}),role:C.union([C.string().meta({description:"The role to set. `admin` or `user` by default"}),C.array(C.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]`"})}),nV=C.object({id:C.string().meta({description:"The id of the User"})}),nW=C.object({email:C.string().meta({description:"The email of the user"}),password:C.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:C.string().meta({description:"The name of the user"}),role:C.union([C.string().meta({description:"The role of the user"}),C.array(C.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:C.record(C.string(),C.any()).optional().meta({description:"Extra fields for the user. Including custom additional fields."})}),n$=C.object({userId:H.coerce.string().meta({description:"The user id"}),data:C.record(C.any(),C.any()).meta({description:"The user data to update"})}),nX=C.object({searchValue:C.string().optional().meta({description:'The value to search for. Eg: "some name"'}),searchField:C.enum(["email","name"]).meta({description:'The field to search in, defaults to email. Can be `email` or `name`. Eg: "name"'}).optional(),searchOperator:C.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:C.string().meta({description:"The number of users to return"}).or(C.number()).optional(),offset:C.string().meta({description:"The offset to start from"}).or(C.number()).optional(),sortBy:C.string().meta({description:"The field to sort by"}).optional(),sortDirection:C.enum(["asc","desc"]).meta({description:"The direction to sort by"}).optional(),filterField:C.string().meta({description:"The field to filter by"}).optional(),filterValue:C.string().meta({description:"The value to filter by"}).or(C.number()).or(C.boolean()).or(C.array(C.string())).or(C.array(C.number())).optional(),filterOperator:C.enum(nj.whereOperators).meta({description:"The operator to use for the filter"}).optional()}),n0=C.object({userId:H.coerce.string().meta({description:"The user id"})}),n1=C.object({userId:H.coerce.string().meta({description:"The user id"})}),n8=C.object({userId:H.coerce.string().meta({description:"The user id"}),banReason:C.string().meta({description:"The reason for the ban"}).optional(),banExpiresIn:C.number().meta({description:"The number of seconds until the ban expires"}).optional()}),n4=C.object({userId:H.coerce.string().meta({description:"The user id"})}),n2=C.object({sessionToken:C.string().meta({description:"The session token"})}),n6=C.object({userId:H.coerce.string().meta({description:"The user id"})}),n3=C.object({userId:H.coerce.string().meta({description:"The user id"})}),n5=C.object({newPassword:C.string().nonempty("newPassword cannot be empty").meta({description:"The new password"}),userId:H.coerce.string().nonempty("userId cannot be empty").meta({description:"The user id"})}),n9=C.object({userId:H.coerce.string().optional().meta({description:'The user id. Eg: "user-id"'}),role:C.string().optional().meta({description:'The role to check permission for. Eg: "admin"'})}).and(C.xor([C.object({permission:C.record(C.string(),C.array(C.string()))}),C.object({permissions:C.record(C.string(),C.array(C.string()))})])),n7={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 ae=e.i(259968),aA=e.i(976394);function at(e){try{return decodeURIComponent(e)}catch{return e}}let ar=(0,c.defineErrorCodes)({INVALID_OAUTH_CONFIGURATION:"Invalid OAuth configuration",TOKEN_URL_NOT_FOUND:"Invalid OAuth configuration. Token URL not found."});async function ai(e,A){let t=await rJ(e,{method:"GET",headers:A});if(t.error||!t.data)return null;if(t.data.issuer)try{new URL(t.data.issuer)}catch{return null}return t.data}async function an(e,A){if(e.idToken)try{let A=ic(e.idToken);if(A?.sub&&A?.email)return{id:A.sub,emailVerified:A.email_verified,image:A.picture,...A}}catch{}if(!A)return null;let t=await rJ(A,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});return t.error||!t.data?null:{...t.data,email:t.data.email,emailVerified:t.data.email_verified??!1,image:t.data.picture,name:t.data.name}}let aa=async e=>{let A=await (0,k.createHash)("SHA-256").digest(new TextEncoder().encode(e));return S.base64Url.encode(new Uint8Array(A),{padding:!1})},ao=C.object({token:C.string().meta({description:'The token to verify. Eg: "some-token"'})});var as=e.i(270133),al=e.i(135475),ad=e.i(768843);function au(e,A){return e[A]?.trim()||void 0}function ac(e,A){let t=au(e,A);if(!t)throw Error(`${A} is required for AUTH_MODE.`);return t}function ah(e=process.env){let A=function(e){let A=au(e,"AUTH_MODE")??"password";if("password"!==A&&"oidc"!==A&&"both"!==A)throw Error('AUTH_MODE must be "password", "oidc", or "both".');return A}(e),t=(0,as.resolveAppOrigins)(e);return{secret:(0,ad.getAppSecrets)(e).authSecret,origins:t,baseURL:t.canonical,trustProxyHeaders:function(e){let A=au(e,"TRUST_PROXY_HEADERS")?.toLowerCase();if(!A||"false"===A||"0"===A)return!1;if("true"===A||"1"===A)return!0;throw Error("TRUST_PROXY_HEADERS must be true, false, 1, or 0.")}(e),mode:A,provider:function(e,A){if("password"===A)return null;let t=au(e,"AUTH_OAUTH_DISCOVERY_URL"),r=au(e,"AUTH_OAUTH_AUTHORIZATION_URL"),i=au(e,"AUTH_OAUTH_TOKEN_URL"),n=au(e,"AUTH_OAUTH_USER_INFO_URL"),a=au(e,"AUTH_OAUTH_ISSUER"),o=!!(r||i||n),s=r&&i&&n;if(t&&o)throw Error("OIDC configuration must use either discovery or explicit endpoints, not both.");if(!t&&!s)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(o&&!s)throw Error("Explicit OAuth configuration must include authorization, token, and user-info URLs.");if(s&&!a)throw Error("AUTH_OAUTH_ISSUER is required with explicit OAuth endpoints.");let l=ac(e,"AUTH_OAUTH_SCOPES").split(",").map(e=>e.trim()).filter(Boolean);if(0===l.length)throw Error("AUTH_OAUTH_SCOPES must contain at least one scope.");return{providerId:ac(e,"AUTH_OAUTH_PROVIDER_ID"),displayName:ac(e,"AUTH_OAUTH_PROVIDER_NAME"),clientId:ac(e,"AUTH_OAUTH_CLIENT_ID"),clientSecret:ac(e,"AUTH_OAUTH_CLIENT_SECRET"),scopes:l,requireIssuerValidation:function(e){let A=au(e,"AUTH_OAUTH_REQUIRE_ISSUER_VALIDATION")?.toLowerCase();if(!A||"false"===A||"0"===A)return!1;if("true"===A||"1"===A)return!0;throw Error("AUTH_OAUTH_REQUIRE_ISSUER_VALIDATION must be true, false, 1, or 0.")}(e),discoveryUrl:t,issuer:a,authorizationUrl:r,tokenUrl:i,userInfoUrl:n}}(e,A)}}function ag(e){return"password"===e||"both"===e}function ap(e){return"oidc"===e||"both"===e}e.s(["getAuthRuntimeConfig",0,ah,"oauthAuthenticationEnabled",0,ap,"passwordAuthenticationEnabled",0,ag],658978);var aC=e.i(812057);let af=RegExp(String.raw`((?:"?(?:authorization|password|accessToken|refreshToken|idToken|sessionToken|clientSecret|secret|privateKey)"?)\s*:\s*)(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^,\n}\]]+)`,"gi");function aI(e){return e.replace(af,'$1"[REDACTED]"')}function aw(e,A,...t){let r=[`${new Date().toISOString()} ${e.toUpperCase()} [Better Auth]: ${A}`,...t.map(e=>"string"==typeof e?e:(0,aC.inspect)(e,{depth:6,breakLength:120}))].map(aI);"error"===e?console.error(...r):"warn"===e?console.warn(...r):console.log(...r)}let am="default";async function aE(){let e=await (0,al.getPrismaClient)();return await e.authSettings.findUnique({where:{id:am}})??await e.authSettings.upsert({where:{id:am},create:{id:am},update:{}})}async function ay({allowWhenRegistrationClosed:e=!1}={}){let A=await (0,al.getPrismaClient)(),t=await aE();if(t.bootstrapCompleted){if(!t.registrationEnabled&&!e)throw new R.APIError("FORBIDDEN",{message:"Account registration is disabled."});return}if(await A.user.count()>0){if(await A.authSettings.update({where:{id:am},data:{bootstrapCompleted:!0,registrationEnabled:!1,bootstrapClaimId:null,bootstrapClaimedAt:null}}),e)return;throw new R.APIError("FORBIDDEN",{message:"Account registration is disabled."})}let r=new Date(Date.now()-18e4),i=(0,Ae.randomUUID)();if(1!==(await A.authSettings.updateMany({where:{id:am,bootstrapCompleted:!1,OR:[{bootstrapClaimedAt:null},{bootstrapClaimedAt:{lt:r}}]},data:{bootstrapClaimId:i,bootstrapClaimedAt:new Date}})).count)throw new R.APIError("CONFLICT",{message:"The initial account is already being created. Try again shortly."})}async function aB(){let e=await (0,al.getPrismaClient)();await e.authSettings.updateMany({where:{id:am,bootstrapCompleted:!1},data:{bootstrapCompleted:!0,registrationEnabled:!1,bootstrapClaimId:null,bootstrapClaimedAt:null}})}let aQ={user:{create:{before:async(e,A)=>(await ay({allowWhenRegistrationClosed:A?.path?.includes("/admin/create-user")??!1}),{data:{...e,role:"user",banned:!1,banReason:null,banExpires:null}}),after:async()=>{await aB()}},update:{before:async e=>({data:{...e,role:"user",banned:!1,banReason:null,banExpires:null}})},delete:{before:async()=>{throw new R.APIError("BAD_REQUEST",{message:"Accounts must be deleted through the management API."})}}}};e.s(["authDatabaseHooks",0,aQ],525796);let aD={user:["create","list","set-password","set-email","get","update"],session:["list","revoke","delete"]},ab=(0,_.createAccessControl)(aD),aS=ab.newRole(aD),ak=null;function aR(){return ak||(ak=(0,al.getPrismaClient)().then(e=>(function(e,A=ah()){var t;let r,i,n,a,o,s=ap(A.mode)&&A.provider?(e=>{let A=new Set,t=new Set;for(let r of e.config){let e=r.providerId;A.has(e)&&t.add(e),A.add(e)}return t.size>0&&console.warn(`Duplicate provider IDs found: ${Array.from(t).join(", ")}`),{id:"generic-oauth",version:nx.PACKAGE_VERSION,init:async A=>{let t=[];for(let r of e.config){let e,i,n=r.authorizationUrl,a=r.tokenUrl,o=r.userInfoUrl,s=r.endSessionEndpoint,l=!1;if(r.discoveryUrl){let t=await ai(r.discoveryUrl,r.discoveryHeaders).catch(e=>(A.logger.error(`Discovery fetch failed for "${r.providerId}": ${e}`),null));if(t){if(!t.issuer&&!r.accountIssuer)throw Error(`Provider "${r.providerId}": discovery did not return an issuer. Configure accountIssuer explicitly to establish a stable account namespace.`);n??=t.authorization_endpoint,a??=t.token_endpoint,o??=t.userinfo_endpoint,s??=t.end_session_endpoint,e=t.issuer;let A=t.id_token_signing_alg_values_supported;if(l=Array.isArray(A)&&A.length>0,t.jwks_uri&&t.issuer){let e;try{e=new URL(t.jwks_uri,r.discoveryUrl)}catch{throw Error(`Provider "${r.providerId}": invalid jwks_uri "${t.jwks_uri}" in discovery document.`)}i={jwks:io(e),issuer:t.issuer,audience:r.clientId,algorithms:l?A:void 0}}}else if(r.accountIssuer)n&&a||A.logger.error(`Provider "${r.providerId}": discovery returned no data and no explicit endpoints configured. OAuth sign-in will fail for this provider.`);else throw Error(`Provider "${r.providerId}": discovery returned no valid data. Provider initialization stopped to keep its account issuer stable.`)}if(r.requireIdTokenVerification&&!i)throw Error(`Provider "${r.providerId}": requires verified ID tokens, but discovery did not provide a usable issuer and jwks_uri.`);let d=r.tokenEndpointAuth;if(r.clientSecret&&(d?.method==="private_key_jwt"||d?.method==="none"))throw Error(`Provider "${r.providerId}": tokenEndpointAuth.method "${d?.method}" cannot be combined with clientSecret`);if(!r.clientSecret&&(d?.method==="client_secret_basic"||d?.method==="client_secret_post"))throw Error(`Provider "${r.providerId}": tokenEndpointAuth.method "${d?.method}" requires clientSecret`);if(!r.clientSecret&&!d&&"basic"===r.authentication)throw Error(`Provider "${r.providerId}": authentication "basic" requires clientSecret`);let u=r.accountSubject,c=r.accountIssuer,h={id:r.providerId,name:r.name??r.providerId,issuer:e,accountSubject:({tokens:e,profile:A})=>u?u({tokens:e,profile:A}):l?A.sub??"":A.id??"",accountIssuer:"function"==typeof c?({tokens:e,profile:A})=>c({tokens:e,profile:A}):c??e,idToken:i,requiresIdTokenNonce:void 0!==i&&!0!==r.disableIdTokenNonceBinding,allowIdpInitiated:r.allowIdpInitiated,async createEndSessionURL(e){let t;if(r.disableProviderLogout||!s)return null;try{t=new URL(s)}catch{return null}e.idToken&&t.searchParams.set("id_token_hint",e.idToken);let i=e.postLogoutRedirectURI??r.postLogoutRedirectURI,n=i?new URL(i,A.baseURL).toString():void 0;return n?(t.searchParams.set("post_logout_redirect_uri",n),t.searchParams.set("client_id",r.clientId),e.state&&t.searchParams.set("state",e.state)):e.idToken||t.searchParams.set("client_id",r.clientId),t},createAuthorizationURL(e){if(!n)throw R.APIError.from("BAD_REQUEST",ar.INVALID_OAUTH_CONFIGURATION);return rC({id:r.providerId,options:{clientId:r.clientId,clientSecret:r.clientSecret,redirectURI:r.redirectURI},authorizationEndpoint:n,state:e.state,codeVerifier:r.pkce??!0?e.codeVerifier:void 0,scopes:(()=>{let A=[...e.scopes??[],...r.scopes??[]];return l&&!A.includes("openid")&&A.unshift("openid"),A})(),redirectURI:e.redirectURI,prompt:r.prompt,accessType:r.accessType,responseType:r.responseType,responseMode:r.responseMode,nonce:e.idTokenNonce,additionalParams:{...r.authorizationUrlParams??{},...e.additionalParams??{}},loginHint:e.loginHint})},async validateAuthorizationCode(e){if(r.getToken)return ru(await r.getToken(e),r.accessTokenExpiresIn);if(!a)throw R.APIError.from("BAD_REQUEST",ar.TOKEN_URL_NOT_FOUND);return ru(await il({headers:r.authorizationHeaders,code:e.code,codeVerifier:r.pkce??!0?e.codeVerifier:void 0,redirectURI:e.redirectURI,options:{clientId:r.clientId,clientSecret:r.clientSecret,redirectURI:r.redirectURI},tokenEndpoint:a,authentication:r.authentication,tokenEndpointAuth:d,additionalParams:r.tokenUrlParams}),r.accessTokenExpiresIn)},async getUserInfo(e){let{expectedIdTokenNonce:t,...i}=e;if(i.idToken&&h.idToken&&!await ry(h,i.idToken,t))return A.logger.error(`Provider "${r.providerId}": id_token failed verification against the discovery JWKS or expected nonce`),null;let n=r.getUserInfo?await r.getUserInfo(i):await an(i,o);if(!n)return null;let a=r.mapProfileToUser?await r.mapProfileToUser(n):{},s={email:n.email,emailVerified:n.emailVerified,image:n.image,name:n.name,...a};return{user:{...s,image:s.image??void 0},data:n}},async refreshAccessToken(e,A){if(!a)throw R.APIError.from("BAD_REQUEST",ar.TOKEN_URL_NOT_FOUND);let t="function"==typeof r.refreshTokenParams?await r.refreshTokenParams(A):r.refreshTokenParams;return ru(await r6({refreshToken:e,options:{clientId:r.clientId,clientSecret:r.clientSecret},authentication:r.authentication,tokenEndpointAuth:d,tokenEndpoint:a,extraParams:t}),r.accessTokenExpiresIn)},disableImplicitSignUp:r.disableImplicitSignUp,disableSignUp:r.disableSignUp,options:{disableSignUp:r.disableSignUp,overrideUserInfoOnSignIn:r.overrideUserInfo,requireEmailVerification:r.requireEmailVerification}};t.push(h)}let r=new Set(A.socialProviders.map(e=>e.id));for(let e of t)r.has(e.id)&&A.logger.warn(`Generic OAuth provider "${e.id}" shadows a built-in social provider with the same ID`);return{context:{socialProviders:t.concat(A.socialProviders)}}},options:e,$ERROR_CODES:ar}})({config:[{providerId:A.provider.providerId,clientId:A.provider.clientId,clientSecret:A.provider.clientSecret,scopes:A.provider.scopes,discoveryUrl:A.provider.discoveryUrl,accountIssuer:`local:oauth:${A.provider.providerId}`,authorizationUrl:A.provider.authorizationUrl,tokenUrl:A.provider.tokenUrl,userInfoUrl:A.provider.userInfoUrl,pkce:!0,requireIdTokenVerification:A.provider.requireIssuerValidation,disableImplicitSignUp:!1}]}):null;return((e,A)=>{let t=A(e),{api:r}=nu(t,e),i=e.plugins?.reduce((e,A)=>A.$ERROR_CODES?{...e,...A.$ERROR_CODES}:e,{}),n=async A=>{let r,i=await t,n=i.options.basePath||"/api/auth";if((0,e1.isDynamicBaseURLConfig)(e.baseURL))r=await AO(i,A,AN(i.options));else{r=Object.create(Object.getPrototypeOf(i),Object.getOwnPropertyDescriptors(i));let e=i.options;if(!i.options.baseURL){let t=(0,e1.getBaseURL)(void 0,n,A,void 0,i.options.advanced?.trustedProxyHeaders);if(!t)throw new R.BetterAuthError("Could not get base URL from request. Please provide a valid base URL.");r.baseURL=t,r.options={...i.options,baseURL:(0,e1.getOrigin)(t)||void 0},e=r.options}r.trustedOrigins=await AM(e,A),r.trustedProviders=await AU(e,A)}let{handler:a}=((e,A)=>{let{api:t,middlewares:r}=nu(e,A),i=new URL(e.baseURL).pathname;return(0,nd.createRouter)(t,{routerContext:e,openapi:{disabled:!0},basePath:i,routerMiddleware:[{path:"/**",middleware:AY},...r],allowedMediaTypes:["application/json"],skipTrailingSlashes:A.advanced?.skipTrailingSlashes??!1,async onRequest(A){let t=e.options.disabledPaths||[],r=Aq(A.url,i);if(t.includes(r))return new Response("Not Found",{status:404});let n=A,a=await A4(n,e);if(a)return a;for(let A of e.options.plugins||[])if(A.onRequest){let t=await (0,AI.withSpan)(`onRequest ${A.id}`,{[AC]:"onRequest",[Af]:`plugin:${A.id}`},()=>A.onRequest(n,e));if(t&&"response"in t)return t.response;t&&"request"in t&&(n=t.request)}return n},async onResponse(A,t){for(let t of e.options.plugins||[])if(t.onResponse){let r=await (0,AI.withSpan)(`onResponse ${t.id}`,{[AC]:"onResponse",[Af]:`plugin:${t.id}`,[Ag.ATTR_HTTP_RESPONSE_STATUS_CODE]:A.status},()=>t.onResponse(A,e));if(r)return r.response}return A},onError(t){if((0,AP.isAPIError)(t)&&"FOUND"===t.status)return;if(A.onAPIError?.throw)throw t;if(A.onAPIError?.onError)return void A.onAPIError.onError(t,e);let r=A.logger?.level,i="error"===r||"warn"===r||"debug"===r?eM.logger:void 0;if(A.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 e.logger?.error(t.message);(0,AP.isAPIError)(t)?("INTERNAL_SERVER_ERROR"===t.status&&e.logger.error(t.status,t),i?.error(t.message)):e.logger?.error(t&&"object"==typeof t&&"name"in t?t.name:"",t)}}})})(r,e);return(0,Ac.runWithAdapter)(r.adapter,()=>a(A))};return{handler:n,fetch:n,api:r,options:e,$context:t,$ERROR_CODES:{...i,...A_.BASE_ERROR_CODES}}})({appName:"AI Development Environment",baseURL:(0,as.betterAuthBaseURL)(A.origins),trustedOrigins:e=>{if(!e)return[];let t=(0,as.originFromRequest)(e,A.trustProxyHeaders);return t&&(0,as.isTrustedOrigin)(A.origins,t)?[t]:[]},secret:A.secret,logger:{log:aw},advanced:{trustedProxyHeaders:A.trustProxyHeaders},database:(t={provider:"sqlite"},r=null,i=(e,A=!1)=>({getFieldName:r,getModelName:i,getFieldAttributes:n,getDefaultModelName:a,schema:o})=>{let s=(e,A,t)=>{if(!e&&!t)return;let n={};if(e)for(let t of e)n[r({model:A,field:t})]=!0;if(t){if(!e){let e=o[a(A)]?.fields||{};for(let t of(e.id={type:"string"},Object.keys(e)))n[r({model:A,field:t})]=!0}for(let[e,r]of Object.entries(t)){let t=l(A,i(e),o);"one-to-one"===r.relation?n[t]=!0:n[t]={take:r.limit}}}return n},l=(e,A,r)=>{try{let n=a(e),o=a(A),s=i(A).toLowerCase(),l=Object.entries(r[o]?.fields||{}).filter(([e,A])=>A.references&&a(A.references.model)===n);if(l.length>0){let[e,A]=l[0];return A?.unique===!0||!0===t.usePlural?s:`${s}s`}if((l=Object.entries(r[n]?.fields||{}).filter(([e,A])=>A.references&&a(A.references.model)===o)).length>0)return s}catch{}return`${i(A).toLowerCase()}s`};function d(e){switch(e){case"starts_with":return"startsWith";case"ends_with":return"endsWith";case"ne":return"not";case"not_in":return"notIn";default:return e}}let u=({action:e,model:A,where:i})=>{if(!i||!i.length)return{};let a=e=>{let i=r({model:A,field:e.field}),a=(e.mode??"sensitive")==="insensitive"&&("string"==typeof e.value||Array.isArray(e.value)&&e.value.every(e=>"string"==typeof e)),o="postgresql"===t.provider||"mongodb"===t.provider,s=a&&o?"insensitive":void 0,l=s?{mode:s}:{};if("ne"===e.operator&&null===e.value)return n({model:A,field:e.field})?.required!==!0?{[i]:{not:null}}:{};if(("in"===e.operator||"not_in"===e.operator)&&Array.isArray(e.value)){let A=e.value.filter(e=>null!=e);if(0===A.length)if("in"===e.operator)return{AND:[{[i]:{equals:"__never__"}},{[i]:{not:"__never__"}}]};else return{};return{[i]:{[d(e.operator)]:A,...l}}}return"eq"!==e.operator&&e.operator?"ne"===e.operator?{[i]:{not:{equals:e.value},...l}}:{[i]:{[d(e.operator)]:e.value,...l}}:{[i]:{equals:e.value,...l}}};if("update"===e){let e=i.filter(e=>"AND"===e.connector||!e.connector),t=i.filter(e=>"OR"===e.connector),n=e.filter(e=>"eq"===e.operator||!e.operator),o=e.filter(e=>"eq"!==e.operator&&void 0!==e.operator).map(e=>a(e)),s=t.map(e=>a(e)),l={};for(let e of n)l[r({model:A,field:e.field})]=e.value;return o.length>0&&(l.AND=o),s.length>0&&(l.OR=s),l}if("delete"===e){let e=i.find(e=>"id"===e.field);if(e){let t=r({model:A,field:"id"}),n=i.filter(e=>"id"!==e.field);if(0===n.length)return{[t]:e.value};let o=n.filter(e=>"AND"===e.connector||!e.connector),s=n.filter(e=>"OR"===e.connector),l=o.map(e=>a(e)),d=s.map(e=>a(e)),u={[t]:e.value};return l.length>0&&(u.AND=l),d.length>0&&(u.OR=d),u}}if(1===i.length){let e=i[0];if(!e)return;return a(e)}let o=i.filter(e=>"AND"===e.connector||!e.connector),s=i.filter(e=>"OR"===e.connector),l=o.map(e=>a(e)),u=s.map(e=>a(e));return{...l.length?{AND:l}:{},...u.length?{OR:u}:{}}};return{async create({model:A,data:t,select:r}){if(!e[A])throw new R.BetterAuthError(`Model ${A} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);return await e[A].create({data:t,select:s(r,A)})},async findOne({model:A,where:t,select:r,join:n}){let a=u({model:A,where:t,action:"findOne"});if(!e[A])throw new R.BetterAuthError(`Model ${A} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let d=new Map;for(let e of Object.keys(n??{})){let t=l(A,e,o);d.set(t,i(e))}let c=s(r,A,n),h=await e[A].findFirst({where:a,select:c});if(n&&h)for(let[e,A]of d.entries())e!==A&&e in h&&(h[A]=h[e],delete h[e]);return h},async findMany({model:A,where:t,limit:n,select:a,offset:d,sortBy:c,join:h}){let g=u({model:A,where:t,action:"findMany"});if(!e[A])throw new R.BetterAuthError(`Model ${A} 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[e,t]of Object.entries(h)){let t=l(A,e,o);p.set(t,i(e))}let C=s(a,A,h),f=await e[A].findMany({where:g,take:n||100,skip:d||0,...c?.field?{orderBy:{[r({model:A,field:c.field})]:"desc"===c.direction?"desc":"asc"}}:{},select:C});if(h&&Array.isArray(f))for(let e of f)for(let[A,t]of p.entries())A!==t&&A in e&&(e[t]=e[A],delete e[A]);return f},async count({model:A,where:t}){let r=u({model:A,where:t,action:"count"});if(!e[A])throw new R.BetterAuthError(`Model ${A} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);return await e[A].count({where:r})},async update({model:A,where:r,update:i}){if(!e[A])throw new R.BetterAuthError(`Model ${A} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);if(!(r?.length&&r.some(e=>{if("OR"===e.connector||e.operator&&"eq"!==e.operator)return!1;if("insensitive"===e.mode){let A="postgresql"===t.provider||"mongodb"===t.provider,r="string"==typeof e.value||Array.isArray(e.value)&&e.value.every(e=>"string"==typeof e);if(A&&r)return!1}return"id"===e.field||n({model:A,field:e.field})?.unique===!0}))){let t=u({model:A,where:r,action:"updateMany"});return(await e[A].updateMany({where:t,data:i}))?.count?await e[A].findFirst({where:t}):null}let a=u({model:A,where:r,action:"update"});try{return await e[A].update({where:a,data:i})}catch(e){if(eG(e))return null;throw e}},async updateMany({model:A,where:t,update:r}){if(!e[A])throw new R.BetterAuthError(`Model ${A} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let i=u({model:A,where:t,action:"updateMany"}),n=await e[A].updateMany({where:i,data:r});return n?n.count:0},async delete({model:A,where:t}){if(!e[A])throw new R.BetterAuthError(`Model ${A} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);if(!t?.some(e=>"id"===e.field)){let r=u({model:A,where:t,action:"deleteMany"});await e[A].deleteMany({where:r});return}let r=u({model:A,where:t,action:"delete"});try{await e[A].delete({where:r})}catch(e){if(eG(e))return;throw e}},async deleteMany({model:A,where:t}){let r=u({model:A,where:t,action:"deleteMany"}),i=await e[A].deleteMany({where:r});return i?i.count:0},async consumeOne({model:t,where:r}){if(!e[t])throw new R.BetterAuthError(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);if(r?.some(e=>"id"===e.field)){let A=u({model:t,where:r,action:"delete"});try{return await e[t].delete({where:A})??null}catch(e){if(eG(e))return null;throw e}}let i=u({model:t,where:r,action:"findOne"}),n=async e=>{let A=await e[t].findFirst({where:i});if(!A)return null;try{return(await e[t].deleteMany({where:u({model:t,where:[...r??[],{field:"id",value:A.id,operator:"eq",connector:"AND",mode:"sensitive"}],action:"deleteMany"})}))?.count>0?A:null}catch(e){if(eG(e))return null;throw e}};return A||"function"!=typeof e.$transaction?n(e):e.$transaction(n)},async incrementOne({model:t,where:r,increment:i,set:n}){if(!e[t])throw new R.BetterAuthError(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let a={...n??{}};for(let[e,A]of Object.entries(i))a[e]={increment:A};if(r?.some(e=>"id"===e.field)){let A=u({model:t,where:r,action:"update"});try{return await e[t].update({where:A,data:a})??null}catch(e){if(eG(e))return null;throw e}}let o=u({model:t,where:r,action:"findOne"}),s=async e=>{let A=await e[t].findFirst({where:o});if(!A)return null;try{return await e[t].update({where:u({model:t,where:[...r,{field:"id",value:A.id,operator:"eq",connector:"AND",mode:"sensitive"}],action:"update"}),data:a})??null}catch(e){if(eG(e))return null;throw e}};return A||"function"!=typeof e.$transaction?s(e):e.$transaction(s)},options:t}},n=null,n={config:{adapterId:"prisma",adapterName:"Prisma Adapter",usePlural:t.usePlural??!1,debugLogs:t.debugLogs??!1,supportsUUIDs:"postgresql"===t.provider,supportsArrays:"postgresql"===t.provider||"mongodb"===t.provider,transaction:!!t.transaction&&(A=>e.$transaction(e=>A((0,ev.createAdapterFactory)({config:{...n.config,transaction:!1},adapter:i(e,!0)})(r))))},adapter:i(e)},a=(0,ev.createAdapterFactory)(n),e=>(r=e,a(e))),emailAndPassword:{enabled:ag(A.mode),requireEmailVerification:!1},account:{accountLinking:{enabled:!0,disableImplicitLinking:!0,allowDifferentEmails:!1}},databaseHooks:aQ,plugins:[function(){let e=(e=>{let A={...e||{},defaultRole:e?.defaultRole??"user",adminRoles:e?.adminRoles??["admin"],bannedUserMessage:e?.bannedUserMessage??"You have been banned from this application. Please contact support if you believe this is an error."};if(e?.adminRoles){let A=(Array.isArray(e.adminRoles)?e.adminRoles:[...e.adminRoles.split(",")]).filter(A=>!Object.keys(e?.roles||nq).map(e=>e.toLowerCase()).includes(A.toLowerCase()));if(A.length>0)throw new R.BetterAuthError(`Invalid admin roles: ${A.join(", ")}. Admin roles must be defined in the 'roles' configuration.`)}return{id:"admin",version:nx.PACKAGE_VERSION,init:()=>({options:{databaseHooks:{user:{create:{before:async A=>({data:{role:e?.defaultRole??"user",...A}})}},session:{create:{async before(e,t){if(!t)return;let r=await t.context.internalAdapter.findUserById(e.userId);if(r?.banned){if(r.banExpires&&new Date(r.banExpires).getTime()<Date.now())return void await t.context.internalAdapter.updateUser(e.userId,{banned:!1,banReason:null,banExpires:null});throw R.APIError.from("FORBIDDEN",{message:A.bannedUserMessage,code:"BANNED_USER"})}}}}}}}),hooks:{after:[{matcher:e=>"/list-sessions"===e.path,handler:(0,g.createAuthMiddleware)(async e=>{let A=await nJ(e);if(!A)return;let t=A.filter(e=>!e.impersonatedBy);return e.json(t)})}]},endpoints:{setRole:(0,g.createAuthEndpoint)("/admin/set-role",{method:"POST",body:nZ,requireHeaders:!0,use:[nz],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 e=>{if(!nF({userId:e.context.session.user.id,role:e.context.session.user.role,options:A,permissions:{user:["set-role"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE);let t=A.roles;if(t){for(let A of Array.isArray(e.body.role)?e.body.role:[e.body.role])if(!t[A])throw R.APIError.from("BAD_REQUEST",nK.YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE)}if(!await e.context.internalAdapter.findUserById(e.body.userId))throw R.APIError.from("NOT_FOUND",A_.BASE_ERROR_CODES.USER_NOT_FOUND);let r=await e.context.internalAdapter.updateUser(e.body.userId,{role:nY(e.body.role)});return e.json({user:(0,M.parseUserOutput)(e.context.options,r)})}),getUser:(0,g.createAuthEndpoint)("/admin/get-user",{method:"GET",query:nV,use:[nz],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 e=>{let{id:t}=e.query;if(!nF({userId:e.context.session.user.id,role:e.context.session.user.role,options:A,permissions:{user:["get"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_GET_USER);let r=await e.context.internalAdapter.findUserById(t);if(!r)throw R.APIError.from("NOT_FOUND",A_.BASE_ERROR_CODES.USER_NOT_FOUND);return(0,M.parseUserOutput)(e.context.options,r)}),createUser:(0,g.createAuthEndpoint)("/admin/create-user",{method:"POST",body:nW,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 e=>{let t=await (0,v.getAuthoritativeSessionFromCtx)(e);if(!t&&(e.request||e.headers))throw e.error("UNAUTHORIZED");if(t&&!nF({userId:t.user.id,role:t.user.role,options:A,permissions:{user:["create"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS);let{role:r,...i}=e.body.data??{},n=e.body.role??r;if(void 0!==n){if(t&&!nF({userId:t.user.id,role:t.user.role,options:A,permissions:{user:["set-role"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE);for(let e of Array.isArray(n)?n:[n]){if("string"!=typeof e)throw R.APIError.from("BAD_REQUEST",nK.INVALID_ROLE_TYPE);if(A.roles&&!A.roles[e])throw R.APIError.from("BAD_REQUEST",nK.YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE)}}if(t&&["banned","banReason","banExpires"].some(e=>Object.prototype.hasOwnProperty.call(i,e))&&!nF({userId:t.user.id,role:t.user.role,options:A,permissions:{user:["ban"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_BAN_USERS);let a=e.body.email.toLowerCase();if(!C.email().safeParse(a).success)throw R.APIError.from("BAD_REQUEST",A_.BASE_ERROR_CODES.INVALID_EMAIL);if(await e.context.internalAdapter.findUserByEmail(a))throw R.APIError.from("BAD_REQUEST",nK.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL);let o=await e.context.internalAdapter.createUser({...i,email:a,name:e.body.name,role:void 0!==n?nY(n):A?.defaultRole??"user"},{method:"admin"});if(!o)throw R.APIError.from("INTERNAL_SERVER_ERROR",nK.FAILED_TO_CREATE_USER);if(e.body.password){let A=await e.context.password.hash(e.body.password);await e.context.internalAdapter.linkAccount({providerId:"credential",issuer:Am("credential"),accountId:o.id,password:A,userId:o.id})}return e.json({user:(0,M.parseUserOutput)(e.context.options,o)})}),adminUpdateUser:(0,g.createAuthEndpoint)("/admin/update-user",{method:"POST",body:n$,use:[nz],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 e=>{if(!nF({userId:e.context.session.user.id,role:e.context.session.user.role,options:A,permissions:{user:["update"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS);if(0===Object.keys(e.body.data).length)throw R.APIError.from("BAD_REQUEST",nK.NO_DATA_TO_UPDATE);let t=e.body.data,r=e=>Object.prototype.hasOwnProperty.call(t,e);if(r("password"))throw R.APIError.from("BAD_REQUEST",nK.PASSWORD_CANNOT_BE_UPDATED_VIA_UPDATE_USER);if(Object.prototype.hasOwnProperty.call(e.body.data,"role")){if(!nF({userId:e.context.session.user.id,role:e.context.session.user.role,options:A,permissions:{user:["set-role"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE);let t=e.body.data.role,r=Array.isArray(t)?t:[t];for(let e of r){if("string"!=typeof e)throw R.APIError.from("BAD_REQUEST",nK.INVALID_ROLE_TYPE);if(A.roles&&!A.roles[e])throw R.APIError.from("BAD_REQUEST",nK.YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE)}e.body.data.role=nY(r)}if(["banned","banReason","banExpires"].some(r)){if(!nF({userId:e.context.session.user.id,role:e.context.session.user.role,options:A,permissions:{user:["ban"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_BAN_USERS);if(!0===t.banned&&e.body.userId===e.context.session.user.id)throw R.APIError.from("BAD_REQUEST",nK.YOU_CANNOT_BAN_YOURSELF)}if(r("email")||r("emailVerified")){if(!nF({userId:e.context.session.user.id,role:e.context.session.user.role,options:A,permissions:{user:["set-email"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_SET_USERS_EMAIL);if(r("email")){let A=String(t.email).toLowerCase();if(!C.email().safeParse(A).success)throw R.APIError.from("BAD_REQUEST",A_.BASE_ERROR_CODES.INVALID_EMAIL);let r=await e.context.internalAdapter.findUserByEmail(A);if(r&&r.user.id!==e.body.userId)throw R.APIError.from("BAD_REQUEST",nK.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL);t.email=A}}if(!await e.context.internalAdapter.findUserById(e.body.userId))throw R.APIError.from("NOT_FOUND",A_.BASE_ERROR_CODES.USER_NOT_FOUND);let i=await e.context.internalAdapter.updateUser(e.body.userId,e.body.data);return!0===t.banned&&await e.context.internalAdapter.deleteUserSessions(e.body.userId),e.json((0,M.parseUserOutput)(e.context.options,i))}),listUsers:(0,g.createAuthEndpoint)("/admin/list-users",{method:"GET",use:[nz],query:nX,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 e=>{let t=e.context.session;if(!nF({userId:e.context.session.user.id,role:t.user.role,options:A,permissions:{user:["list"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_LIST_USERS);let r=[];e.query?.searchValue&&r.push({field:e.query.searchField||"email",operator:e.query.searchOperator||"contains",value:e.query.searchValue}),e.query?.filterValue!==void 0&&r.push({field:e.query.filterField||"email",operator:e.query.filterOperator||"eq",value:e.query.filterValue});try{let A=await e.context.internalAdapter.listUsers(Number(e.query?.limit)||void 0,Number(e.query?.offset)||void 0,e.query?.sortBy?{field:e.query.sortBy,direction:e.query.sortDirection||"asc"}:void 0,r.length?r:void 0),t=await e.context.internalAdapter.countTotalUsers(r.length?r:void 0);return e.json({users:A.map(A=>(0,M.parseUserOutput)(e.context.options,A)),total:t,limit:Number(e.query?.limit)||void 0,offset:Number(e.query?.offset)||void 0})}catch{return e.json({users:[],total:0})}}),listUserSessions:(0,g.createAuthEndpoint)("/admin/list-user-sessions",{method:"POST",use:[nz],body:n0,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 e=>{let t=e.context.session;if(!nF({userId:e.context.session.user.id,role:t.user.role,options:A,permissions:{session:["list"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS);let r=await e.context.internalAdapter.listSessions(e.body.userId);return e.json({sessions:r.map(A=>(0,M.parseSessionOutput)(e.context.options,A))})}),unbanUser:(0,g.createAuthEndpoint)("/admin/unban-user",{method:"POST",body:n1,use:[nz],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 e=>{let t=e.context.session;if(!nF({userId:e.context.session.user.id,role:t.user.role,options:A,permissions:{user:["ban"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_BAN_USERS);if(!await e.context.internalAdapter.findUserById(e.body.userId))throw R.APIError.from("NOT_FOUND",A_.BASE_ERROR_CODES.USER_NOT_FOUND);let r=await e.context.internalAdapter.updateUser(e.body.userId,{banned:!1,banExpires:null,banReason:null,updatedAt:new Date});return e.json({user:(0,M.parseUserOutput)(e.context.options,r)})}),banUser:(0,g.createAuthEndpoint)("/admin/ban-user",{method:"POST",body:n8,use:[nz],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 e=>{let t=e.context.session;if(!nF({userId:e.context.session.user.id,role:t.user.role,options:A,permissions:{user:["ban"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_BAN_USERS);if(!await e.context.internalAdapter.findUserById(e.body.userId))throw R.APIError.from("NOT_FOUND",A_.BASE_ERROR_CODES.USER_NOT_FOUND);if(e.body.userId===e.context.session.user.id)throw R.APIError.from("BAD_REQUEST",nK.YOU_CANNOT_BAN_YOURSELF);let r=await e.context.internalAdapter.updateUser(e.body.userId,{banned:!0,banReason:e.body.banReason||A?.defaultBanReason||"No reason",banExpires:e.body.banExpiresIn?(0,Aa.getDate)(e.body.banExpiresIn,"sec"):A?.defaultBanExpiresIn?(0,Aa.getDate)(A.defaultBanExpiresIn,"sec"):null,updatedAt:new Date});return await e.context.internalAdapter.deleteUserSessions(e.body.userId),e.json({user:(0,M.parseUserOutput)(e.context.options,r)})}),impersonateUser:(0,g.createAuthEndpoint)("/admin/impersonate-user",{method:"POST",body:n4,use:[nz],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 e=>{if(!nF({userId:e.context.session.user.id,role:e.context.session.user.role,options:A,permissions:{user:["impersonate"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS);let t=await e.context.internalAdapter.findUserById(e.body.userId);if(!t)throw R.APIError.from("NOT_FOUND",A_.BASE_ERROR_CODES.USER_NOT_FOUND);let r=(Array.isArray(A.adminRoles)?A.adminRoles:A.adminRoles?.split(",")||[]).map(e=>e.trim());if(((t.role||A.defaultRole||"user").split(",").some(e=>r.includes(e))||A.adminUserIds?.includes(t.id))&&!(!0===A.allowImpersonatingAdmins||nF({userId:e.context.session.user.id,role:e.context.session.user.role,options:A,permissions:{user:["impersonate-admins"]}})))throw R.APIError.from("FORBIDDEN",nK.YOU_CANNOT_IMPERSONATE_ADMINS);let i=await e.context.internalAdapter.createSession(t.id,!0,{impersonatedBy:e.context.session.user.id,expiresAt:A?.impersonationSessionDuration?(0,Aa.getDate)(A.impersonationSessionDuration,"sec"):(0,Aa.getDate)(3600,"sec")},!0);if(!i)throw R.APIError.from("INTERNAL_SERVER_ERROR",nK.FAILED_TO_CREATE_USER);let n=e.context.authCookies;(0,An.deleteSessionCookie)(e);let a=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret),o=e.context.createAuthCookie("admin_session");return await e.setSignedCookie(o.name,`${e.context.session.session.token}:${a||""}`,e.context.secret,n.sessionToken.attributes),await (0,An.setSessionCookie)(e,{session:i,user:t},!0),e.json({session:i,user:(0,M.parseUserOutput)(e.context.options,t)})}),stopImpersonating:(0,g.createAuthEndpoint)("/admin/stop-impersonating",{method:"POST",requireHeaders:!0},async e=>{let A=await (0,v.getSessionFromCtx)(e);if(!A)throw R.APIError.fromStatus("UNAUTHORIZED");if(!A.session.impersonatedBy)throw R.APIError.fromStatus("BAD_REQUEST",{message:"You are not impersonating anyone"});let t=await e.context.internalAdapter.findUserById(A.session.impersonatedBy);if(!t)throw R.APIError.fromStatus("INTERNAL_SERVER_ERROR",{message:"Failed to find user"});let r=e.context.createAuthCookie("admin_session"),i=await e.getSignedCookie(r.name,e.context.secret);if(!i)throw R.APIError.fromStatus("INTERNAL_SERVER_ERROR",{message:"Failed to find admin session"});let[n,a]=i?.split(":"),o=await e.context.internalAdapter.findSession(n);if(!o||o.session.userId!==t.id)throw R.APIError.fromStatus("INTERNAL_SERVER_ERROR",{message:"Failed to find admin session"});return await e.context.internalAdapter.deleteSession(A.session.token),await (0,An.setSessionCookie)(e,o,!!a),(0,An.expireCookie)(e,r),e.json({session:(0,M.parseSessionOutput)(e.context.options,o.session),user:(0,M.parseUserOutput)(e.context.options,o.user)})}),revokeUserSession:(0,g.createAuthEndpoint)("/admin/revoke-user-session",{method:"POST",body:n2,use:[nz],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 e=>{let t=e.context.session;if(!nF({userId:e.context.session.user.id,role:t.user.role,options:A,permissions:{session:["revoke"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS);return await e.context.internalAdapter.deleteSession(e.body.sessionToken),e.json({success:!0})}),revokeUserSessions:(0,g.createAuthEndpoint)("/admin/revoke-user-sessions",{method:"POST",body:n6,use:[nz],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 e=>{let t=e.context.session;if(!nF({userId:e.context.session.user.id,role:t.user.role,options:A,permissions:{session:["revoke"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS);return await e.context.internalAdapter.deleteUserSessions(e.body.userId),e.json({success:!0})}),removeUser:(0,g.createAuthEndpoint)("/admin/remove-user",{method:"POST",body:n3,use:[nz],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 e=>{let t=e.context.session;if(!nF({userId:e.context.session.user.id,role:t.user.role,options:A,permissions:{user:["delete"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS);if(e.body.userId===e.context.session.user.id)throw R.APIError.from("BAD_REQUEST",nK.YOU_CANNOT_REMOVE_YOURSELF);if(!await e.context.internalAdapter.findUserById(e.body.userId))throw R.APIError.from("NOT_FOUND",A_.BASE_ERROR_CODES.USER_NOT_FOUND);return await e.context.internalAdapter.deleteUserSessions(e.body.userId),await e.context.internalAdapter.deleteUser(e.body.userId),e.json({success:!0})}),setUserPassword:(0,g.createAuthEndpoint)("/admin/set-user-password",{method:"POST",body:n5,use:[nz],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 e=>{if(!nF({userId:e.context.session.user.id,role:e.context.session.user.role,options:A,permissions:{user:["set-password"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD);let{newPassword:t,userId:r}=e.body,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.warn("Password is too short"),R.APIError.from("BAD_REQUEST",A_.BASE_ERROR_CODES.PASSWORD_TOO_SHORT);let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.warn("Password is too long"),R.APIError.from("BAD_REQUEST",A_.BASE_ERROR_CODES.PASSWORD_TOO_LONG);let a=await e.context.internalAdapter.findUserById(r);if(!a)throw R.APIError.from("NOT_FOUND",A_.BASE_ERROR_CODES.USER_NOT_FOUND);let o=await e.context.password.hash(t);return await e.context.internalAdapter.findCredentialAccount(r)?await e.context.internalAdapter.updatePassword(r,o):await e.context.internalAdapter.createAccount({userId:r,providerId:"credential",issuer:Am("credential"),accountId:a.id,password:o}),e.json({status:!0})}),userHasPermission:(0,g.createAuthEndpoint)("/admin/has-permission",{method:"POST",body:n9,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 e=>{if(!e.body?.permissions)throw new R.APIError("BAD_REQUEST",{message:"invalid permission check. no permission(s) were passed."});let t=await (0,v.getAuthoritativeSessionFromCtx)(e);if(!t&&(e.request||e.headers))throw new R.APIError("UNAUTHORIZED");if(!t&&!e.body.userId&&!e.body.role)throw new R.APIError("BAD_REQUEST",{message:"user id or role is required"});let r=t?.user||(e.body.role?{id:e.body.userId||"",role:e.body.role}:null)||(e.body.userId?await e.context.internalAdapter.findUserById(e.body.userId):null);if(!r)throw new R.APIError("BAD_REQUEST",{message:"user not found"});let i=nF({userId:r.id,role:r.role,options:A,permissions:e.body.permissions});return e.json({error:null,success:i})})},$ERROR_CODES:nK,schema:(0,M.mergeSchema)(n7,A.schema),options:e}})({ac:ab,roles:{user:aS},defaultRole:"user",adminRoles:["user"]}),{setRole:A,banUser:t,unbanUser:r,impersonateUser:i,stopImpersonating:n,removeUser:a,...o}=e.endpoints;return{...e,endpoints:o}}(),function(e){if(Array.isArray(e)&&e.length>0){if(!e.every(e=>e.configId))throw new R.BetterAuthError("configId is required for each API key configuration in the api-key plugin.");let A=e.map(e=>e.configId);if(new Set(A).size!==A.length)throw new R.BetterAuthError("configId must be unique for each API key configuration in the api-key plugin.")}let A=(void 0)??{schema:Array.isArray(e)?void 0:e?.schema},t=[...(Array.isArray(e)?e:[e]).map(e=>({...e,apiKeyHeaders:e?.apiKeyHeaders??"x-api-key",defaultKeyLength:e?.defaultKeyLength||64,maximumPrefixLength:e?.maximumPrefixLength??32,minimumPrefixLength:e?.minimumPrefixLength??1,maximumNameLength:e?.maximumNameLength??32,minimumNameLength:e?.minimumNameLength??1,enableMetadata:e?.enableMetadata??!1,disableKeyHashing:e?.disableKeyHashing??!1,requireName:e?.requireName??!1,storage:e?.storage??"database",rateLimit:{enabled:e?.rateLimit?.enabled===void 0||e?.rateLimit?.enabled,timeWindow:e?.rateLimit?.timeWindow??864e5,maxRequests:e?.rateLimit?.maxRequests??10},keyExpiration:{defaultExpiresIn:e?.keyExpiration?.defaultExpiresIn??null,disableCustomExpiresTime:e?.keyExpiration?.disableCustomExpiresTime??!1,maxExpiresIn:e?.keyExpiration?.maxExpiresIn??365,minExpiresIn:e?.keyExpiration?.minExpiresIn??1},startingCharactersConfig:{shouldStore:e?.startingCharactersConfig?.shouldStore??!0,charactersLength:e?.startingCharactersConfig?.charactersLength??6},enableSessionForAPIKeys:e?.enableSessionForAPIKeys??!1,fallbackToDatabase:e?.fallbackToDatabase??!1,customStorage:e?.customStorage,deferUpdates:e?.deferUpdates??!1}))],r=(0,M.mergeSchema)((({defaultRateLimitMax:e,defaultTimeWindow:A})=>({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:A},rateLimitMax:{type:"number",required:!1,input:!1,defaultValue:e},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:e=>JSON.stringify(e),output:e=>e?(0,x.parseJSON)(e):null}}}}}))({defaultRateLimitMax:(1===t.length?t[0]?.rateLimit.maxRequests:void 0)??10,defaultTimeWindow:(1===t.length?t[0]?.rateLimit.timeWindow:void 0)??864e5}),A.schema);function i(e){for(let A of t){if(!A.enableSessionForAPIKeys)continue;let t=function(e,A){if(A.customAPIKeyGetter)return A.customAPIKeyGetter(e);if(Array.isArray(A.apiKeyHeaders)){for(let t of A.apiKeyHeaders){let A=e.headers?.get(t);if(A)return A}return null}return e.headers?.get(A.apiKeyHeaders)??null}(e,A);if(t)return{key:t,config:A}}return null}let n=function({defaultKeyGenerator:e,configurations:A,schema:t}){return{createApiKey:function({defaultKeyGenerator:e,configurations:A,schema:t,deleteAllExpiredApiKeys:r}){return(0,g.createAuthEndpoint)("/api-key/create",{method:"POST",body:eu,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:o,expiresIn:s,prefix:l,remaining:d,metadata:u,refillAmount:c,refillInterval:g,permissions:p,rateLimitMax:C,rateLimitTimeWindow:f,rateLimitEnabled:I}=t.body,w=eB(t.context,A,a),m=w.customKeyGenerator||e,E=await (0,v.getSessionFromCtx)(t,{disableCookieCache:!0}),y=t.request||t.headers;if(y&&(void 0!==c||void 0!==g||void 0!==C||void 0!==f||void 0!==I||void 0!==p||null!==d))throw R.APIError.from("BAD_REQUEST",h.SERVER_ONLY_PROPERTY);if(t.request&&void 0!==t.body.userId)throw R.APIError.from("UNAUTHORIZED",h.UNAUTHORIZED_SESSION);if("organization"===(w.references??"user")){let e=t.body.organizationId;if(!e){let e=h.ORGANIZATION_ID_REQUIRED;throw R.APIError.from("BAD_REQUEST",e)}let A=E?.user.id||t.body.userId;if(!A)throw R.APIError.from("UNAUTHORIZED",h.UNAUTHORIZED_SESSION);await es(t,A,e,"create"),i=e}else if(y){if(!E?.user.id){let e=h.UNAUTHORIZED_SESSION;throw R.APIError.from("UNAUTHORIZED",e)}i=E.user.id}else{let e=t.body.userId,A=E?.user.id;if(!A&&!e||E&&e&&A!==e){let e=h.UNAUTHORIZED_SESSION;throw R.APIError.from("UNAUTHORIZED",e)}i=A||e}if(u){if(!1===w.enableMetadata)throw R.APIError.from("BAD_REQUEST",h.METADATA_DISABLED);if("object"!=typeof u)throw R.APIError.from("BAD_REQUEST",h.INVALID_METADATA_TYPE)}if(c&&!g){let e=h.REFILL_AMOUNT_AND_INTERVAL_REQUIRED;throw R.APIError.from("BAD_REQUEST",e)}if(g&&!c){let e=h.REFILL_INTERVAL_AND_AMOUNT_REQUIRED;throw R.APIError.from("BAD_REQUEST",e)}if(s){if(!0===w.keyExpiration.disableCustomExpiresTime){let e=h.KEY_DISABLED_EXPIRATION;throw R.APIError.from("BAD_REQUEST",e)}let e=s/86400;if(w.keyExpiration.minExpiresIn>e){let e=h.EXPIRES_IN_IS_TOO_SMALL;throw R.APIError.from("BAD_REQUEST",e)}if(w.keyExpiration.maxExpiresIn<e){let e=h.EXPIRES_IN_IS_TOO_LARGE;throw R.APIError.from("BAD_REQUEST",e)}}if(l&&(l.length<w.minimumPrefixLength||l.length>w.maximumPrefixLength))throw R.APIError.from("BAD_REQUEST",h.INVALID_PREFIX_LENGTH);if(o){if(o.length<w.minimumNameLength||o.length>w.maximumNameLength)throw R.APIError.from("BAD_REQUEST",h.INVALID_NAME_LENGTH)}else if(w.requireName)throw R.APIError.from("BAD_REQUEST",h.NAME_REQUIRED);r(t.context);let B=await m({length:w.defaultKeyLength,prefix:l||w.defaultPrefix}),Q=w.disableKeyHashing?B:await ek(B),D=null;w.startingCharactersConfig.shouldStore&&(D=B.substring(0,w.startingCharactersConfig.charactersLength));let b=w.permissions?.defaultPermissions?"function"==typeof w.permissions.defaultPermissions?await w.permissions.defaultPermissions(i,t):w.permissions.defaultPermissions:void 0,S=p?JSON.stringify(p):b?JSON.stringify(b):void 0,k={configId:w.configId??"default",createdAt:new Date,updatedAt:new Date,name:o??null,prefix:l??w.defaultPrefix??null,start:D,key:Q,enabled:!0,expiresAt:s?ed(s,"sec"):w.keyExpiration.defaultExpiresIn?ed(w.keyExpiration.defaultExpiresIn,"sec"):null,referenceId:i,lastRefillAt:null,lastRequest:null,metadata:null,rateLimitMax:C??w.rateLimit.maxRequests??null,rateLimitTimeWindow:f??w.rateLimit.timeWindow??null,remaining:null===d?d:d??c??null,refillAmount:c??null,refillInterval:g??null,rateLimitEnabled:void 0===I?w.rateLimit.enabled??!0:I,requestCount:0,permissions:S};if(u&&(k.metadata=u),"secondary-storage"===w.storage&&w.fallbackToDatabase)n=await t.context.adapter.create({model:eR,data:k}),await ei(t,n,w);else if("secondary-storage"===w.storage){let e=t.context.generateId({model:"apikey"})||(0,N.generateId)();n={...k,id:e},await ei(t,n,w)}else n=await t.context.adapter.create({model:eR,data:k});return t.json({...n,key:B,metadata:u??null,permissions:n.permissions?(0,O.safeJSONParse)(n.permissions):null})})}({defaultKeyGenerator:e,configurations:A,schema:t,deleteAllExpiredApiKeys:eS}),verifyApiKey:function({configurations:e,schema:A,deleteAllExpiredApiKeys:t}){return g.createAuthEndpoint.serverOnly({method:"POST",body:ey},async r=>{let i,{configId:n,key:a}=r.body,o=eB(r.context,e,n);if(void 0!==n&&o.customAPIKeyValidator&&!await o.customAPIKeyValidator({ctx:r,key:a}))return r.json({valid:!1,error:{message:h.INVALID_API_KEY,code:"KEY_NOT_FOUND"},key:null});let s=null;try{let l=await ef({key:a,permissions:r.body.permissions,ctx:r,lookupOpts:o,configurations:e,schema:A,expectedConfigId:n,runCustomValidator:void 0===n});s=l.apiKey,(i=l.opts).deferUpdates&&r.context.runInBackground(t(r.context).catch(e=>{r.context.logger.error("Failed to delete expired API keys:",e)}))}catch(e){if(r.context.logger.error("Failed to validate API key:",e),e instanceof R.APIError||e instanceof R.APIError||e?.name==="APIError")return r.json({valid:!1,error:{...e.body,message:e.body?.message,code:e.body?.code},key:null});return r.json({valid:!1,error:{message:h.INVALID_API_KEY,code:"INVALID_API_KEY"},key:null})}let{key:l,...d}=s??{key:1,permissions:void 0},u=null;return s&&(u=await K(r,s,i)),d.permissions=d.permissions?(0,O.safeJSONParse)(d.permissions):null,r.json({valid:!0,error:null,key:null===s?null:{...d,metadata:u}})})}({configurations:A,schema:t,deleteAllExpiredApiKeys:eS}),getApiKey:function({configurations:e,schema:A,deleteAllExpiredApiKeys:t}){return(0,g.createAuthEndpoint)("/api-key/get",{method:"GET",query:eh,use:[v.sessionMiddleware],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 A=>{let{configId:r,id:i}=A.query,n=A.context.session,a=eB(A.context,e,r),o=null;if(!(o=await er(A,i,a))||!eD(o.configId,a.configId))throw R.APIError.from("NOT_FOUND",h.KEY_NOT_FOUND);let s=eB(A.context,e,o.configId);if((s.references??"user")==="organization")await es(A,n.user.id,o.referenceId,"read");else if(o.referenceId!==n.user.id)throw R.APIError.from("NOT_FOUND",h.KEY_NOT_FOUND);t(A.context);let l=await K(A,o,s),{key:d,...u}=o;return A.json({...u,metadata:l,permissions:u.permissions?(0,O.safeJSONParse)(u.permissions):null})})}({configurations:A,schema:t,deleteAllExpiredApiKeys:eS}),updateApiKey:function({configurations:e,schema:A,deleteAllExpiredApiKeys:t}){return(0,g.createAuthEndpoint)("/api-key/update",{method:"POST",body:ep,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 A=>{let{configId:r,keyId:i,expiresIn:n,enabled:a,metadata:o,refillAmount:s,refillInterval:l,remaining:d,name:u,permissions:c,rateLimitEnabled:g,rateLimitTimeWindow:p,rateLimitMax:C}=A.body,f=await (0,v.getSessionFromCtx)(A,{disableCookieCache:!0}),I=A.request||A.headers,w=I&&!f?null:f?.user||{id:A.body.userId};if(!w?.id||f&&A.body.userId&&f?.user.id!==A.body.userId)throw R.APIError.from("UNAUTHORIZED",h.UNAUTHORIZED_SESSION);if(I&&(void 0!==s||void 0!==l||void 0!==C||void 0!==p||void 0!==g||void 0!==d||void 0!==c))throw R.APIError.from("BAD_REQUEST",h.SERVER_ONLY_PROPERTY);let m=eB(A.context,e,r),E=null;if(!(E=await er(A,i,m))||!eD(E.configId,m.configId))throw R.APIError.from("NOT_FOUND",h.KEY_NOT_FOUND);let y=eB(A.context,e,E.configId);if((y.references??"user")==="organization")await es(A,w.id,E.referenceId,"update");else if(E.referenceId!==w.id)throw R.APIError.from("NOT_FOUND",h.KEY_NOT_FOUND);let B={};if(void 0!==u){if(u.length<y.minimumNameLength||u.length>y.maximumNameLength)throw R.APIError.from("BAD_REQUEST",h.INVALID_NAME_LENGTH);B.name=u}if(void 0!==a&&(B.enabled=a),void 0!==n){if(!0===y.keyExpiration.disableCustomExpiresTime)throw R.APIError.from("BAD_REQUEST",h.KEY_DISABLED_EXPIRATION);if(null!==n){let e=n/86400;if(e<y.keyExpiration.minExpiresIn)throw R.APIError.from("BAD_REQUEST",h.EXPIRES_IN_IS_TOO_SMALL);if(e>y.keyExpiration.maxExpiresIn)throw R.APIError.from("BAD_REQUEST",h.EXPIRES_IN_IS_TOO_LARGE)}B.expiresAt=n?ed(n,"sec"):null}if(void 0!==o&&!0===y.enableMetadata){if("object"!=typeof o)throw R.APIError.from("BAD_REQUEST",h.INVALID_METADATA_TYPE);B.metadata=o}if(void 0!==d&&(B.remaining=d),void 0!==s||void 0!==l){if(void 0!==s&&void 0===l)throw R.APIError.from("BAD_REQUEST",h.REFILL_AMOUNT_AND_INTERVAL_REQUIRED);if(void 0!==l&&void 0===s)throw R.APIError.from("BAD_REQUEST",h.REFILL_INTERVAL_AND_AMOUNT_REQUIRED);B.refillAmount=s,B.refillInterval=l}if(void 0!==g&&(B.rateLimitEnabled=g),void 0!==p&&(B.rateLimitTimeWindow=p),void 0!==C&&(B.rateLimitMax=C),void 0!==c&&(B.permissions=JSON.stringify(c)),0===Object.keys(B).length)throw R.APIError.from("BAD_REQUEST",h.NO_VALUES_TO_UPDATE);let Q=E;try{if("secondary-storage"===y.storage&&y.fallbackToDatabase){let e=await A.context.adapter.update({model:eR,where:[{field:"id",value:E.id}],update:B});e&&(await ei(A,e,y),Q=e)}else if("database"===y.storage){let e=await A.context.adapter.update({model:eR,where:[{field:"id",value:E.id}],update:B});e&&(Q=e)}else{let e={...E,...B,updatedAt:new Date};await ei(A,e,y),Q=e}}catch(e){throw R.APIError.fromStatus("INTERNAL_SERVER_ERROR",{message:e?.message})}t(A.context);let D=await K(A,Q,y),{key:b,...S}=Q;return A.json({...S,metadata:D,permissions:S.permissions?(0,O.safeJSONParse)(S.permissions):null})})}({configurations:A,schema:t,deleteAllExpiredApiKeys:eS}),deleteApiKey:function({configurations:e,schema:A,deleteAllExpiredApiKeys:t}){return(0,g.createAuthEndpoint)("/api-key/delete",{method:"POST",body:ec,use:[v.sessionMiddleware],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 A=>{let{configId:r,keyId:i}=A.body,n=A.context.session;if(!0===n.user.banned)throw R.APIError.from("UNAUTHORIZED",h.USER_BANNED);let a=eB(A.context,e,r),o=null;if(!(o=await er(A,i,a))||!eD(o.configId,a.configId))throw R.APIError.from("NOT_FOUND",h.KEY_NOT_FOUND);let s=eB(A.context,e,o.configId);if((s.references??"user")==="organization")await es(A,n.user.id,o.referenceId,"delete");else if(o.referenceId!==n.user.id)throw R.APIError.from("NOT_FOUND",h.KEY_NOT_FOUND);try{"secondary-storage"===s.storage&&s.fallbackToDatabase?(await en(A,o,s),await A.context.adapter.delete({model:eR,where:[{field:"id",value:o.id}]})):"database"===s.storage?await A.context.adapter.delete({model:eR,where:[{field:"id",value:o.id}]}):await en(A,o,s)}catch(e){throw R.APIError.fromStatus("INTERNAL_SERVER_ERROR",{message:e?.message})}return t(A.context),A.json({success:!0})})}({configurations:A,schema:t,deleteAllExpiredApiKeys:eS}),listApiKeys:function({configurations:e,schema:A,deleteAllExpiredApiKeys:t}){return(0,g.createAuthEndpoint)("/api-key/list",{method:"GET",use:[v.sessionMiddleware],query:eg,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 A=>{let r=A.context.session,i=A.query?.configId,n=A.query?.organizationId,a=A.query?.limit!=null?Number(A.query.limit):void 0,o=A.query?.offset!=null?Number(A.query.offset):void 0;n&&await es(A,r.user.id,n,"read");let s=n??r.user.id,l=n?"organization":"user",d=[];if(i){let{apiKeys:t}=await eo(A,s,eB(A.context,e,i),{limit:void 0,offset:void 0,sortBy:A.query?.sortBy,sortDirection:A.query?.sortDirection});d=t}else{let t=new Map;for(let A of e){let e="database"===A.storage?"database":A.customStorage?`custom:${A.configId??"default"}`:A.fallbackToDatabase?"secondary-storage-with-fallback":"secondary-storage";t.has(e)||t.set(e,A)}let r=await Promise.all([...t.values()].map(e=>eo(A,s,e,{limit:void 0,offset:void 0,sortBy:A.query?.sortBy,sortDirection:A.query?.sortDirection}))),i=new Set;for(let{apiKeys:e}of r)for(let A of e)i.has(A.id)||(i.add(A.id),d.push(A))}let u=d.filter(A=>(e.find(e=>eQ(A.configId)?eQ(e.configId):e.configId===A.configId)?.references??"user")===l&&A.referenceId===s);i&&(u=u.filter(e=>eD(e.configId,i)));let c=u.length,h=u;void 0!==o&&(h=h.slice(o)),void 0!==a&&(h=h.slice(0,a)),t(A.context);let g=h.map(e=>{let{key:A,...t}=e;return{...t,metadata:L(e.metadata),permissions:t.permissions?(0,O.safeJSONParse)(t.permissions):null}}),p=e.find(e=>"database"===e.storage||e.fallbackToDatabase);return p&&await A.context.runInBackgroundOrAwait(q(A,h,p)),A.json({apiKeys:g,total:c,limit:a,offset:o})})}({configurations:A,schema:t,deleteAllExpiredApiKeys:eS}),deleteAllExpiredApiKeys:function({deleteAllExpiredApiKeys:e}){return g.createAuthEndpoint.serverOnly({method:"POST"},async A=>{try{await e(A.context,!0)}catch(e){return A.context.logger.error("[API KEY PLUGIN] Failed to delete expired API keys:",e),A.json({success:!1,error:e})}return A.json({success:!0,error:null})})}({deleteAllExpiredApiKeys:eS})}}({defaultKeyGenerator:async e=>{let A=T(e.length,"a-z","A-Z");return`${e.prefix||""}${A}`},configurations:t,schema:r});return{id:"api-key",version:"1.7.2",$ERROR_CODES:h,hooks:{before:[{matcher:e=>!!i(e),handler:(0,g.createAuthMiddleware)(async e=>{let{key:A,config:n}=i(e);if("string"!=typeof A)throw R.APIError.from("BAD_REQUEST",h.INVALID_API_KEY_GETTER_RETURN_TYPE);if(A.length<n.defaultKeyLength||n.customAPIKeyValidator&&!await n.customAPIKeyValidator({ctx:e,key:A}))throw R.APIError.from("FORBIDDEN",h.INVALID_API_KEY);let{apiKey:a}=await ef({key:A,ctx:e,lookupOpts:n,configurations:t,schema:r,expectedConfigId:n.configId}),o=eS(e.context).catch(A=>{e.context.logger.error("Failed to delete expired API keys:",A)});if(n.deferUpdates&&e.context.runInBackground(o),(n.references??"user")!=="user"){let e=h.INVALID_REFERENCE_ID_FROM_API_KEY;throw R.APIError.from("UNAUTHORIZED",e)}let s=await e.context.internalAdapter.findUserById(a.referenceId);if(!s){let e=h.INVALID_REFERENCE_ID_FROM_API_KEY;throw R.APIError.from("UNAUTHORIZED",e)}let l={user:s,session:{id:a.id,token:A,userId:a.referenceId,userAgent:e.request?.headers.get("user-agent")??null,ipAddress:e.request?b(e.request,e.context.options):null,createdAt:new Date,updatedAt:new Date,expiresAt:a.expiresAt||ed(e.context.options.session?.expiresIn||604800,"ms")}};return(e.context.session=l,"/get-session"===e.path)?l:{context:e}})}]},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:nx.PACKAGE_VERSION,hooks:{before:[{matcher:e=>!!(e.request?.headers.get("authorization")||e.headers?.get("authorization")),handler:(0,g.createAuthMiddleware)(async e=>{let A,t=e.request?.headers.get("authorization")||e.headers?.get("Authorization");if(!t||"bearer "!==t.slice(0,7).toLowerCase())return;let r=t.slice(7).trim();if(!r)return;A=r.includes(".")?r.includes("%")?at(r):r:at((await (0,ae.serializeSignedCookie)("",r,e.context.secret)).replace("=",""));try{if(!await (0,aA.createHMAC)("SHA-256","base64urlnopad").verify(e.context.secret,A.split(".")[0],A.split(".")[1]))return}catch{return}let i=e.request?.headers||e.headers,n=new Headers({...Object.fromEntries(i?.entries())});return(0,n_.setRequestCookie)(n,e.context.authCookies.sessionToken.name,A),{context:{headers:n}}})}],after:[{matcher:e=>!0,handler:(0,g.createAuthMiddleware)(async e=>{let A=e.context.responseHeaders?.get("set-cookie");if(!A)return;let t=(0,n_.parseSetCookieHeader)(A),r=e.context.authCookies.sessionToken.name,i=t.get(r);if(!i||!i.value||0===i["max-age"])return;let n=i.value,a=new Set((e.context.responseHeaders?.get("access-control-expose-headers")||"").split(",").map(e=>e.trim()).filter(Boolean));a.add("set-auth-token"),e.setHeader("set-auth-token",n),e.setHeader("Access-Control-Expose-Headers",Array.from(a).join(", "))})}]},options:void 0},(e=>{let A={storeToken:"plain",...e};async function t(e,t){return"hashed"===A.storeToken?await aa(t):"object"==typeof A.storeToken&&"type"in A.storeToken&&"custom-hasher"===A.storeToken.type?await A.storeToken.hash(t):t}async function r(e,r){let i=A?.generateToken?await A.generateToken(r,e):T(32),n=new Date(Date.now()+(A?.expiresIn??3)*6e4),a=await t(e,i);return await e.context.internalAdapter.createVerificationValue({value:r.session.token,identifier:`one-time-token:${a}`,expiresAt:n}),i}return{id:"one-time-token",version:nx.PACKAGE_VERSION,endpoints:{generateOneTimeToken:(0,g.createAuthEndpoint)("/one-time-token/generate",{method:"GET",use:[v.sessionMiddleware]},async e=>{if(A?.disableClientRequest&&e.request)throw e.error("BAD_REQUEST",{message:"Client requests are disabled"});let t=e.context.session,i=await r(e,t);return e.json({token:i})}),verifyOneTimeToken:(0,g.createAuthEndpoint)("/one-time-token/verify",{method:"POST",body:ao},async e=>{let{token:r}=e.body,i=await t(e,r),n=await e.context.internalAdapter.consumeVerificationValue(`one-time-token:${i}`);if(!n)throw e.error("BAD_REQUEST",{message:"Invalid token"});let a=await e.context.internalAdapter.findSession(n.value);if(!a)throw e.error("BAD_REQUEST",{message:"Session not found"});if(A?.disableSetSessionCookie||await (0,An.setSessionCookie)(e,a),a.session.expiresAt<new Date)throw e.error("BAD_REQUEST",{message:"Session expired"});return e.json(a)})},hooks:{after:[{matcher:()=>!0,handler:(0,g.createAuthMiddleware)(async e=>{if(e.context.newSession){if(!A?.setOttHeaderOnNewSession)return;let t=new Set((e.context.responseHeaders?.get("access-control-expose-headers")||"").split(",").map(e=>e.trim()).filter(Boolean));t.add("set-ott");let i=await r(e,e.context.newSession);e.setHeader("set-ott",i),e.setHeader("Access-Control-Expose-Headers",Array.from(t).join(", "))}})}]},options:e}})({disableClientRequest:!0,expiresIn:1,storeToken:"hashed"}),...s?[s]:[],(o=!1,{id:"next-cookies",version:nx.PACKAGE_VERSION,hooks:{before:[{matcher:e=>"/get-session"===e.path,handler:(0,g.createAuthMiddleware)(async e=>{let A;if(o||(!function(e,A){let t=e.options.plugins||[];if(0===t.length)return;let r=t.findIndex(e=>e.id===A);-1===r||t.slice(r+1).some(e=>e.hooks&&Array.isArray(e.hooks.after)&&e.hooks.after.length>0)&&e.logger.warn(`[better-auth] Cookie integration plugin "${A}" 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.`)}(e.context,"next-cookies"),o=!0),"_flag"in e&&"router"===e._flag)return;try{let{headers:e}=await nL();A=await e()}catch{return}let t="1"===A.get("RSC"),r=!!A.get("next-action");t&&!r&&await (0,te.setShouldSkipSessionRefresh)(!0)})}],after:[{matcher:e=>!0,handler:(0,g.createAuthMiddleware)(async e=>{let A=e.context.responseHeaders;if((!("_flag"in e)||"router"!==e._flag)&&A instanceof Headers){let e,t=A?.get("set-cookie");if(!t)return;let r=(0,n_.parseSetCookieHeader)(t);try{let{cookies:A}=await nL();e=await A()}catch(e){if(e instanceof Error&&(e.message.startsWith("`cookies` was called outside a request scope.")||e.message.includes("Cannot find module")))return;throw e}r.forEach((A,t)=>{if(t)try{e.set(t,A.value,(0,n_.toCookieOptions)(A))}catch{}});return}})}]}})]},nU)})(e))),ak}e.s(["getAuth",0,aR],725307);class av extends Error{status;constructor(e,A=401){super(e),this.status=A,this.name="PrincipalResolutionError"}}async function aG(e,A){let t=e.get("x-api-key")?.trim()||null,r=function(e){let A=e.get("authorization");if(!A)return null;if(!A.startsWith("Bearer "))throw new av("Authorization must use the Bearer scheme.");let t=A.slice(7).trim();if(!t)throw new av("The bearer credential is empty.");return t}(e),i=/(?:^|;\s*)(?:__Secure-)?better-auth\.session_token=/.test(e.get("cookie")??"");if(Number(!!t)+Number(!!r)+Number(i)>1)throw new av("Provide exactly one application credential.",400);if(t){let e=await aR(),A=await e.api.verifyApiKey({body:{key:t}});if(!A.valid||!A.key)throw new av("The API key is invalid or inactive.");return{kind:"apiKey",apiKeyId:A.key.id,userId:A.key.referenceId,name:A.key.name??null}}if(r?.startsWith("agent_")){if(!A)throw new av("Agent credentials are not accepted by this endpoint.");let e=await A.authenticate(r);if(!e)throw new av("The agent credential is invalid.");return{kind:"agent",agentId:e}}if(r||i){let A=await aR(),t=await A.api.getSession({headers:e});if(!t?.session||!t.user)throw new av("The session is invalid or expired.");return{kind:"user",userId:t.user.id,email:t.user.email,sessionId:t.session.id}}return{kind:"anonymous"}}e.s(["resolveRequestPrincipal",0,aG],847435)},914710,e=>{"use strict";e.i(725307),e.i(658978),e.i(847435),e.i(525796),e.s([],914710)},737799,e=>{"use strict";e.i(666680),e.i(914710),e.s([])},476314,e=>{"use strict";var A,t=e.i(715224),r=e.i(822196);e.i(198171),e.i(448224);e.i(214928),t.Protocol,e.i(381575),Symbol.for("mcp.completable"),(A||(A={})).Completable="McpCompletable",e.i(749906),e.s([],476314)},423924,e=>e.a(async(A,t)=>{try{e.s([]),e.i(476314);var r=e.i(652085),i=A([r]);[r]=i.then?(await i)():i,t()}catch(e){t(e)}},!1),576565,e=>e.a(async(A,t)=>{try{e.s([]);var r=e.i(504400);e.i(737799),e.i(176985);var i=e.i(423924),n=e.i(652085),a=A([r,i,n]);[r,i,n]=a.then?(await a)():a,t()}catch(e){t(e)}},!1),374421,e=>{"use strict";var A=e.i(666680),t=e.i(380592),r=e.i(135475);let i="server:worktree-automations",n=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"]),a=new Set(["SUCCEEDED","FAILED","CANCELLED"]);function o(e){let[A,t,r]=e.split("/");if(!A||!t||r)throw Error("A GitHub repository must be in owner/name format");return{owner:A,name:t}}function s(e){return{worktreeId:e.worktreeId,state:e.state,conflictWorkflowId:e.conflictWorkflowId,conflictWorkflowChoice:e.conflictWorkflowChoice,lastError:e.lastError,pauseReason:e.pauseReason,lastSyncedAt:e.lastSyncedAt?.toISOString()??null,updatedAt:e.updatedAt.toISOString()}}function l(e){return{...e,mergeMethod:e.mergeMethod,updatedAt:e.updatedAt.toISOString()}}e.s(["WorktreeAutomationService",0,class{worktrees;github;jira;workflows;agentControl;polling;timer;running;rerunRequested;constructor(e,A,r,n,a,o){this.worktrees=e,this.github=A,this.jira=r,this.workflows=n,this.agentControl=a,this.polling=o,this.timer=null,this.running=!1,this.rerunRequested=!1,this.agentControl.registerCompletionObserver(async e=>{e.kind===t.WORKTREE_AUTO_SYNC_JOB_KIND&&this.changed()}),this.polling?.register({id:i,kind:"WORKTREE_AUTOMATION",runtime:"SERVER",enabled:!0,cadenceSeconds:60,details:{}})}startRuntime(){queueMicrotask(()=>void this.reconcile())}schedule(){this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>void this.reconcile(),6e4),this.timer.unref(),this.polling?.schedule(i,new Date(Date.now()+6e4))}changed(){if(this.running){this.rerunRequested=!0;return}this.timer&&clearTimeout(this.timer),this.timer=null,queueMicrotask(()=>void this.reconcile())}async stopAutoSyncWork(e){e?.activeJobId&&await this.agentControl.cancelJob(e.activeJobId).catch(()=>null),e?.workflowRunId&&await this.workflows.lifecycle(e.workflowRunId,"CANCEL").catch(()=>null)}async autoSync(e){let A=await (0,r.getPrismaClient)(),t=await A.worktreeAutoSync.findUnique({where:{worktreeId:e}});return t?s(t):null}async configureAutoSync(e){let A=await (0,r.getPrismaClient)(),t=await A.worktree.findFirst({where:{id:e.worktreeId,missingAt:null},select:{id:!0,branch:!0,codebaseId:!0,codebase:{select:{repositoryId:!0}}}});if(!t?.branch)throw Error("Auto Sync requires a branch");await this.stopAutoSyncWork(await A.worktreeAutoSync.findUnique({where:{worktreeId:t.id},select:{activeJobId:!0,workflowRunId:!0}}));let i=e.conflictWorkflowId?.trim()||null;if(i){let e=await A.workflow.findUnique({where:{id:i},select:{enabled:!0,archivedAt:!0,activeVersionId:!0,quickActionKind:!0,quickActionRepositories:{select:{repositoryId:!0}}}});if(!e?.enabled||e.archivedAt||!e.activeVersionId||"MERGE_CONFLICT"!==e.quickActionKind)throw Error("Select an enabled merge-conflict quick action workflow");if(e.quickActionRepositories.length>0&&!e.quickActionRepositories.some(({repositoryId:e})=>e===t.codebase.repositoryId))throw Error("The merge-conflict workflow is not available for this repository")}let n=await A.worktreeAutoSync.upsert({where:{worktreeId:t.id},create:{worktreeId:t.id,branch:t.branch,conflictWorkflowId:i,conflictWorkflowChoice:e.conflictWorkflowChoice?.trim()||null},update:{state:"ACTIVE",branch:t.branch,conflictWorkflowId:i,conflictWorkflowChoice:e.conflictWorkflowChoice?.trim()||null,activeJobId:null,workflowRunId:null,lastError:null,pauseReason:null}});return this.worktrees.publishAutomationChange(t.id,t.codebaseId),this.changed(),s(n)}async cancelAutoSync(e){let A=await (0,r.getPrismaClient)(),t=await A.worktreeAutoSync.findUnique({where:{worktreeId:e},select:{activeJobId:!0,workflowRunId:!0}});await this.stopAutoSyncWork(t);let i=await A.worktreeAutoSync.deleteMany({where:{worktreeId:e}});return this.worktrees.publishAutomationChange(e),i.count>0}async retryAutoSync(e){let A=await (0,r.getPrismaClient)(),t=await A.worktreeAutoSync.update({where:{worktreeId:e},data:{state:"ACTIVE",activeJobId:null,workflowRunId:null,lastError:null,pauseReason:null}});return this.worktrees.publishAutomationChange(e),this.changed(),s(t)}async autoMerge(e){let A=await (0,r.getPrismaClient)(),t=await A.worktreeAutoMerge.findUnique({where:{worktreeId:e}});return t?l(t):null}async configureAutoMerge(e){let A=await (0,r.getPrismaClient)(),t=await A.worktree.findFirst({where:{id:e.worktreeId,missingAt:null},select:{id:!0,primary:!0,branch:!0,codebaseId:!0,codebase:{select:{repository:{select:{canonicalOrigin:!0}}}}}});if(!t?.branch)throw Error("Auto Merge requires a branch");if(e.deleteWorktree&&t.primary)throw Error("The primary worktree cannot be deleted after merge");let i=await A.worktreeAutoMerge.findUnique({where:{worktreeId:t.id}}),n=await this.worktrees.ticketKeyForWorktree(t.id);if(e.moveTicketToDone){if(!n)throw Error("This worktree is not linked to a Jira ticket");let e=await A.jiraProject.findUnique({where:{key:n.split("-")[0]??""},select:{doneStatusId:!0}});if(!e?.doneStatusId)throw Error("Configure this Jira project's done status before enabling this option")}let a=o(e.repositoryNameWithOwner),s=await this.github.pullRequestAutomationState(a.owner,a.name,e.pullRequestNumber);if(s.headRefName!==t.branch)throw Error("The pull request does not belong to this worktree branch");if(!s.headRepositoryNameWithOwner)throw Error("The pull request head repository is unavailable");if(t.codebase.repository.canonicalOrigin.toLowerCase()!==`github.com/${s.headRepositoryNameWithOwner.toLowerCase()}`)throw Error("The pull request head repository does not match this worktree");let d=!!(i&&(i.repositoryNameWithOwner.toLowerCase()!==e.repositoryNameWithOwner.toLowerCase()||i.pullRequestNumber!==e.pullRequestNumber)),u=!1,c=!1;try{if(i&&d){let e=o(i.repositoryNameWithOwner),A=await this.github.pullRequestAutomationState(e.owner,e.name,i.pullRequestNumber);"OPEN"===A.state&&A.autoMergeEnabled&&(await this.github.disablePullRequestAutoMerge({...e,number:i.pullRequestNumber},"WORKTREE_AUTOMATION"),u=!0)}c=!0,await this.github.enablePullRequestAutoMerge({...a,number:e.pullRequestNumber,method:e.method,commitHeadline:e.commitHeadline,commitBody:e.commitBody,authorEmail:e.authorEmail},"WORKTREE_AUTOMATION");let r=await A.worktreeAutoMerge.upsert({where:{worktreeId:t.id},create:{worktreeId:t.id,repositoryNameWithOwner:e.repositoryNameWithOwner,pullRequestNumber:e.pullRequestNumber,branch:t.branch,mergeMethod:e.method,commitHeadline:e.commitHeadline.trim(),commitBody:e.commitBody,authorEmail:e.authorEmail?.trim()||null,deleteWorktree:e.deleteWorktree,moveTicketToDone:e.moveTicketToDone,ticketKey:n},update:{state:"ACTIVE",repositoryNameWithOwner:e.repositoryNameWithOwner,pullRequestNumber:e.pullRequestNumber,branch:t.branch,mergeMethod:e.method,commitHeadline:e.commitHeadline.trim(),commitBody:e.commitBody,authorEmail:e.authorEmail?.trim()||null,deleteWorktree:e.deleteWorktree,moveTicketToDone:e.moveTicketToDone,ticketKey:n,ticketMovedAt:null,deleteJobId:null,lastError:null}});return this.worktrees.publishAutomationChange(t.id,t.codebaseId),this.changed(),l(r)}catch(A){if(c&&await this.github.disablePullRequestAutoMerge({...a,number:e.pullRequestNumber},"WORKTREE_AUTOMATION").catch(()=>null),i&&(u||!d)){let e=o(i.repositoryNameWithOwner);await this.github.enablePullRequestAutoMerge({...e,number:i.pullRequestNumber,method:i.mergeMethod,commitHeadline:i.commitHeadline,commitBody:i.commitBody,authorEmail:i.authorEmail},"WORKTREE_AUTOMATION").catch(()=>null)}throw A}}async forceAutoSync(e,A){if(!A.trim())throw Error("requestId is required");let t=await (0,r.getPrismaClient)(),i=await t.worktreeAutoSync.findUnique({where:{worktreeId:e}});if(!i||"PAUSED"!==i.state||"PREPARATION_CONFLICT"!==i.pauseReason)throw Error("Auto Sync is not paused for a preparation conflict");let n=await this.worktrees.createAutoSyncJob(e,"SYNC",i.branch,A,!0);return await t.worktreeAutoSync.update({where:{worktreeId:e},data:{state:"SYNCING",activeJobId:n.id,workflowRunId:null,lastError:null,pauseReason:null}}),this.worktrees.publishAutomationChange(e),this.changed(),n}async cancelAutoMerge(e){let A=await (0,r.getPrismaClient)(),t=await A.worktreeAutoMerge.findUnique({where:{worktreeId:e}});if(!t)return!1;let i=o(t.repositoryNameWithOwner),n=await this.github.pullRequestAutomationState(i.owner,i.name,t.pullRequestNumber);return"OPEN"===n.state&&n.autoMergeEnabled&&await this.github.disablePullRequestAutoMerge({...i,number:t.pullRequestNumber},"WORKTREE_AUTOMATION"),await A.worktreeAutoMerge.delete({where:{worktreeId:e}}),this.worktrees.publishAutomationChange(e),!0}async retryAutoMerge(e){let A=await (0,r.getPrismaClient)(),t=await A.worktreeAutoMerge.findUniqueOrThrow({where:{worktreeId:e}}),i=o(t.repositoryNameWithOwner),n="MERGED"===(await this.github.pullRequestAutomationState(i.owner,i.name,t.pullRequestNumber)).state?"POST_MERGE":"ACTIVE",a=await A.worktreeAutoMerge.update({where:{worktreeId:e},data:{state:n,lastError:null,deleteJobId:null}});return this.worktrees.publishAutomationChange(e),this.changed(),l(a)}async reconcile(){if(this.running){this.rerunRequested=!0;return}this.running=!0;try{let e=async()=>{do this.rerunRequested=!1,await this.reconcileAutoSync(),await this.reconcileAutoMerge();while(this.rerunRequested)};this.polling?await this.polling.run(i,e):await e()}catch{}finally{this.running=!1,this.schedule()}}async reconcileAutoSync(){let e=await (0,r.getPrismaClient)();for(let t of(await e.worktreeAutoSync.findMany({where:{state:{in:["ACTIVE","SYNCING","RESOLVING"]}},include:{worktree:{select:{codebaseId:!0}}}})))try{let r=await e.worktree.findUnique({where:{id:t.worktreeId},select:{branch:!0}});if(r?.branch!==t.branch)throw Error("Auto Sync paused because the worktree branch changed");if("ACTIVE"===t.state){let r=await this.worktrees.createAutoSyncJob(t.worktreeId,"SYNC",t.branch,(0,A.randomUUID)());await e.worktreeAutoSync.update({where:{worktreeId:t.worktreeId},data:{state:"SYNCING",activeJobId:r.id,lastError:null,pauseReason:null}});continue}if("RESOLVING"===t.state){if(!t.workflowRunId)throw Error("The conflict workflow run is missing");let r=await this.workflows.run(t.workflowRunId);if(!r||!a.has(r.status))continue;if("SUCCEEDED"!==r.status)throw Error(`The conflict workflow ${r.status.toLowerCase()}`);let i=await this.worktrees.createAutoSyncJob(t.worktreeId,"FINALIZE",t.branch,(0,A.randomUUID)());await e.worktreeAutoSync.update({where:{worktreeId:t.worktreeId},data:{state:"SYNCING",activeJobId:i.id,workflowRunId:null,pauseReason:null}});continue}if(!t.activeJobId)throw Error("The Auto Sync job is missing");let i=await this.agentControl.getJob(t.activeJobId);if(!i||!n.has(i.status))continue;if("SUCCEEDED"!==i.status)throw Error(i.error||`Auto Sync ${i.status.toLowerCase()}`);let o=function(e){if(!e)return null;try{let A=JSON.parse(e);if(!A||"object"!=typeof A||Array.isArray(A))return null;return"string"==typeof A.outcome?String(A.outcome):null}catch{return null}}(i.resultJson);if("PREPARATION_CONFLICT"===o){let A=function(e){if(!e)return[];try{let A=JSON.parse(e);if(!A||"object"!=typeof A||Array.isArray(A))return[];let t=A.preparationConflictPaths;return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}(i.resultJson);await e.worktreeAutoSync.update({where:{worktreeId:t.worktreeId},data:{state:"PAUSED",activeJobId:null,workflowRunId:null,lastError:"Auto Sync paused because repository preparations block the rebase"+(A.length?`: ${A.join(", ")}`:""),pauseReason:"PREPARATION_CONFLICT"}});continue}if("CONFLICT"===o){if(!t.conflictWorkflowId){await e.worktreeAutoSync.update({where:{worktreeId:t.worktreeId},data:{state:"PAUSED",activeJobId:null,workflowRunId:null,lastError:"Auto Sync paused because the rebase has merge conflicts",pauseReason:"REBASE_CONFLICT"}});continue}let A=await this.workflows.trigger({workflowId:t.conflictWorkflowId,resourceKind:"WORKTREE",resourceId:t.worktreeId,subjectKey:`auto-sync:${t.worktreeId}:${i.id}`,choice:t.conflictWorkflowChoice});if(!A)throw Error("The conflict workflow did not start");await e.worktreeAutoSync.update({where:{worktreeId:t.worktreeId},data:{state:"RESOLVING",activeJobId:null,workflowRunId:A.id,lastError:null,pauseReason:null}});continue}if("UNRESOLVED"===o)throw Error("The conflict workflow did not fully resolve the rebase");if("SYNCED"!==o&&"NO_CHANGE"!==o)throw Error("The Auto Sync job returned an unknown result");await e.worktreeAutoSync.update({where:{worktreeId:t.worktreeId},data:{state:"ACTIVE",activeJobId:null,workflowRunId:null,lastError:null,pauseReason:null,..."SYNCED"===o?{lastSyncedAt:new Date}:{}}})}catch(n){let A=n instanceof Error?n.message:String(n),r=/offline|busy|already has an active job|temporarily/i.test(A),i=/branch changed/i.test(A)?"BRANCH_CHANGED":"ERROR";await e.worktreeAutoSync.updateMany({where:{worktreeId:t.worktreeId},data:{state:r?"ACTIVE":"PAUSED",activeJobId:null,workflowRunId:null,lastError:A,pauseReason:r?null:i}})}finally{this.worktrees.publishAutomationChange(t.worktreeId,t.worktree.codebaseId)}}async reconcileAutoMerge(){let e=await (0,r.getPrismaClient)();for(let t of(await e.worktreeAutoMerge.findMany({where:{state:{in:["ACTIVE","POST_MERGE"]}},include:{worktree:{select:{codebaseId:!0,branch:!0,headSha:!0,primary:!0}}}})))try{let r=o(t.repositoryNameWithOwner);if("ACTIVE"===t.state){let A=await this.github.pullRequestAutomationState(r.owner,r.name,t.pullRequestNumber);if("MERGED"===A.state)await e.worktreeAutoMerge.update({where:{worktreeId:t.worktreeId},data:{state:"POST_MERGE",lastError:null}}),this.rerunRequested=!0;else if("OPEN"!==A.state)throw Error("The pull request closed without merging");else if(!A.autoMergeEnabled)throw Error("GitHub Auto Merge is no longer enabled");continue}if(t.moveTicketToDone&&t.ticketKey&&!t.ticketMovedAt&&(await this.jira.transitionTicketToConfiguredDone(t.ticketKey),await e.worktreeAutoMerge.update({where:{worktreeId:t.worktreeId},data:{ticketMovedAt:new Date,lastError:null}})),!t.deleteWorktree){await e.worktreeAutoMerge.update({where:{worktreeId:t.worktreeId},data:{state:"COMPLETED",lastError:null}});continue}if(t.worktree.primary)throw Error("The primary worktree cannot be deleted");if(!t.deleteJobId){let i=await this.github.pullRequestAutomationState(r.owner,r.name,t.pullRequestNumber);if("MERGED"!==i.state)throw Error("The pull request is no longer merged");if(i.headRefName!==t.branch)throw Error("The merged pull request branch does not match the Auto Merge rule");if(t.worktree.branch!==t.branch)throw Error("The worktree branch changed after Auto Merge completed");if(!t.worktree.headSha||t.worktree.headSha!==i.headRefOid)throw Error("The worktree HEAD does not match the merged pull request");let n=await this.worktrees.deleteWorktree({worktreeId:t.worktreeId,deleteRemoteBranch:!1,requireClean:!0,expectedBranch:t.branch,expectedHeadSha:i.headRefOid,requestId:`auto-merge-${(0,A.randomUUID)()}`});await e.worktreeAutoMerge.update({where:{worktreeId:t.worktreeId},data:{deleteJobId:n.id,lastError:null}});continue}let i=await this.agentControl.getJob(t.deleteJobId);if(!i||!n.has(i.status))continue;if("SUCCEEDED"!==i.status)throw Error(i.error||`Worktree deletion ${i.status.toLowerCase()}`);await e.worktreeAutoMerge.updateMany({where:{worktreeId:t.worktreeId},data:{state:"COMPLETED",lastError:null}})}catch(A){await e.worktreeAutoMerge.updateMany({where:{worktreeId:t.worktreeId},data:{state:"ACTION_REQUIRED",lastError:A instanceof Error?A.message:String(A)}})}finally{this.worktrees.publishAutomationChange(t.worktreeId,t.worktree.codebaseId)}}}])},741193,e=>{"use strict";e.i(520962),e.i(374421),e.s([])},593464,e=>{"use strict";var A=e.i(666680),t=e.i(750227),r=e.i(904342),i=e.i(135475);e.i(256554);var n=e.i(848201);function a(e,A){let t=[],r=e.includes("CLAUDE");return r&&t.push("CLAUDE"),(e.includes("CODEX")||!r&&e.length>0||"GLOBAL"===A&&e.includes("GITHUB_COPILOT"))&&t.push("AGENTS"),t}let o="default",s=["PREPARING","READY","APPLYING","NEEDS_RESOLUTION"],l=["SCAN","READ"],d=[...l,"APPLY"],u={files:{orderBy:{path:"asc"}},groups:{include:{group:!0}}},c={skills:{include:{skill:{include:{files:!0}}}},repositories:{include:{repository:!0}}};function h(e,A){if(!e)return A;try{return JSON.parse(e)}catch{return A}}function g(e){return[...e.cursorEnabled?["CURSOR"]:[],...e.githubCopilotEnabled?["GITHUB_COPILOT"]:[],...e.codexEnabled?["CODEX"]:[],...e.claudeEnabled?["CLAUDE"]:[],...e.openCodeEnabled?["OPENCODE"]:[]]}function p(e,A){return"AGENTS"===A?[".agents","skills"]:"CLAUDE"===A?[".claude","skills"]:"GLOBAL"===e?"CURSOR"===A?[".cursor","skills"]:"GITHUB_COPILOT"===A?[".copilot","skills"]:"CODEX_LEGACY"===A?[".codex","skills"]:[".config","opencode","skills"]:"CURSOR"===A?[".cursor","skills"]:"GITHUB_COPILOT"===A?[".github","skills"]:"CODEX_LEGACY"===A?[".codex","skills"]:[".opencode","skills"]}function C(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")?t.win32:t.posix}function f(e,...A){return C(e).join(e,...A)}function I(e){return C(e).dirname(e)}e.s(["SkillsService",0,class{agentControl;constructor(e){this.agentControl=e,this.agentControl.registerCompletionHandler(r.SKILL_SCAN_JOB_KIND,e=>this.completeScan(e)),this.agentControl.registerCompletionHandler(r.SKILL_READ_JOB_KIND,e=>this.completeRead(e)),this.agentControl.registerCompletionHandler(r.SKILL_APPLY_JOB_KIND,e=>this.completeApply(e)),this.agentControl.registerConnectionHandler(async()=>{await this.requestAutoReconcile()})}publish(e){n.agentEventBus.publish(n.SKILLS_CHANGED_TOPIC,{id:e??null}),e&&n.agentEventBus.publish((0,n.skillSyncRunTopic)(e),{id:e})}subscribe(){return n.agentEventBus.iterate(n.SKILLS_CHANGED_TOPIC)}subscribeRun(e){return n.agentEventBus.iterate((0,n.skillSyncRunTopic)(e))}async settings(){return(await (0,i.getPrismaClient)()).skillSettings.upsert({where:{id:o},create:{id:o},update:{}})}async listSkills(e=""){let A=await (0,i.getPrismaClient)(),t=e.trim().toLocaleLowerCase(),r=await A.skill.findMany({where:{deletedAt:null},include:{groups:u.groups,files:{orderBy:{path:"asc"},omit:{contents:!0}}},orderBy:{name:"asc"}});return t?r.filter(e=>[e.name,e.description,...e.groups.map(({group:e})=>e.name)].some(e=>e.toLocaleLowerCase().includes(t))):r}async listGroups(){return(await (0,i.getPrismaClient)()).skillGroup.findMany({include:c,orderBy:{name:"asc"}})}async getGroup(e){return(await (0,i.getPrismaClient)()).skillGroup.findUnique({where:{id:e},include:c})}async observations(){return(await (0,i.getPrismaClient)()).skillToolObservation.findMany({include:{agent:!0},orderBy:[{tool:"asc"},{agent:{name:"asc"}}]})}async installations(e=""){let A=await (0,i.getPrismaClient)(),t=e.trim().toLocaleLowerCase(),r=await A.skillInstallation.findMany({where:{present:!0},include:{agent:!0,codebase:{include:{repository:!0}},worktree:!0,baseline:!0,skill:!0},orderBy:[{skillName:"asc"},{rootPath:"asc"}]});return t?r.filter(e=>[e.skillName,e.description,e.agent.name,e.rootPath,e.codebase?.repository.name??""].some(e=>e.toLocaleLowerCase().includes(t))):r}async repositories(){return(await (0,i.getPrismaClient)()).codebaseRepository.findMany({orderBy:{name:"asc"}})}async fileContents(e){let A=await (0,i.getPrismaClient)();return(await A.skillFile.findUniqueOrThrow({where:{id:e},select:{contents:!0}})).contents}async overview(e=""){let[A,t,r,i,n,a]=await Promise.all([this.listSkills(e),this.listGroups(),this.observations(),this.installations(e),this.settings(),this.repositories()]);return{skills:A,groups:t,observations:r,installations:i,settings:n,repositories:a}}async getSkill(e){return(await (0,i.getPrismaClient)()).skill.findFirst({where:{id:e,deletedAt:null},include:u})}async saveSkill(e){let t,n=(t=e.files.map(e=>({path:e.path,contentsBase64:e.contentsBase64,executable:e.executable})),(0,r.parseSkillPackage)({name:e.name,description:e.description,packageHash:(0,r.hashSkillFiles)(t),files:t})),a=[...new Set(e.groupIds)].slice(0,100),o=await (0,i.getPrismaClient)();if(await o.skillGroup.count({where:{id:{in:a}}})!==a.length)throw Error("One or more skill groups were not found");let s=await o.skill.findUnique({where:{name:n.name}});if(s&&s.id!==e.id)throw Error("Skill names must be unique");let l=e.id??(0,A.randomUUID)(),d=e.id?await o.skillGroupSkill.findMany({where:{skillId:l},select:{groupId:!0}}):[];return await o.$transaction(async t=>{await t.skill.upsert({where:{id:l},create:{id:l,name:n.name,description:n.description,syncGlobally:e.syncGlobally,packageHash:n.packageHash},update:{name:n.name,description:n.description,syncGlobally:e.syncGlobally,packageHash:n.packageHash,deletedAt:null}}),await t.skillFile.deleteMany({where:{skillId:l}}),await t.skillFile.createMany({data:n.files.map(e=>{let t=Buffer.from(e.contentsBase64,"base64");return{id:(0,A.randomUUID)(),skillId:l,path:e.path,contents:t,executable:e.executable,contentHash:(0,A.createHash)("sha256").update(t).digest("hex")}})}),await t.skillGroupSkill.deleteMany({where:{skillId:l}}),a.length&&await t.skillGroupSkill.createMany({data:a.map(e=>({groupId:e,skillId:l}))})}),this.publish(),await this.scheduleAutoSync([...a,...d.map(e=>e.groupId)]),await this.getSkill(l)}async deleteSkill(e){let A=await (0,i.getPrismaClient)(),t=await A.skill.findUnique({where:{id:e},include:{groups:!0}});return!!t&&(await A.skill.update({where:{id:e},data:{deletedAt:new Date}}),this.publish(),await this.scheduleAutoSync(t.groups.map(e=>e.groupId)),!0)}async saveGroup(e){let t=e.name.trim();if(!t||t.length>80)throw Error("Group names must contain 1-80 characters");let r=[...new Set(e.skillIds)].slice(0,500),n=[...new Set(e.repositoryIds)].slice(0,500),a=await (0,i.getPrismaClient)(),[o,s,l]=await Promise.all([a.skill.count({where:{id:{in:r},deletedAt:null}}),a.codebaseRepository.count({where:{id:{in:n}}}),a.skillGroup.findUnique({where:{name:t}})]);if(o!==r.length)throw Error("One or more skills were not found");if(s!==n.length)throw Error("One or more repositories were not found");if(l&&l.id!==e.id)throw Error("Group names must be unique");let d=e.id??(0,A.randomUUID)();return await a.$transaction(async e=>{await e.skillGroup.upsert({where:{id:d},create:{id:d,name:t},update:{name:t}}),await e.skillGroupSkill.deleteMany({where:{groupId:d}}),await e.codebaseRepositorySkillGroup.deleteMany({where:{groupId:d}}),r.length&&await e.skillGroupSkill.createMany({data:r.map(e=>({groupId:d,skillId:e}))}),n.length&&await e.codebaseRepositorySkillGroup.createMany({data:n.map(e=>({groupId:d,repositoryId:e}))})}),this.publish(),await this.scheduleAutoSync([d]),a.skillGroup.findUniqueOrThrow({where:{id:d},include:c})}async validateGroupIds(e){let A=[...new Set(e)].slice(0,100),t=await (0,i.getPrismaClient)();if(await t.skillGroup.count({where:{id:{in:A}}})!==A.length)throw Error("One or more skill groups were not found");return A}async groupsForRepository(e){let A=await (0,i.getPrismaClient)();return(await A.codebaseRepositorySkillGroup.findMany({where:{repositoryId:e},include:{group:!0},orderBy:{group:{name:"asc"}}})).map(e=>e.group)}async deleteGroup(e){let A=await (0,i.getPrismaClient)(),t=await A.skillGroup.deleteMany({where:{id:e}});return t.count&&this.publish(),t.count&&(await this.settings()).autoSyncProjectGroups&&await this.prepareSync("GROUP",null,!0),t.count>0}async saveSettings(e){let A=await (0,i.getPrismaClient)(),t=await A.skillSettings.upsert({where:{id:o},create:{id:o,...e},update:e});return this.publish(),t.autoSyncProjectGroups&&await this.prepareSync("GROUP",null,!0),t}async setRepositoryGroups(e,A){let t=await this.validateGroupIds(A),r=await (0,i.getPrismaClient)();await r.$transaction(async A=>{await A.codebaseRepositorySkillGroup.deleteMany({where:{repositoryId:e}}),t.length&&await A.codebaseRepositorySkillGroup.createMany({data:t.map(A=>({repositoryId:e,groupId:A}))})}),this.publish(),(await this.settings()).autoSyncProjectGroups&&await this.prepareSync("GROUP",null,!0)}async scheduleAutoSync(e){if((await this.settings()).autoSyncProjectGroups&&e.length)for(let A of[...new Set(e)])await this.prepareSync("GROUP",A,!0)}async requestAutoReconcile(){return(await this.settings()).autoSyncProjectGroups?this.prepareSync("GROUP",null,!0):null}async targets(e){let A=await (0,i.getPrismaClient)(),t=await A.codebase.findMany({where:{agentId:e,availability:"AVAILABLE"},include:{worktrees:{where:{missingAt:null}}}}),r=new Map;for(let e of t)for(let A of(r.set(e.folder,{codebaseId:e.id,worktreeId:null,folder:e.folder}),e.worktrees))r.set(A.folder,{codebaseId:e.id,worktreeId:A.id,folder:A.folder});return[...r.values()]}async prepareSync(e,t,n=!1){let a=await (0,i.getPrismaClient)();if(t&&!await a.skillGroup.findUnique({where:{id:t}}))throw Error("Skill group not found");if(n){let A=await a.skillSyncRun.findFirst({where:{kind:e,groupId:t??null,status:{in:s}},orderBy:{createdAt:"desc"}});if(A)return A}let o=await a.skillSyncRun.create({data:{id:(0,A.randomUUID)(),kind:e,groupId:t??null,automatic:n,status:"PREPARING"}}),l=g(await this.settings()),d=await a.agent.findMany({orderBy:{name:"asc"}});for(let e of d){let t=await a.skillSyncItem.create({data:{id:(0,A.randomUUID)(),runId:o.id,agentId:e.id,direction:"SCAN",status:"PENDING"}});await this.agentControl.createJob({agentId:e.id,kind:r.SKILL_SCAN_JOB_KIND,payload:{tools:l,targets:await this.targets(e.id),syncRunId:o.id,syncItemId:t.id},idempotencyKey:`skills:scan:${o.id}:${e.id}`,timeoutSeconds:300,visibility:n?"SYSTEM":"USER"})}return!d.length&&(await a.skillSyncRun.update({where:{id:o.id},data:{status:"READY"}}),n)?this.applyRun(o.id):(this.publish(o.id),this.getRun(o.id))}async getRun(e){return(await (0,i.getPrismaClient)()).skillSyncRun.findUnique({where:{id:e},include:{group:!0,items:{include:{skill:!0,installation:{include:{agent:!0}},agent:!0},orderBy:{createdAt:"asc"}}}})}completionIds(e){return h(e.payloadJson,{})}async completeScan(e){let{syncRunId:t,syncItemId:n}=this.completionIds(e);if(!t||!n)return;let a=await (0,i.getPrismaClient)();if(await a.skillSyncItem.findFirst({where:{id:n,runId:t,direction:"SCAN",status:"PENDING"}})){if("SUCCEEDED"===e.status&&e.resultJson){let t=h(e.resultJson,{configuredTools:[],installations:[],warnings:[]}),i=new Date;await a.$transaction(async a=>{for(let A of(await a.skillInstallation.updateMany({where:{agentId:e.agentId},data:{present:!1}}),t.configuredTools))r.AI_TOOLS.includes(A.tool)&&await a.skillToolObservation.upsert({where:{agentId_tool:{agentId:e.agentId,tool:A.tool}},create:{agentId:e.agentId,tool:A.tool,configured:A.configured,homePath:A.homePath,checkedAt:i},update:{configured:A.configured,homePath:A.homePath,checkedAt:i}});for(let r of t.installations){let t=await a.skill.findUnique({where:{name:r.skillName},select:{id:!0,deletedAt:!0}});await a.skillInstallation.upsert({where:{agentId_rootPath_skillName:{agentId:e.agentId,rootPath:r.rootPath,skillName:r.skillName}},create:{id:(0,A.randomUUID)(),agentId:e.agentId,skillId:t&&!t.deletedAt?t.id:null,codebaseId:r.codebaseId,worktreeId:r.worktreeId,scope:r.scope,rootKind:r.rootKind,rootPath:r.rootPath,skillName:r.skillName,description:r.description,packageHash:r.packageHash,present:!0,fileCount:r.fileCount,totalBytes:r.totalBytes,tracked:r.tracked,consumersJson:JSON.stringify(r.consumers),lastSeenAt:i},update:{skillId:t&&!t.deletedAt?t.id:void 0,codebaseId:r.codebaseId,worktreeId:r.worktreeId,scope:r.scope,rootKind:r.rootKind,description:r.description,packageHash:r.packageHash,present:!0,fileCount:r.fileCount,totalBytes:r.totalBytes,tracked:r.tracked,consumersJson:JSON.stringify(r.consumers),lastSeenAt:i}})}await a.skillSyncItem.updateMany({where:{id:n,status:"PENDING"},data:{status:"COMPLETE",error:t.warnings?.length?t.warnings.join("\n").slice(0,64e3):null}})})}else await a.skillSyncItem.updateMany({where:{id:n,status:"PENDING"},data:{status:"FAILED",error:e.error??"Skill scan failed"}});await a.skillSyncItem.count({where:{runId:t,direction:"SCAN",status:"PENDING"}})||await this.buildPlan(t),this.publish(t)}}async configuredByAgent(){let e=await (0,i.getPrismaClient)(),A=new Set(g(await this.settings())),t=await e.skillToolObservation.findMany({where:{configured:!0}}),r=new Map;for(let e of t){if(!A.has(e.tool))continue;let t=r.get(e.agentId)??[];t.push(e.tool),r.set(e.agentId,t)}return r}async desiredLocations(e,A=new Set){let t=await (0,i.getPrismaClient)(),r=await this.configuredByAgent(),n=await t.skillToolObservation.findMany({where:{configured:!0}}),o=new Map;for(let e of n)o.set(e.agentId,e.homePath);let s=[];if("ALL"===e.kind){let e=await t.skill.findMany({where:{deletedAt:null,syncGlobally:!0},include:u});for(let[t,i]of r){if(A.has(t))continue;let r=o.get(t);if(r)for(let A of a(i,"GLOBAL")){let i=f(r,...p("GLOBAL",A));for(let r of e)s.push({skill:r,agentId:t,codebaseId:null,worktreeId:null,scope:"GLOBAL",rootKind:A,folder:null,rootPath:i,targetPath:f(i,r.name)})}}}for(let i of(await t.skillGroup.findMany({where:"GROUP"===e.kind&&e.groupId?{id:e.groupId}:void 0,include:{skills:{where:{skill:{deletedAt:null}},include:{skill:{include:u}}},repositories:{include:{repository:{include:{codebases:{where:{availability:"AVAILABLE"},include:{worktrees:{where:{missingAt:null}}}}}}}}}})))for(let e of i.repositories)for(let t of e.repository.codebases){if(A.has(t.agentId))continue;let e=a(r.get(t.agentId)??[],"PROJECT");for(let A of[{folder:t.folder,worktreeId:null},...t.worktrees.map(e=>({folder:e.folder,worktreeId:e.id}))])for(let r of e){let e=f(A.folder,...p("PROJECT",r));for(let n of i.skills)s.push({skill:n.skill,agentId:t.agentId,codebaseId:t.id,worktreeId:A.worktreeId,scope:"PROJECT",rootKind:r,folder:A.folder,rootPath:e,targetPath:f(e,n.skill.name)})}}return[...new Map(s.map(e=>[`${e.agentId}\0${e.targetPath}`,e])).values()]}installationWhere(e,A){return{present:!0,...A.size?{agentId:{notIn:[...A]}}:{},..."GROUP"===e.kind?{scope:"PROJECT",...e.groupId?{codebase:{repository:{skillGroups:{some:{groupId:e.groupId}}}}}:{}}:{}}}async buildPlan(e){let t=await (0,i.getPrismaClient)(),n=await t.skillSyncRun.findUniqueOrThrow({where:{id:e}}),a=new Set((await t.skillSyncItem.findMany({where:{runId:e,direction:"SCAN",status:"SKIPPED"},select:{agentId:!0}})).flatMap(e=>e.agentId?[e.agentId]:[]));await t.skillSyncItem.deleteMany({where:{runId:e,direction:{not:"SCAN"}}});let[o,s,l,d,c]=await Promise.all([t.skill.findMany({where:{deletedAt:null},include:u}),t.skill.findMany({where:{deletedAt:{not:null}}}),t.skillInstallation.findMany({where:this.installationWhere(n,a),include:{baseline:!0}}),this.desiredLocations(n,a),"GROUP"===n.kind&&n.groupId?this.desiredLocations({...n,groupId:null},a):this.desiredLocations(n,a)]),h=new Map(o.map(e=>[e.name,e])),p=new Map(o.map(e=>[e.id,e])),C=new Map(s.map(e=>[e.name,e])),f=new Map(s.map(e=>[e.id,e])),I=new Map;for(let e of l){let A=I.get(e.skillName)??[];A.push(e.packageHash),I.set(e.skillName,A)}let w=new Set([...I].flatMap(([e,A])=>{var t;return(t=h.get(e)?.packageHash??null,new Set(A.filter(e=>null===t||e!==t)).size>1)?[e]:[]})),m=[];for(let t of d)l.find(e=>e.agentId===t.agentId&&e.rootPath===t.rootPath&&e.skillName===t.skill.name)||m.push({id:(0,A.randomUUID)(),runId:e,skillId:t.skill.id,agentId:t.agentId,direction:"EXPORT",status:"READY",sourceHash:t.skill.packageHash,candidatePackageJson:JSON.stringify({location:t})});for(let r of l){let i=r.baseline?.skillId??r.skillId,n=(i?p.get(i):void 0)??h.get(r.skillName),a=(i?f.get(i):void 0)??C.get(r.skillName),o=!!r.baseline&&!!n&&n.name!==r.skillName,s=d.find(e=>e.agentId===r.agentId&&e.rootPath===r.rootPath&&e.skill.name===r.skillName),l=c.find(e=>e.agentId===r.agentId&&e.rootPath===r.rootPath&&e.skill.name===r.skillName);n&&r.packageHash===n.packageHash&&!r.baseline&&await t.skillSyncBaseline.upsert({where:{installationId:r.id},create:{id:(0,A.randomUUID)(),installationId:r.id,skillId:n.id,packageHash:n.packageHash},update:{skillId:n.id,packageHash:n.packageHash,syncedAt:new Date}});let u="UNCHANGED",g="COMPLETE";if(a&&r.baseline&&!r.tracked)u="DELETE_MANAGED",g="READY";else if(o)u=r.tracked?"CONFLICT":"DELETE_MANAGED",g=r.tracked?"BLOCKED":"READY";else if(l||!r.baseline||r.tracked)if(n)if(r.packageHash!==n.packageHash){var E;g="CONFLICT"===(u=w.has(r.skillName)?"CONFLICT":(E={databaseHash:n.packageHash,targetHash:r.packageHash,baselineHash:r.baseline?.packageHash??null,tracked:r.tracked}).databaseHash===E.targetHash?"UNCHANGED":E.tracked?"CONFLICT":E.baselineHash===E.databaseHash?"IMPORT":E.baselineHash===E.targetHash?"EXPORT":"CONFLICT")?"BLOCKED":"READY"}else!l&&["CURSOR","GITHUB_COPILOT","CODEX_LEGACY","OPENCODE"].includes(r.rootKind)&&c.some(e=>e.agentId===r.agentId&&e.scope===r.scope&&("GLOBAL"===r.scope||e.codebaseId===r.codebaseId&&e.worktreeId===r.worktreeId)&&e.skill.name===r.skillName&&e.skill.packageHash===r.packageHash)&&!r.tracked&&(u="DELETE_REDUNDANT",g="READY");else g="CONFLICT"==(u=w.has(r.skillName)?"CONFLICT":"IMPORT")||"PROJECT"===r.scope?"BLOCKED":"READY";else u="DELETE_MANAGED",g="READY";m.push({id:(0,A.randomUUID)(),runId:e,skillId:n?.id??a?.id??null,installationId:r.id,agentId:r.agentId,direction:u,status:g,sourceHash:n?.packageHash??null,targetHash:r.packageHash,candidatePackageJson:JSON.stringify({location:{scope:r.scope,rootKind:r.rootKind,folder:"PROJECT"===r.scope?s?.folder??null:null,skillName:r.skillName},projectGroupRequired:!n&&"PROJECT"===r.scope})})}m.length&&await t.skillSyncItem.createMany({data:m});let y=await t.skillSyncItem.findMany({where:{runId:e,installationId:{not:null},direction:{in:["IMPORT","CONFLICT"]}},include:{installation:!0}}),B=new Map;for(let e of y){if(!e.agentId||!e.installation)continue;let A=B.get(e.agentId)??[];A.push(e),B.set(e.agentId,A)}let Q=g(await this.settings());for(let[i,n]of B){let a=await t.skillSyncItem.create({data:{id:(0,A.randomUUID)(),runId:e,agentId:i,direction:"READ",status:"PENDING"}}),o=await this.targets(i);await this.agentControl.createJob({agentId:i,kind:r.SKILL_READ_JOB_KIND,payload:{tools:Q,targets:o,requests:n.map(e=>({scope:e.installation.scope,rootKind:e.installation.rootKind,folder:"PROJECT"===e.installation.scope?o.find(A=>A.codebaseId===e.installation.codebaseId&&A.worktreeId===e.installation.worktreeId)?.folder??null:null,skillName:e.installation.skillName})),syncRunId:e,syncItemId:a.id},idempotencyKey:`skills:read:${e}:${i}`,timeoutSeconds:300})}await this.refreshRunStatus(e)}async completeRead(e){let{syncRunId:A,syncItemId:t}=this.completionIds(e);if(!A||!t)return;let r=await (0,i.getPrismaClient)();if(await r.skillSyncItem.findFirst({where:{id:t,runId:A,direction:"READ",status:"PENDING"}})){if("SUCCEEDED"===e.status&&e.resultJson){let i=h(e.resultJson,{packages:[]}),n=await r.skillSyncItem.findMany({where:{runId:A,agentId:e.agentId,installationId:{not:null},direction:{in:["IMPORT","CONFLICT"]}},include:{installation:!0}});for(let e of i.packages){let A=n.find(A=>A.installation?.skillName===e.package.name&&A.installation?.rootKind===e.rootKind&&A.installation?.scope===e.scope&&("GLOBAL"===e.scope||A.installation?.rootPath===f(e.folder,...p("PROJECT",e.rootKind))));if(!A)continue;let t=h(A.candidatePackageJson,{});await r.skillSyncItem.update({where:{id:A.id},data:{candidatePackageJson:JSON.stringify({...t,package:e.package})}})}await r.skillSyncItem.updateMany({where:{id:t,status:"PENDING"},data:{status:"COMPLETE"}})}else await r.skillSyncItem.updateMany({where:{id:t,status:"PENDING"},data:{status:"FAILED",error:e.error??"Skill package read failed"}});await this.refreshRunStatus(A),this.publish(A)}}async refreshRunStatus(e){let A=await (0,i.getPrismaClient)(),t=await A.skillSyncItem.findMany({where:{runId:e}});if(t.some(e=>l.includes(e.direction)&&"PENDING"===e.status))return;let r=t.some(e=>"BLOCKED"===e.status),n=t.some(e=>"FAILED"===e.status),a=r?"NEEDS_RESOLUTION":n?"PARTIAL":"READY",o=await A.skillSyncRun.update({where:{id:e},data:{status:a}});this.publish(e),o.automatic&&"READY"===a&&await this.applyRun(e)}async skipPending(e){let A=await (0,i.getPrismaClient)();await A.skillSyncRun.findUniqueOrThrow({where:{id:e}});let t=await A.skillSyncItem.findMany({where:{runId:e,direction:{in:d},status:"PENDING",agentId:{not:null}}}),r=[];for(let i of t){if(1!==(await A.skillSyncItem.updateMany({where:{id:i.id,status:"PENDING"},data:{status:"SKIPPED",resolution:"SKIP"}})).count||!i.agentId)continue;r.push(i);let t=await A.agentJob.findUnique({where:{agentId_idempotencyKey:{agentId:i.agentId,idempotencyKey:`skills:${i.direction.toLowerCase()}:${e}:${i.agentId}`}}});t&&await this.agentControl.cancelJob(t.id)}if(!r.length)return this.getRun(e);let n=[...new Set(r.flatMap(e=>"READ"===e.direction&&e.agentId?[e.agentId]:[]))];n.length&&await A.skillSyncItem.updateMany({where:{runId:e,agentId:{in:n},direction:{notIn:d},status:{in:["READY","BLOCKED"]}},data:{status:"SKIPPED",resolution:"SKIP"}});let a=r.filter(e=>"APPLY"===e.direction),o=a.flatMap(e=>{let{deployments:A=[]}=h(e.candidatePackageJson,{});return A.map(e=>e.id)});return o.length&&await A.skillDeployment.updateMany({where:{id:{in:o},status:"PENDING"},data:{status:"SKIPPED"}}),r.some(e=>"SCAN"===e.direction)?await A.skillSyncItem.count({where:{runId:e,direction:"SCAN",status:"PENDING"}})||await this.buildPlan(e):n.length&&await this.refreshRunStatus(e),a.length&&(await A.skillSyncItem.count({where:{runId:e,direction:"APPLY",status:"PENDING"}})||await A.skillSyncRun.update({where:{id:e},data:{status:"PARTIAL",finishedAt:new Date}})),this.publish(e),this.getRun(e)}async resolveItem(e){let A=await (0,i.getPrismaClient)(),t=await A.skillSyncItem.findUniqueOrThrow({where:{id:e.itemId}});if(!["BLOCKED","READY"].includes(t.status))throw Error("Sync item cannot be resolved");let n=h(t.candidatePackageJson,{});if("MANUAL"===e.resolution&&(n.package=(0,r.parseSkillPackage)(e.package,"manual resolution package")),"TARGET"===e.resolution&&!n.package)throw Error("The target package is unavailable");if("DELETE"===e.resolution&&!t.installationId)throw Error("The client skill installation is unavailable");if(n.projectGroupRequired&&["TARGET","MANUAL"].includes(e.resolution)){if(!e.groupId||!await A.skillGroup.findUnique({where:{id:e.groupId}}))throw Error("A project skill import requires a skill group");n.groupId=e.groupId}if(await A.skillSyncItem.update({where:{id:t.id},data:{resolution:e.resolution,direction:"DELETE"===e.resolution?"DELETE_REDUNDANT":t.direction,candidatePackageJson:JSON.stringify(n),status:"SKIP"===e.resolution?"SKIPPED":"READY"}}),["TARGET","MANUAL"].includes(e.resolution)){let e=n.package?.name??null;if(e){let r=(await A.skillSyncItem.findMany({where:{runId:t.runId,id:{not:t.id},direction:"CONFLICT",status:{in:["BLOCKED","READY"]}},include:{skill:!0,installation:!0}})).flatMap(A=>(A.skill?.name??A.installation?.skillName)===e?[A.id]:[]);r.length&&await A.skillSyncItem.updateMany({where:{id:{in:r}},data:{resolution:"DATABASE",status:"READY"}})}}return await this.refreshRunStatus(t.runId),this.getRun(t.runId)}async importCandidates(e){let t=await (0,i.getPrismaClient)();for(let r of(await t.skillSyncItem.findMany({where:{runId:e,status:"READY",OR:[{direction:"IMPORT"},{direction:"CONFLICT",resolution:{in:["TARGET","MANUAL"]}}]},include:{installation:!0}}))){let e=h(r.candidatePackageJson,{});if(!e.package)continue;let i=await t.skill.findUnique({where:{name:e.package.name},include:u}),n=await this.saveSkill({id:i?.id,name:e.package.name,description:e.package.description,syncGlobally:i?.syncGlobally??!e.groupId,groupIds:[...i?.groups.map(e=>e.groupId)??[],...e.groupId?[e.groupId]:[]],files:e.package.files});r.installationId&&(await t.skillInstallation.update({where:{id:r.installationId},data:{skillId:n.id}}),r.targetHash===n.packageHash&&await t.skillSyncBaseline.upsert({where:{installationId:r.installationId},create:{id:(0,A.randomUUID)(),installationId:r.installationId,skillId:n.id,packageHash:n.packageHash},update:{skillId:n.id,packageHash:n.packageHash,syncedAt:new Date}}))}}async applyRun(e){let t=await (0,i.getPrismaClient)(),n=await t.skillSyncRun.findUniqueOrThrow({where:{id:e}});if(await t.skillSyncItem.count({where:{runId:e,status:"BLOCKED"}}))throw Error("Resolve all conflicts before applying sync");await this.importCandidates(e);let a=new Set((await t.skillSyncItem.findMany({where:{runId:e,direction:{in:l},status:"SKIPPED"},select:{agentId:!0}})).flatMap(e=>e.agentId?[e.agentId]:[])),o=await this.desiredLocations(n,a),s=await t.skillInstallation.findMany({where:this.installationWhere(n,a)}),d=new Map,u=new Map,c=(e,A)=>{let t=d.get(e)??[];t.push(A),d.set(e,t)},h=(e,A)=>{let t=u.get(e)??[];t.push(A),u.set(e,t)};for(let e of o){let r=s.find(A=>A.agentId===e.agentId&&A.rootPath===e.rootPath&&A.skillName===e.skill.name);if(r?.packageHash===e.skill.packageHash||r?.tracked)continue;c(e.agentId,{kind:"WRITE",scope:e.scope,rootKind:e.rootKind,folder:e.folder,package:function(e){let A=e.files.map(e=>({path:e.path,contentsBase64:Buffer.from(e.contents).toString("base64"),executable:e.executable}));return{name:e.name,description:e.description,packageHash:e.packageHash,files:A}}(e.skill),manageGitExclude:"PROJECT"===e.scope});let i=await t.skillDeployment.upsert({where:{agentId_targetPath:{agentId:e.agentId,targetPath:e.targetPath}},create:{id:(0,A.randomUUID)(),skillId:e.skill.id,agentId:e.agentId,codebaseId:e.codebaseId,worktreeId:e.worktreeId,scope:e.scope,rootKind:e.rootKind,targetPath:e.targetPath,desiredHash:e.skill.packageHash,status:"PENDING"},update:{skillId:e.skill.id,desiredHash:e.skill.packageHash,status:"PENDING",lastError:null}});h(e.agentId,{id:i.id,desiredHash:e.skill.packageHash})}let g=await t.skillSyncItem.findMany({where:{runId:e,direction:{in:["DELETE_REDUNDANT","DELETE_MANAGED"]},status:"READY"},include:{installation:!0}}),p=new Set(g.flatMap(e=>e.installationId?[e.installationId]:[])),C=s.filter(e=>!p.has(e.id)&&!e.tracked&&["CURSOR","GITHUB_COPILOT","CODEX_LEGACY","OPENCODE"].includes(e.rootKind)&&!o.some(A=>A.agentId===e.agentId&&A.rootPath===e.rootPath&&A.skill.name===e.skillName)&&o.some(A=>A.agentId===e.agentId&&A.scope===e.scope&&("GLOBAL"===e.scope||A.codebaseId===e.codebaseId&&A.worktreeId===e.worktreeId)&&A.skill.name===e.skillName&&A.skill.packageHash===e.packageHash));for(let e of[...g.flatMap(e=>e.installation?[e.installation]:[]),...C]){if(!e||e.tracked)continue;let A=await this.targets(e.agentId),t="PROJECT"===e.scope?A.find(A=>A.codebaseId===e.codebaseId&&A.worktreeId===e.worktreeId)?.folder??null:null;("PROJECT"!==e.scope||t)&&c(e.agentId,{kind:"DELETE",scope:e.scope,rootKind:e.rootKind,folder:t,skillName:e.skillName,manageGitExclude:"PROJECT"===e.scope})}for(let[i,n]of d){let a=await t.skillSyncItem.create({data:{id:(0,A.randomUUID)(),runId:e,agentId:i,direction:"APPLY",status:"PENDING",candidatePackageJson:JSON.stringify({deployments:u.get(i)??[]})}});await this.agentControl.createJob({agentId:i,kind:r.SKILL_APPLY_JOB_KIND,payload:{operations:n,syncRunId:e,syncItemId:a.id},idempotencyKey:`skills:apply:${e}:${i}`,timeoutSeconds:600})}return await t.skillSyncRun.update({where:{id:e},data:d.size?{status:"APPLYING"}:{status:"SUCCEEDED",finishedAt:new Date}}),this.publish(e),this.getRun(e)}async completeApply(e){let{syncRunId:t,syncItemId:r}=this.completionIds(e);if(!t||!r)return;let n=await (0,i.getPrismaClient)(),a=await n.skillSyncItem.findFirst({where:{id:r,runId:t,direction:"APPLY",status:"PENDING"}});if(!a)return;let o="SUCCEEDED"===e.status,{deployments:s=[]}=h(a?.candidatePackageJson??null,{});await n.skillSyncItem.updateMany({where:{id:r,status:"PENDING"},data:{status:o?"COMPLETE":"FAILED",error:o?null:e.error??"Skill apply failed"}});let l=await n.skillDeployment.findMany({where:{id:{in:s.map(e=>e.id)},agentId:e.agentId,status:"PENDING"},include:{skill:{include:{files:!0}}}}),d=h(e.resultJson,{});if(o){let t=await this.configuredByAgent();for(let e of l){let r=s.find(A=>A.id===e.id),i=d.results?.find(A=>"WRITE"===A.kind&&A.path===e.targetPath);if(!r||e.desiredHash!==r.desiredHash||i?.packageHash!==r.desiredHash)continue;let a=await n.skillInstallation.upsert({where:{agentId_rootPath_skillName:{agentId:e.agentId,rootPath:I(e.targetPath),skillName:e.skill.name}},create:{id:(0,A.randomUUID)(),skillId:e.skillId,agentId:e.agentId,codebaseId:e.codebaseId,worktreeId:e.worktreeId,scope:e.scope,rootKind:e.rootKind,rootPath:I(e.targetPath),skillName:e.skill.name,description:e.skill.description,packageHash:e.desiredHash,present:!0,fileCount:e.skill.files.length,totalBytes:e.skill.files.reduce((e,A)=>e+A.contents.byteLength,0),tracked:!1,consumersJson:JSON.stringify(t.get(e.agentId)??[]),lastSeenAt:new Date},update:{skillId:e.skillId,codebaseId:e.codebaseId,worktreeId:e.worktreeId,scope:e.scope,rootKind:e.rootKind,description:e.skill.description,packageHash:e.desiredHash,present:!0,fileCount:e.skill.files.length,totalBytes:e.skill.files.reduce((e,A)=>e+A.contents.byteLength,0),tracked:!1,consumersJson:JSON.stringify(t.get(e.agentId)??[]),lastSeenAt:new Date}});await n.skillSyncBaseline.upsert({where:{installationId:a.id},create:{id:(0,A.randomUUID)(),installationId:a.id,skillId:e.skillId,packageHash:e.desiredHash},update:{skillId:e.skillId,packageHash:e.desiredHash,syncedAt:new Date}}),await n.skillDeployment.update({where:{id:e.id},data:{status:"INSTALLED",installedHash:e.desiredHash,lastError:null}})}for(let A of d.results??[])if("DELETE"===A.kind){var u;await n.skillInstallation.updateMany({where:{agentId:e.agentId,rootPath:I(A.path),skillName:C(u=A.path).basename(u)},data:{present:!1,lastSeenAt:new Date}})}}else for(let A of s)await n.skillDeployment.updateMany({where:{id:A.id,agentId:e.agentId,desiredHash:A.desiredHash,status:"PENDING"},data:{status:"FAILED",lastError:e.error??"Skill apply failed"}});if(!await n.skillSyncItem.count({where:{runId:t,direction:"APPLY",status:"PENDING"}})){let e=await n.skillSyncItem.count({where:{runId:t,direction:"APPLY",status:{in:["FAILED","SKIPPED"]}}});await n.skillSyncRun.update({where:{id:t},data:{status:e?"PARTIAL":"SUCCEEDED",finishedAt:new Date}})}this.publish(t)}}],593464)},333329,e=>{"use strict";e.i(593464),e.s([])},412150,142897,553434,e=>{"use strict";var A=e.i(374186);let t=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function r(e){return function e(A){return null===A?"null":Array.isArray(A)?`[${A.map(e).join(",")}]`:"object"==typeof A?`{${Object.entries(A).sort(([e],[A])=>e.localeCompare(A)).map(([A,t])=>`${JSON.stringify(A)}:${e(t)}`).join(",")}}`:JSON.stringify(A)}(e)}function i(e){return t.test(e)?`.${e}`:`[${JSON.stringify(e)}]`}function n(e,A){let t={},r=(e,A)=>{if(A&&"object"==typeof A&&!Array.isArray(A)&&Object.getPrototypeOf(A)===Object.prototype){let n=Object.entries(A);if(0===n.length)t[e]=A;else for(let[A,t]of n)r(`${e}${i(A)}`,t)}else t[e]=A};for(let[t,n]of Object.entries(A))r(`${e}${i(t)}`,n);return t}function a(e){let A={default:e.defaultParameters,additional:e.additionalParameters};return{...{source:e.entryType,time:e.clientTime,receivedAt:e.receivedAt,deviceIp:e.deviceIp,message:e.message,level:e.level,category:e.category,eventName:e.eventName,eventKind:e.eventKind,levelKind:e.level??e.eventKind,screenName:e.screenName,buildId:e.buildId,sessionId:e.sessionId,attributes:e.attributes,defaultParameters:e.defaultParameters,additionalParameters:e.additionalParameters,parameters:A,detail:"CONSOLE"===e.entryType?e.message:`${e.eventName??""}${e.screenName?` (${e.screenName})`:""}`},...n("attributes",e.attributes),...n("defaultParameters",e.defaultParameters),...n("additionalParameters",e.additionalParameters)}}function o(e){return null==e?"":"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e?String(e):r(e)}function s(e){return Object.entries(a(e)).flatMap(([e,A])=>[e,o(A)]).join("\n")}e.s(["stableJson",0,r,"telemetryDisplay",0,o,"telemetryFields",0,a,"telemetrySearchText",0,s],142897);let l=["TEXT","GLOB","REGEX"],d=["CONTAINS","DOES_NOT_CONTAIN","IS","IS_NOT","MATCHES_GLOB","MATCHES_REGEX","NO_REGEX_MATCH","IS_EMPTY","IS_NOT_EMPTY"];e.s(["DEFAULT_TELEMETRY_COLUMNS",0,{CONSOLE:["time","level","category","message","buildId","sessionId"],ANALYTICS:["time","eventKind","eventName","screenName","parameters","buildId","sessionId"],UNIFIED:["time","source","levelKind","detail","buildId","sessionId"]},"TELEMETRY_COLORS",0,["gray","stone","red","rose","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink"],"TELEMETRY_FILTER_OPERATORS",0,d,"TELEMETRY_SEARCH_MODES",0,l,"TELEMETRY_VIEWS",0,["CONSOLE","ANALYTICS","UNIFIED"]],553434);let u=new Map;function c(e,t,r){let i;if(t.length>1024)throw Error("Pattern must not exceed 1024 characters");if(!l.includes(e))throw Error("Unknown search mode");let n=`${e}\u0000${r?"1":"0"}\u0000${t}`,a=u.get(n);if(a)return a;if("TEXT"===e){let e=r?t:t.toLocaleLowerCase();i=A=>(r?A:A.toLocaleLowerCase()).includes(e)}else{let n="GLOB"===e?`^${function(e){let A="";for(let t=0;t<e.length;t+=1){let r=e[t];if("*"===r)A+=".*";else if("?"===r)A+=".";else if("["===r){let r=e.indexOf("]",t+1);if(-1===r)throw Error("Invalid glob pattern: missing ]");{let i=e.slice(t+1,r).replace(/^!/,"^");A+=`[${i}]`,t=r}}else A+=r.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&")}return A}(t)}$`:t,a=new A.default(n,r?"su":"isu");i=e=>a.test(e)}return u.set(n,i),u.size>100&&u.delete(u.keys().next().value),i}function h(e){return null==e||""===e||Array.isArray(e)&&0===e.length||"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length}function g(e){return"CONSOLE"===e?["CONSOLE"]:"ANALYTICS"===e?["ANALYTICS"]:["CONSOLE","ANALYTICS"]}e.s(["fieldsForFacet",0,function(e){return a(e)},"matchesTelemetryQuery",0,function(e,A){return"SEPARATOR"!==e.entryType&&!!g(A.view).includes(e.entryType)&&(!A.search||!!c(A.searchMode??"TEXT",A.search,!0===A.caseSensitive)(s(e)))&&function(e,A){if(!A)return!0;let t=a(e);return Object.entries(A).every(([e,A])=>0===A.length||A.includes(o(t[e])))}(e,A.quickFilters)&&function(e,A){if(!A?.conditions.length)return!0;let t=A.conditions.filter(A=>!A.sources?.length||"SEPARATOR"!==e.entryType&&A.sources.includes(e.entryType));if(0===t.length)return!0;let r=a(e),i=t.map(e=>(function(e,A){if(!d.includes(A.operator))throw Error("Unknown filter operator");let t=e[A.field];if("IS_EMPTY"===A.operator)return h(t);if("IS_NOT_EMPTY"===A.operator)return!h(t);let r=o(t),i=A.value??"",n=!0===A.caseSensitive,a=n?r:r.toLocaleLowerCase(),s=n?i:i.toLocaleLowerCase();if("CONTAINS"===A.operator)return a.includes(s);if("DOES_NOT_CONTAIN"===A.operator)return!a.includes(s);if("IS"===A.operator)return a===s;if("IS_NOT"===A.operator)return a!==s;if("MATCHES_GLOB"===A.operator)return c("GLOB",i,n)(r);let l=c("REGEX",i,n)(r);return"MATCHES_REGEX"===A.operator?l:!l})(r,e));return"ANY"===A.mode?i.some(Boolean):i.every(Boolean)}(e,A.advancedFilter)},"sourcesForView",0,g,"validateTelemetryQuery",0,function(e){for(let A of(e.search&&c(e.searchMode??"TEXT",e.search,!0===e.caseSensitive),e.advancedFilter?.conditions??[]))["MATCHES_GLOB","MATCHES_REGEX","NO_REGEX_MATCH"].includes(A.operator)&&c("MATCHES_GLOB"===A.operator?"GLOB":"REGEX",A.value??"",!0===A.caseSensitive)}],412150)},342572,e=>{"use strict";var A=e.i(794231),t=e.i(666680),r=e.i(135475);e.i(256554);var i=e.i(848201),n=e.i(660526),a=e.i(412150),o=e.i(142897),s=e.i(553434);let l="default";function d(e){try{let A=JSON.parse(e);return A&&"object"==typeof A&&!Array.isArray(A)?A:{}}catch{return{}}}function u(e){return{id:e.id,entryType:e.entryType,clientTime:e.clientTime.toISOString(),receivedAt:e.receivedAt.toISOString(),deviceIp:e.deviceIp,message:e.message,level:e.level,category:e.category,eventName:e.eventName,eventKind:e.eventKind,screenName:e.screenName,buildId:e.buildId,sessionId:e.sessionId,attributes:d(e.attributesJson),defaultParameters:d(e.defaultParametersJson),additionalParameters:d(e.additionalParametersJson),highlightColor:e.highlightColor,separatorKind:e.separatorKind,separatorName:e.separatorName}}function c(e){if(!s.TELEMETRY_VIEWS.includes(e))throw Error("Unknown telemetry view");return e}function h(e){let A=e.trim();if(!A||A.length>100)throw Error("Name must contain 1-100 characters");return{name:A,normalizedName:A.toLocaleLowerCase()}}function g(e){let A;try{A=new URL(e.trim())}catch{throw Error("Telemetry URL must be a valid HTTP(S) origin")}if(!["http:","https:"].includes(A.protocol)||A.username||A.password||"/"!==A.pathname&&""!==A.pathname||A.search||A.hash)throw Error("Telemetry URL must be an HTTP(S) origin without a path, credentials, query, or fragment");return A.origin}function p(e){return e?.trim()?g(e):null}function C(e){if(!e?.trim())return null;try{let A=new URL(e.trim());return["http:","https:"].includes(A.protocol)?A.origin:null}catch{return null}}function f(e){if(!e)return null;try{let A=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));if(A&&"object"==typeof A&&"string"==typeof A.clientTime&&"string"==typeof A.receivedAt&&"string"==typeof A.id&&Number.isFinite(Date.parse(A.clientTime))&&Number.isFinite(Date.parse(A.receivedAt)))return A}catch{}throw Error("Invalid telemetry cursor")}function I(e){let A=new Date(e.clientTime),t=new Date(e.receivedAt);return{OR:[{clientTime:{lt:A}},{clientTime:A,receivedAt:{lt:t}},{clientTime:A,receivedAt:t,id:{lt:e.id}}]}}function w(e){return Buffer.from(JSON.stringify({clientTime:e.clientTime,receivedAt:e.receivedAt,id:e.id})).toString("base64url")}function m(e,A){return e.clientTime!==A.clientTime?e.clientTime<A.clientTime:e.receivedAt!==A.receivedAt?e.receivedAt<A.receivedAt:e.id<A.id}function E(e){return!!(e.search||Object.values(e.quickFilters??{}).some(e=>e.length)||e.advancedFilter?.conditions.length)}function y(e){return{entryType:{in:(0,a.sourcesForView)(e)}}}let B={source:{name:"entryType",nullable:!1},deviceIp:{name:"deviceIp",nullable:!0},message:{name:"message",nullable:!0},level:{name:"level",nullable:!0},category:{name:"category",nullable:!0},eventName:{name:"eventName",nullable:!0},eventKind:{name:"eventKind",nullable:!0},screenName:{name:"screenName",nullable:!0},buildId:{name:"buildId",nullable:!0},sessionId:{name:"sessionId",nullable:!0}};function Q(e){let A=[...new Set(e.map(e=>e.trim()).filter(Boolean))];if(0===A.length||A.length>100||A.some(e=>e.length>512))throw Error("Columns must contain 1-100 valid column identifiers");return JSON.stringify(A)}function D(e,A){try{let A=JSON.parse(e);if(Array.isArray(A)&&A.every(e=>"string"==typeof e)&&A.length)return A}catch{}return s.DEFAULT_TELEMETRY_COLUMNS[A]}e.s(["TelemetryService",0,class{subscribe(e){let t=i.agentEventBus.iterate(i.TELEMETRY_CHANGED_TOPIC);return e?(0,A.filterAsyncIterator)(t,A=>!A.views||A.views.includes(e)):t}subscribeSettings(){return i.agentEventBus.iterate(i.TELEMETRY_SETTINGS_CHANGED_TOPIC)}publish(e,A,t){i.agentEventBus.publish(i.TELEMETRY_CHANGED_TOPIC,{ids:e,reason:A,...t?{views:t}:{}})}notifyChange(e,A){this.publish(e,A)}async rawSettings(){return(await (0,r.getPrismaClient)()).telemetrySettings.upsert({where:{id:l},create:{id:l},update:{}})}async settings(e={}){let[A,t]=await Promise.all([this.rawSettings(),Promise.resolve(function(e={}){let A,t=C(e.requestOrigin),r=(e.localOrigins??function(){let e=Number(process.env.PORT??3e3),A=Number.isInteger(e)&&e>0&&e<=65535?e:3e3;var t=(0,n.networkInterfaces)();let r=new Set;for(let e of Object.values(t))for(let t of e??[])t&&!t.internal&&("IPv4"===t.family?r.add(`http://${t.address}:${A}`):"IPv6"!==t.family||t.address.toLowerCase().startsWith("fe80:")||r.add(`http://[${t.address}]:${A}`));return[...r]}()).flatMap(e=>{try{return[g(e)]}catch{return[]}}),i=C(e.publicBaseUrl??process.env.PUBLIC_BASE_URL),a=!!t&&("localhost"===(A=new URL(t).hostname.toLowerCase().replace(/^\[|\]$/g,""))||"::1"===A||A.endsWith(".local")||/^127\./.test(A)||/^10\./.test(A)||/^192\.168\./.test(A)||/^172\.(1[6-9]|2\d|3[01])\./.test(A)),o=t&&a?t:r[0]??t??"http://127.0.0.1:3000",s=i??t??o;return{local:o,remote:s}}(e))]);return{localBaseUrlOverride:A.localBaseUrlOverride,remoteBaseUrlOverride:A.remoteBaseUrlOverride,consoleCollectionEnabled:A.consoleCollectionEnabled,analyticsCollectionEnabled:A.analyticsCollectionEnabled,detectedLocalBaseUrl:t.local,detectedRemoteBaseUrl:t.remote,effectiveLocalBaseUrl:A.localBaseUrlOverride??t.local,effectiveRemoteBaseUrl:A.remoteBaseUrlOverride??t.remote,updatedAt:A.updatedAt.toISOString()}}async saveSettings(e,A={}){let t=await (0,r.getPrismaClient)(),n=await this.rawSettings(),a=await t.telemetrySettings.update({where:{id:l},data:{localBaseUrlOverride:void 0===e.localBaseUrlOverride?n.localBaseUrlOverride:p(e.localBaseUrlOverride),remoteBaseUrlOverride:void 0===e.remoteBaseUrlOverride?n.remoteBaseUrlOverride:p(e.remoteBaseUrlOverride),consoleCollectionEnabled:e.consoleCollectionEnabled??n.consoleCollectionEnabled,analyticsCollectionEnabled:e.analyticsCollectionEnabled??n.analyticsCollectionEnabled}});return i.agentEventBus.publish(i.TELEMETRY_SETTINGS_CHANGED_TOPIC,{updatedAt:a.updatedAt.toISOString()}),this.settings(A)}async buildSettings(e,A={}){let t=await this.settings(A),r="SIMULATOR"===e?t.effectiveLocalBaseUrl:t.effectiveRemoteBaseUrl;return{localBaseUrl:t.effectiveLocalBaseUrl,remoteBaseUrl:t.effectiveRemoteBaseUrl,selectedBaseUrl:r,consoleLogsUrl:`${r}/api/telemetry/console-logs`,analyticsEventsUrl:`${r}/api/telemetry/analytics-events`,consoleCollectionEnabled:t.consoleCollectionEnabled,analyticsCollectionEnabled:t.analyticsCollectionEnabled}}async ingestConsole(e,A){if(!(await this.rawSettings()).consoleCollectionEnabled)return{collected:!1,items:[]};let i=await (0,r.getPrismaClient)(),n=new Date,a=e.map(e=>{let r={id:(0,t.randomUUID)(),entryType:"CONSOLE",clientTime:new Date(e.time),receivedAt:n,deviceIp:A,message:e.message,level:e.level,category:e.category,buildId:e.buildId,sessionId:e.sessionId,attributesJson:JSON.stringify(e.attributes),searchText:""},i=u({...r,eventName:null,eventKind:null,screenName:null,defaultParametersJson:"{}",additionalParametersJson:"{}",highlightColor:null,separatorKind:null,separatorName:null});return{...r,searchText:(0,o.telemetrySearchText)(i)}});return await i.telemetryEntry.createMany({data:a}),this.publish(a.map(({id:e})=>e),"INGESTED",["CONSOLE","UNIFIED"]),{collected:!0,items:a.map(({id:e})=>({id:e,receivedAt:n.toISOString(),deviceIp:A}))}}async ingestAnalytics(e,A){if(!(await this.rawSettings()).analyticsCollectionEnabled)return{collected:!1,items:[]};let i=await (0,r.getPrismaClient)(),n=new Date,a=e.map(e=>{let r={id:(0,t.randomUUID)(),entryType:"ANALYTICS",clientTime:new Date(e.time),receivedAt:n,deviceIp:A,eventName:e.eventName,eventKind:e.kind,screenName:e.screenName,buildId:e.buildId,sessionId:e.sessionId,defaultParametersJson:JSON.stringify(e.defaultParameters),additionalParametersJson:JSON.stringify(e.additionalParameters),searchText:""},i=u({...r,message:null,level:null,category:null,attributesJson:"{}",highlightColor:null,separatorKind:null,separatorName:null});return{...r,searchText:(0,o.telemetrySearchText)(i)}});return await i.telemetryEntry.createMany({data:a}),this.publish(a.map(({id:e})=>e),"INGESTED",["ANALYTICS","UNIFIED"]),{collected:!0,items:a.map(({id:e})=>({id:e,receivedAt:n.toISOString(),deviceIp:A}))}}async scan(e,A,t=1e3){let i=await (0,r.getPrismaClient)(),n=null;for(;;){let r=await i.telemetryEntry.findMany({where:n?{AND:[e,{OR:[{clientTime:{lt:n.clientTime}},{clientTime:n.clientTime,receivedAt:{lt:n.receivedAt}},{clientTime:n.clientTime,receivedAt:n.receivedAt,id:{lt:n.id}}]}]}:e,orderBy:[{clientTime:"desc"},{receivedAt:"desc"},{id:"desc"}],take:t});for(let e of r)if(await A(u(e))===!1)return;if(r.length<t)break;n=r.at(-1)}}async timeline(e){let A=c(e.view);(0,a.validateTelemetryQuery)(e);let t=Math.min(500,Math.max(1,e.first??200)),i=f(e.after),n=await (0,r.getPrismaClient)(),o=await n.telemetryEntry.count({where:y(A)}),s=E(e);if(!s){let e=[],r=0,n=!1,s=null,l=!1,d={entryType:{in:[...(0,a.sourcesForView)(A),"SEPARATOR"]}};return(await this.scan(i?{AND:[d,I(i)]}:d,A=>{if("SEPARATOR"===A.entryType){l&&e.push(A),l=!1;return}if(r<t){e.push(A),r+=1,s=A,l=!0;return}return n=!0,!1},Math.min(1e3,t+1)),s)?{items:e,nextCursor:n?w(s):null,matchingCount:o,totalCount:o}:{items:[],nextCursor:null,matchingCount:o,totalCount:o}}let l=[],d=0,u=!1,h=0,g=null,p=!1,C=!1,Q=function(e){let A=[];for(let[t,r]of(e.search&&(e.searchMode??"TEXT")==="TEXT"&&!0===e.caseSensitive&&A.push({searchText:{contains:e.search}}),Object.entries(e.quickFilters??{}))){if(!r.length)continue;let e=B[t];if(!e)continue;let i=function(e,A){let t=[...new Set(A)],r=t.filter(Boolean),i=[];return(r.length&&i.push({[e.name]:{in:r}}),t.includes("")&&(i.push({[e.name]:""}),e.nullable&&i.push({[e.name]:null})),0===i.length)?null:1===i.length?i[0]:{OR:i}}(e,r);i&&A.push(i)}if(e.advancedFilter?.mode==="ALL")for(let t of e.advancedFilter.conditions){if(t.sources?.length||!0!==t.caseSensitive)continue;let e=B[t.field],r=t.value??"";e&&r&&("IS"===t.operator?A.push({[e.name]:r}):"CONTAINS"===t.operator&&A.push({[e.name]:{contains:r}}))}return A.length?1===A.length?A[0]:{AND:A}:null}(e);return(await this.scan(Q?{OR:[{entryType:"SEPARATOR"},{AND:[y(A),Q]}]}:{entryType:{in:[...(0,a.sourcesForView)(A),"SEPARATOR"]}},A=>{if("SEPARATOR"===A.entryType){(!i||m(A,i))&&(!s&&!u||s&&p&&!C)&&l.push(A),p=!1,C=!1;return}!(0,a.matchesTelemetryQuery)(A,e)||(d+=1,(!i||m(A,i))&&(h<t?(l.push(A),h+=1,g=A,p=!0):(u=!0,C=!0)))}),g)?{items:l,nextCursor:u?w(g):null,matchingCount:d,totalCount:o}:{items:[],nextCursor:null,matchingCount:d,totalCount:o}}async entries(e){let A=await (0,r.getPrismaClient)(),t=[...new Set(e)].slice(0,1e3);return(await A.telemetryEntry.findMany({where:{id:{in:t}}})).map(u)}async entry(e,A){let t=c(A),r=(await this.entries([e]))[0]??null;if(!r)return null;if("SEPARATOR"===r.entryType||!(0,a.sourcesForView)(t).includes(r.entryType))throw Error(`Telemetry entry ${e} does not belong to ${t}`);return r}async latestSeparator(){let e=await (0,r.getPrismaClient)(),A=await e.telemetryEntry.findFirst({where:{entryType:"SEPARATOR"},orderBy:[{clientTime:"desc"},{receivedAt:"desc"},{id:"desc"}]});return A?u(A):null}async separators(e){let A=Math.min(500,Math.max(1,e.first??100)),t=f(e.after),i=[{entryType:"SEPARATOR"}];e.kind?.trim()&&i.push({separatorKind:e.kind.trim()}),e.name?.trim()&&i.push({separatorName:{contains:e.name.trim()}}),e.buildId?.trim()&&i.push({buildId:e.buildId.trim()}),t&&i.push(I(t));let n=await (0,r.getPrismaClient)(),a=await n.telemetryEntry.findMany({where:{AND:i},orderBy:[{clientTime:"desc"},{receivedAt:"desc"},{id:"desc"}],take:A+1}),o=a.length>A,s=a.slice(0,A).map(u);return{items:s,nextCursor:o&&s.length?w(s.at(-1)):null}}async timelineSinceLatestSeparator(e){let A,t,i=c(e.view);(0,a.validateTelemetryQuery)(e);let n=Math.min(500,Math.max(1,e.first??200)),o=f(e.after),s=await this.latestSeparator(),l=s?{clientTime:s.clientTime,receivedAt:s.receivedAt,id:s.id}:null,d=E(e),u=l?{AND:[y(i),(A=new Date(l.clientTime),{OR:[{clientTime:{gt:A}},{clientTime:A,receivedAt:{gt:t=new Date(l.receivedAt)}},{clientTime:A,receivedAt:t,id:{gt:l.id}}]})]}:y(i);if(!d){let e=await (0,r.getPrismaClient)(),A=await e.telemetryEntry.count({where:u}),t=[],i=!1,a=null;return await this.scan(o?{AND:[u,I(o)]}:u,e=>{if(t.length<n){t.push(e),a=e;return}return i=!0,!1},Math.min(1e3,n+1)),{separator:s,items:t,nextCursor:i&&a?w(a):null,matchingCount:A,totalCount:A}}let h=[],g=0,p=0,C=!1,B=null;return await this.scan(u,A=>{p+=1,!(0,a.matchesTelemetryQuery)(A,e)||(g+=1,(!o||m(A,o))&&(h.length<n?(h.push(A),B=A):C=!0))}),{separator:s,items:h,nextCursor:C&&B?w(B):null,matchingCount:g,totalCount:p}}async facets(e){let A=c(e),t="CONSOLE"===A?["level","category","deviceIp","buildId","sessionId"]:"ANALYTICS"===A?["eventKind","eventName","screenName","deviceIp","buildId","sessionId"]:["source","level","eventKind","deviceIp","buildId","sessionId"],r=Object.fromEntries(t.map(e=>[e,new Set]));return await this.scan(y(A),e=>{let i=(0,a.fieldsForFacet)(e);for(let e of t){let A=i[e];null!=A&&""!==String(A)&&r[e].add(String(A))}"UNIFIED"===A&&r.source.add(e.entryType)}),Object.fromEntries(Object.entries(r).map(([e,A])=>[e,[...A].sort((e,A)=>e.localeCompare(A))]))}async fields(e){let A=c(e),t=new Set;return await this.scan(y(A),e=>{for(let A of Object.keys((0,a.fieldsForFacet)(e)))t.add(A)}),[...t].sort((e,A)=>e.localeCompare(A))}async addSeparator(e){let A=e?.trim()||null;if(A&&A.length>100)throw Error("Separator name must not exceed 100 characters");let i=await (0,r.getPrismaClient)(),n=await i.telemetryEntry.create({data:{id:(0,t.randomUUID)(),entryType:"SEPARATOR",clientTime:new Date,receivedAt:new Date,separatorKind:"MANUAL",separatorName:A}});return this.publish([n.id],"SEPARATOR_ADDED"),u(n)}async addBuildSeparator(e){let A=await (0,r.getPrismaClient)(),i=await A.telemetryEntry.upsert({where:{separatorKind_buildId:{separatorKind:"BUILD",buildId:e.buildId}},create:{id:(0,t.randomUUID)(),entryType:"SEPARATOR",clientTime:e.clientTime??new Date,receivedAt:new Date,separatorKind:"BUILD",separatorName:e.name.slice(0,100),buildId:e.buildId},update:{}});return this.publish([i.id],"BUILD_SEPARATOR_ADDED"),u(i)}async highlight(e,A){if(null!==A&&!s.TELEMETRY_COLORS.includes(A))throw Error("Unknown telemetry highlight color");let t=await (0,r.getPrismaClient)();if("SEPARATOR"===(await t.telemetryEntry.findUniqueOrThrow({where:{id:e}})).entryType)throw Error("Separators cannot be highlighted");let i=await t.telemetryEntry.update({where:{id:e},data:{highlightColor:A}});return this.publish([e],"HIGHLIGHT_CHANGED"),u(i)}selectionRanges(e){return(Array.isArray(e.ranges)?e.ranges.slice(0,500):[]).map(e=>{if(!e||"object"!=typeof e)throw Error("Invalid telemetry selection range");let A=e.startTime?Date.parse(e.startTime):null,t=e.endTime?Date.parse(e.endTime):null;if(null!==A&&!Number.isFinite(A)||null!==t&&!Number.isFinite(t)||null!==A&&null!==t&&A>=t)throw Error("Invalid telemetry selection range");return{start:A,end:t,includeSeparators:!0===e.includeSeparators}})}async selectionIds(e){let A=new Set((Array.isArray(e.ids)?e.ids:[]).filter(e=>"string"==typeof e).slice(0,1e5)),t=new Set((Array.isArray(e.excludedIds)?e.excludedIds:[]).filter(e=>"string"==typeof e).slice(0,1e5));if(!e.query){for(let e of t)A.delete(e);return[...A]}if("object"!=typeof e.query||Array.isArray(e.query))throw Error("Invalid telemetry selection query");c(e.query.view),(0,a.validateTelemetryQuery)(e.query);let r=this.selectionRanges(e);return await this.scan(e.includeSeparators||r.some(e=>e.includeSeparators)?{entryType:{in:[...(0,a.sourcesForView)(e.query.view),"SEPARATOR"]}}:y(e.query.view),i=>{let n=Date.parse(i.clientTime),o=r.filter(e=>(null===e.start||n>=e.start)&&(null===e.end||n<e.end));if((!(r.length>0)||0!==o.length)&&!t.has(i.id)){if("SEPARATOR"===i.entryType){(e.includeSeparators||o.some(e=>e.includeSeparators))&&A.add(i.id);return}(0,a.matchesTelemetryQuery)(i,e.query)&&A.add(i.id)}}),[...A]}async clearSelected(e){let A=await this.selectionIds(e);if(!A.length)return 0;let t=await (0,r.getPrismaClient)(),i=0;for(let e=0;e<A.length;e+=500)i+=(await t.telemetryEntry.deleteMany({where:{id:{in:A.slice(e,e+500)}}})).count;return this.publish([],"CLEARED"),i}async clearAll(e,A=!1){let t=c(e),i=await (0,r.getPrismaClient)(),n=await i.telemetryEntry.deleteMany({where:A?{entryType:{in:[...(0,a.sourcesForView)(t),"SEPARATOR"]}}:y(t)});return this.publish([],A?"CLEARED_WITH_SEPARATORS":"CLEARED",A||"UNIFIED"===t?void 0:[t,"UNIFIED"]),n.count}async clearBeforeLatestSeparator(e,A=!1){let t=c(e),i=await this.latestSeparator();if(!i)return 0;let n=await (0,r.getPrismaClient)(),o=await n.telemetryEntry.deleteMany({where:{AND:[A?{entryType:{in:[...(0,a.sourcesForView)(t),"SEPARATOR"]}}:y(t),I({clientTime:i.clientTime,receivedAt:i.receivedAt,id:i.id})]}});return this.publish([],"CLEARED_BEFORE_SEPARATOR"),o.count}async clearScoped(e){let A=c(e.view);if("ALL"===e.scope)return this.clearAll(A,!!e.includeSeparators);if("BEFORE_LATEST_SEPARATOR"===e.scope)return this.clearBeforeLatestSeparator(A,!!e.includeSeparators);if("MATCHING"===e.scope){if(!e.query)throw Error("A matching query is required");return this.clearSelected({query:{...e.query,view:A}})}let t=[...new Set(e.ids??[])].slice(0,1e3);if(!t.length)throw Error("At least one telemetry entry ID is required");let i=await (0,r.getPrismaClient)(),n=await i.telemetryEntry.findMany({where:{id:{in:t},entryType:{in:[...(0,a.sourcesForView)(A),"SEPARATOR"]}},select:{id:!0}});if(!n.length)return 0;let o=await i.telemetryEntry.deleteMany({where:{id:{in:n.map(({id:e})=>e)}}});return this.publish([],"CLEARED"),o.count}async viewSettings(e){let A=c(e),t=await (0,r.getPrismaClient)(),i=await t.telemetryViewSettings.upsert({where:{view:A},create:{id:A,view:A,columnsJson:JSON.stringify(s.DEFAULT_TELEMETRY_COLUMNS[A])},update:{}});return{view:A,columns:D(i.columnsJson,A),timeFormat:"24"===i.timeFormat?"24":"12",activeColumnPresetId:i.activeColumnPresetId,activeSavedFilterId:i.activeSavedFilterId}}async saveViewSettings(e){let A=c(e.view);if(e.timeFormat&&!["12","24"].includes(e.timeFormat))throw Error("Unknown time format");let t=await this.viewSettings(A),i=await (0,r.getPrismaClient)();return await i.telemetryViewSettings.upsert({where:{view:A},create:{id:A,view:A,columnsJson:Q(e.columns??t.columns),timeFormat:e.timeFormat??t.timeFormat,activeColumnPresetId:e.activeColumnPresetId??null,activeSavedFilterId:e.activeSavedFilterId??null},update:{columnsJson:e.columns?Q(e.columns):void 0,timeFormat:e.timeFormat??void 0,activeColumnPresetId:void 0===e.activeColumnPresetId?void 0:e.activeColumnPresetId,activeSavedFilterId:void 0===e.activeSavedFilterId?void 0:e.activeSavedFilterId}}),this.viewSettings(A)}async columnPresets(e){let A=c(e),t=await (0,r.getPrismaClient)();return(await t.telemetryColumnPreset.findMany({where:{view:A},orderBy:[{isDefault:"desc"},{name:"asc"}]})).map(e=>({id:e.id,view:A,name:e.name,columns:D(e.columnsJson,A),isDefault:e.isDefault,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}))}async saveColumnPreset(e){let A=c(e.view),{name:i,normalizedName:n}=h(e.name),a=await (0,r.getPrismaClient)(),o=e.id??(0,t.randomUUID)();return await a.$transaction(async t=>{e.isDefault&&await t.telemetryColumnPreset.updateMany({where:{view:A},data:{isDefault:!1}}),await t.telemetryColumnPreset.upsert({where:{id:o},create:{id:o,view:A,name:i,normalizedName:n,columnsJson:Q(e.columns),isDefault:!0===e.isDefault},update:{name:i,normalizedName:n,columnsJson:Q(e.columns),isDefault:e.isDefault??void 0}})}),(await this.columnPresets(A)).find(e=>e.id===o)}async deleteColumnPreset(e){let A=await (0,r.getPrismaClient)();return await A.telemetryViewSettings.updateMany({where:{activeColumnPresetId:e},data:{activeColumnPresetId:null}}),(await A.telemetryColumnPreset.deleteMany({where:{id:e}})).count>0}async savedFilters(e){let A=c(e),t=await (0,r.getPrismaClient)();return(await t.telemetrySavedFilter.findMany({where:{view:A},orderBy:{name:"asc"}})).map(e=>({id:e.id,view:A,name:e.name,definition:JSON.parse(e.definitionJson),createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}))}async saveFilter(e){let A=c(e.view);(0,a.validateTelemetryQuery)({view:A,advancedFilter:e.definition});let{name:i,normalizedName:n}=h(e.name),s=await (0,r.getPrismaClient)(),l=e.id??(0,t.randomUUID)();return await s.telemetrySavedFilter.upsert({where:{id:l},create:{id:l,view:A,name:i,normalizedName:n,definitionJson:(0,o.stableJson)(e.definition)},update:{name:i,normalizedName:n,definitionJson:(0,o.stableJson)(e.definition)}}),(await this.savedFilters(A)).find(e=>e.id===l)}async deleteFilter(e){let A=await (0,r.getPrismaClient)();return await A.telemetryViewSettings.updateMany({where:{activeSavedFilterId:e},data:{activeSavedFilterId:null}}),(await A.telemetrySavedFilter.deleteMany({where:{id:e}})).count>0}async exportEntries(e){(0,a.validateTelemetryQuery)(e.query);let A=e.selection??(e.ids?.length?{ids:e.ids}:null);if(A){let e=new Set(await this.selectionIds(A)),t=[],r=[...e];for(let e=0;e<r.length;e+=500)await this.scan({id:{in:r.slice(e,e+500)}},e=>{t.push(e)});return t.sort((e,A)=>{let t=A.clientTime.localeCompare(e.clientTime);return t||A.receivedAt.localeCompare(e.receivedAt)||A.id.localeCompare(e.id)}),t}let t=[],r=!1,i=E(e.query);return await this.scan({entryType:{in:[...(0,a.sourcesForView)(e.query.view),"SEPARATOR"]}},A=>{"SEPARATOR"===A.entryType?((!i||r)&&t.push(A),r=!1):(0,a.matchesTelemetryQuery)(A,e.query)&&(t.push(A),r=!0)}),t}}],342572)},829111,e=>{"use strict";let A={type:"object",required:["collected","items"],properties:{collected:{type:"boolean"},items:{type:"array",items:{type:"object",required:["id","receivedAt","deviceIp"],properties:{id:{type:"string",format:"uuid"},receivedAt:{type:"string",format:"date-time"},deviceIp:{type:"string"}}}}}};function t(e,t,r){return{post:{tags:["Telemetry"],summary:r,description:"Unauthenticated ingestion. Accepts one record or an atomic `{ items: [...] }` batch of at most 500 records. The request body is capped at 2 MiB.",requestBody:{required:!0,content:{"application/json":{schema:{oneOf:[e,{type:"object",additionalProperties:!1,required:["items"],properties:{items:{type:"array",minItems:1,maxItems:500,items:e}}}]},examples:{single:{value:t},batch:{value:{items:[t]}}}}}},responses:{201:{description:"Records collected",content:{"application/json":{schema:A}}},202:{description:"Payload valid but collection is disabled",content:{"application/json":{schema:A}}},400:{$ref:"#/components/responses/TelemetryBadRequest"},413:{$ref:"#/components/responses/TelemetryPayloadTooLarge"},415:{$ref:"#/components/responses/TelemetryUnsupportedMediaType"},500:{$ref:"#/components/responses/InternalError"}}}}}t({$ref:"#/components/schemas/ConsoleLogInput"},{message:"Checkout completed",time:"2026-07-20T18:30:00.000Z",level:"info",category:"checkout",buildId:"build-123",sessionId:"session-456",attributes:{durationMs:412,cache:{hit:!0}}},"Collect console logs"),t({$ref:"#/components/schemas/AnalyticsEventInput"},{eventName:"checkout_completed",kind:"product",screenName:"Checkout",time:"2026-07-20T18:30:00.000Z",defaultParameters:{appVersion:"1.0"},additionalParameters:{cartItems:3},buildId:"build-123",sessionId:"session-456"},"Collect analytics events"),e.s([])},826587,e=>{"use strict";e.i(902157),e.i(912714),e.i(660526),e.i(750227),e.i(81111),e.i(188646);let A=globalThis;A.buildArtifactTransfers??(A.buildArtifactTransfers=new Map),e.s([])},354473,e=>e.a(async(A,t)=>{try{e.s(["cachedArtifact",()=>c]);var r=e.i(666680),i=e.i(912714),n=e.i(660526),a=e.i(750227);e.i(135475),e.i(826587);var o=e.i(604104),s=A([o]);[o]=s.then?(await s)():s;let h=process.env.ARTIFACT_CACHE_DIRECTORY?.trim()||(0,a.join)((0,n.tmpdir)(),"ade-build-artifact-cache");process.env.ARTIFACT_CACHE_MAX_BYTES;let g=globalThis;async function l(e){try{let A=JSON.parse(await (0,i.readFile)(e,"utf8"));if(!A||"object"!=typeof A)return null;let{filename:t,contentType:r,size:n}=A;if("string"!=typeof t||"string"!=typeof r||"number"!=typeof n)return null;return{filename:t,contentType:r,size:n}}catch{return null}}async function d(e){let A=(0,a.join)(h,e),t=await l(`${A}.json`);if(!t)return null;try{let r=await (0,i.stat)(A);if(!r.isFile()||r.size!==t.size)return null;let n=new Date;return await (0,i.utimes)(A,n,n).catch(()=>{}),{path:A,etag:`"${e}"`,...t}}catch{return null}}async function u(e,A){var t;let i=(0,o.getServerServices)(),n=await i.buildsService.artifactForInstall(e,A);if(!n)throw Error("Build artifact not found");return{artifact:n,key:(t=n.checksum??n.createdAt,(0,r.createHash)("sha1").update(`${A}:${t}`).digest("hex"))}}async function c(e,A){let{key:t}=await u(e,A);return d(t)}g.buildArtifactMaterializations??(g.buildArtifactMaterializations=new Map),t()}catch(e){t(e)}},!1),250746,e=>e.a(async(A,t)=>{try{e.s(["buildArtifactFileChecksum",()=>u,"failBuildArtifactTransferForJob",()=>c]);var r=e.i(666680),i=e.i(902157);e.i(912714);var n=e.i(660526),a=e.i(750227),o=e.i(135475);e.i(256554);var s=e.i(848201),l=e.i(354473),d=A([l]);[l]=d.then?(await d)():d,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 u(e){let A=(0,r.createHash)("sha256");for await(let t of(0,i.createReadStream)(e))A.update(t);return A.digest("hex")}async function c(e,A){let t=await (0,o.getPrismaClient)(),r=await t.buildArtifactTransfer.findFirst({where:{OR:[{sourceJobId:e},{targetJobId:e}]},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:A,finishedAt:new Date}}),t.buildDeployment.updateMany({where:{transferId:r.id,status:{in:["QUEUED","TRANSFERRING"]}},data:{status:"FAILED",error:A,finishedAt:new Date}})]),i=r.artifact.buildId,s.agentEventBus.publish((0,s.buildTopic)(i),{buildChanged:{id:i}}),s.agentEventBus.publish(s.BUILDS_CHANGED_TOPIC,{buildsChanged:{id:i}})}}h.buildArtifactTransferLocks??(h.buildArtifactTransferLocks=new Map),t()}catch(e){t(e)}},!1),868756,e=>e.a(async(A,t)=>{try{e.s(["BuildsService",()=>R]);var r=e.i(794231),i=e.i(666680),n=e.i(750227),a=e.i(662114),o=e.i(96945),s=e.i(135475);e.i(256554);var l=e.i(118387),d=e.i(848201),u=e.i(988438),c=e.i(354473),h=e.i(250746),g=A([c,h]);[c,h]=g.then?(await g)():g;let D=new Set(a.BUILD_CONFIGURATION_ICON_KEYS),b=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"]),S=["QUEUED","PREPARING","RUNNING"];function p(e,A=null){if(null===e)return A;try{return JSON.parse(e)}catch{return A}}function C(e,A){if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`${A} must be an object`);return e}function f(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function I(e){return null!==e.lastSeenAt&&Date.now()-e.lastSeenAt.getTime()<=(0,l.agentOnlineWindowMs)(e)&&null===e.disconnectedAt}function w(e){return f(p(e.capabilitiesJson,[]))}function m(e,A,t=80){let r=e.trim();if(!r)throw Error(`${A} is required`);if(r.length>t)throw Error(`${A} is too long`);return r}function E(e){return e.split(".").map(e=>Number.parseInt(e,10)||0)}function y(e,A){let t="string"==typeof A.minimumOSVersion?A.minimumOSVersion:null;if("SIMULATOR"!==e.type||!t||!e.osVersion)return e;let r=E(e.osVersion),i=E(t),n=Math.max(r.length,i.length);for(let A=0;A<n&&!((r[A]??0)>(i[A]??0));A+=1)if((r[A]??0)<(i[A]??0))return{...e,available:!1};return e}function B(e){if(e.codebaseId)return e.codebaseId;let A=p(e.snapshotJson,{});if(A&&"object"==typeof A&&!Array.isArray(A)){let e=A.codebase;if(e&&"object"==typeof e&&!Array.isArray(e)){let A=e.id;if("string"==typeof A&&A.trim())return A}}throw Error("Build coordination metadata is unavailable")}function Q(e){return"SUCCEEDED"===e?"SUCCEEDED":"CANCELLED"===e?"CANCELLED":"FAILED"}let k={agent:!0,codebase:{include:{repository:!0}},worktree:{include:{_count:{select:{builds:{where:{status:{in:S}}}}}}},configuration:{include:{source:!0,project:!0}},artifacts:{orderBy:{createdAt:"asc"}},scriptExecutions:{orderBy:[{phase:"asc"},{position:"asc"}]},deployments:{orderBy:{createdAt:"desc"},include:{targetAgent:!0,transfer:{include:{sourceAgent:!0,targetAgent:!0}}}},exports:{orderBy:{createdAt:"desc"}}};class R{agentControl;telemetry;notifications;diskSpace;constructor(e,A,t,r){this.agentControl=e,this.telemetry=A,this.notifications=t,this.diskSpace=r,this.agentControl.registerCompletionHandler(a.IOS_BUILD_JOB_KIND,e=>this.projectBuildCompletion(e)),this.agentControl.registerCompletionHandler(a.IOS_DEPLOY_JOB_KIND,e=>this.projectDeploymentCompletion(e)),this.agentControl.registerCompletionHandler(a.IOS_REMOTE_DEPLOY_JOB_KIND,e=>this.projectDeploymentCompletion(e)),this.agentControl.registerCompletionHandler(a.IOS_ARTIFACT_TRANSFER_UPLOAD_JOB_KIND,async e=>{"SUCCEEDED"!==e.status&&await (0,h.failBuildArtifactTransferForJob)(e.id,e.error||"The build agent could not upload the runnable app")}),this.agentControl.registerCompletionHandler(a.IOS_EXPORT_JOB_KIND,e=>this.projectExportCompletion(e)),this.agentControl.registerCompletionHandler(a.IOS_TEST_RESULTS_JOB_KIND,e=>this.projectGeneratedReportCompletion(e)),this.agentControl.registerCompletionHandler(a.IOS_COVERAGE_REPORT_JOB_KIND,e=>this.projectGeneratedReportCompletion(e)),this.agentControl.registerCompletionHandler(o.COVERAGE_IMPORT_JOB_KIND,e=>this.importedCoverageCompletion(e))}subscribeBuildChanges(e,A){let t=d.agentEventBus.iterate(d.BUILDS_CHANGED_TOPIC);return e||A?(0,r.filterAsyncIterator)(t,async({buildsChanged:{id:t}})=>{let r=await (0,s.getPrismaClient)(),i=await r.build.findUnique({where:{id:t},select:{worktreeId:!0,repository:{select:{apps:{where:{appId:e??void 0},select:{appId:!0},take:1}}}}});return!i||(!A||i.worktreeId===A)&&(!e||!!i.repository?.apps.length)}):t}async repositoryIdForBuild(e){let A=await (0,s.getPrismaClient)();return(await A.build.findUnique({where:{id:e},select:{repositoryId:!0}}))?.repositoryId??null}publish(e){d.agentEventBus.publish((0,d.buildTopic)(e),{buildChanged:{id:e}}),d.agentEventBus.publish(d.BUILDS_CHANGED_TOPIC,{buildsChanged:{id:e}}),d.agentEventBus.publish(d.SIDEBAR_STATUS_CHANGED_TOPIC,{sidebarStatusChanged:!0}),d.agentEventBus.publish(d.ACTION_CENTER_CHANGED_TOPIC,{actionCenterChanged:!0})}async requireWorktree(e,A,t="Agent must be updated to use iOS builds"){let r=await (0,s.getPrismaClient)(),i=await r.worktree.findUnique({where:{id:e},include:{codebase:{include:{agent:!0,repository:!0}}}});if(!i||i.missingAt||"AVAILABLE"!==i.availability)throw Error("Worktree is unavailable");if(!I(i.codebase.agent))throw Error("Agent is offline");if(!w(i.codebase.agent).includes(A))throw Error(t);return i}identity(e){return{codebaseId:e.codebaseId,worktreeId:e.id,branch:e.branch,folder:e.folder,gitDirectory:e.gitDirectory,expectedOrigin:e.codebase.repository.canonicalOrigin,headSha:e.headSha,baseBranch:e.baseBranchOverride??e.codebase.defaultBranch??null}}async ensureProject(e){let A=await (0,s.getPrismaClient)(),t=await A.codebase.findUnique({where:{id:e},select:{repositoryId:!0}});if(!t)throw Error("Codebase not found");return A.codebaseProject.upsert({where:{repositoryId_type:{repositoryId:t.repositoryId,type:"IOS_APP"}},create:{id:(0,i.randomUUID)(),repositoryId:t.repositoryId,type:"IOS_APP"},update:{}})}async project(e){let A=await (0,s.getPrismaClient)(),t=await A.codebase.findUnique({where:{id:e},include:{repository:!0}});if(!t)return null;let r=await A.codebaseProject.findUnique({where:{repositoryId_type:{repositoryId:t.repositoryId,type:"IOS_APP"}},include:{configurations:{orderBy:{name:"asc"},include:{source:{include:{observations:{where:{codebaseId:e},orderBy:{lastParseAttemptAt:"desc"},take:1}}}}}}}),i=await A.codebaseRepositoryBuildScript.findMany({where:{repositoryId:t.repositoryId,script:{deletedAt:null}},orderBy:[{position:"asc"},{script:{name:"asc"}}],include:{script:!0}});return r?{...r,repository:t.repository,allowedScripts:i}:null}async createProject(e){return await this.ensureProject(e),this.project(e)}async projectForWorktree(e){let A=await (0,s.getPrismaClient)(),t=await A.worktree.findUnique({where:{id:e},select:{codebaseId:!0}});return t?this.project(t.codebaseId):null}async saveConfiguration(e){let A=await this.ensureProject(e.codebaseId),t=(0,a.parseBuildSource)({kind:e.sourceKind,relativePath:e.sourcePath}),r=m(e.name,"Configuration name"),n=m(e.scheme,"Scheme",256),o=m(e.buildConfiguration,"Xcode configuration",256);if(!a.BUILD_ACTIONS.includes(e.defaultAction))throw Error("Build action is invalid");let l=e.iconKey?.trim()||null;if(l&&!D.has(l))throw Error("Icon is invalid");let d=(0,a.parseBuildAdvancedSettings)(e.advancedSettings??a.DEFAULT_BUILD_ADVANCED_SETTINGS),u=!0===e.autoExport;if(u&&"ARCHIVE"!==e.defaultAction)throw Error("Auto Export is available only for Archive configurations");let c=e.exportSettings?(0,a.parseBuildExportSettings)(e.exportSettings):null;if(u&&!c)throw Error("Auto Export settings are required");let h=await (0,s.getPrismaClient)(),g=e.id?await h.buildConfiguration.findUnique({where:{id:e.id}}):null;if(e.id&&(!g||g.projectId!==A.id))throw Error("Build configuration not found");let p=await h.buildSource.upsert({where:{projectId_relativePath:{projectId:A.id,relativePath:t.relativePath}},create:{id:(0,i.randomUUID)(),projectId:A.id,kind:t.kind,relativePath:t.relativePath},update:{kind:t.kind}}),C=g?.id??(0,i.randomUUID)();return h.buildConfiguration.upsert({where:{id:C},create:{id:C,projectId:A.id,sourceId:p.id,name:r,iconKey:l,scheme:n,buildConfiguration:o,defaultAction:e.defaultAction,advancedSettingsJson:JSON.stringify(d),autoExport:u,exportSettingsJson:c?JSON.stringify(c):null},update:{sourceId:p.id,name:r,iconKey:l,scheme:n,buildConfiguration:o,defaultAction:e.defaultAction,advancedSettingsJson:JSON.stringify(d),autoExport:u,exportSettingsJson:c?JSON.stringify(c):null},include:{source:!0}})}async deleteConfiguration(e){let A=await (0,s.getPrismaClient)();if(await A.build.findFirst({where:{configurationId:e,status:{in:S}}}))throw Error("Configuration has an active build");let t=await A.buildConfiguration.deleteMany({where:{id:e}});return 1===t.count}async scripts(){return(await (0,s.getPrismaClient)()).buildScript.findMany({where:{deletedAt:null},orderBy:{name:"asc"}})}async saveScript(e){let A=m(e.name,"Script name"),t=e.preBuildScript?.trim()||null,r=e.postBuildScript?.trim()||null;if(!t&&!r)throw Error("A pre-build or post-build script is required");let n=e.timeoutSeconds??300;if(!Number.isInteger(n)||n<1||n>3600)throw Error("Script timeout must be between 1 and 3600 seconds");if(!a.BUILD_SCRIPT_FAILURE_BEHAVIORS.includes(e.failureBehavior))throw Error("Script failure behavior is invalid");let o=await (0,s.getPrismaClient)(),l=e.id??(0,i.randomUUID)(),u=await o.buildScript.upsert({where:{id:l},create:{id:l,name:A,preBuildScript:t,postBuildScript:r,enabledByDefault:e.enabledByDefault,timeoutSeconds:n,failureBehavior:e.failureBehavior},update:{name:A,preBuildScript:t,postBuildScript:r,enabledByDefault:e.enabledByDefault,timeoutSeconds:n,failureBehavior:e.failureBehavior,deletedAt:null}});return d.agentEventBus.publish(d.BUILD_SCRIPTS_CHANGED_TOPIC,{buildScriptsChanged:!0}),u}async deleteScript(e){let A=await (0,s.getPrismaClient)(),t=await A.buildScript.updateMany({where:{id:e,deletedAt:null},data:{deletedAt:new Date}});return await A.codebaseRepositoryBuildScript.deleteMany({where:{scriptId:e}}),t.count&&d.agentEventBus.publish(d.BUILD_SCRIPTS_CHANGED_TOPIC,{buildScriptsChanged:!0}),1===t.count}async setAllowedScripts(e,A){let t=await (0,s.getPrismaClient)(),r=await t.codebase.findUnique({where:{id:e}});if(!r)throw Error("Codebase not found");let i=[...new Set(A)];if((await t.buildScript.findMany({where:{id:{in:i},deletedAt:null}})).length!==i.length)throw Error("Build script not found");return await t.$transaction(async e=>{await e.codebaseRepositoryBuildScript.deleteMany({where:{repositoryId:r.repositoryId}}),i.length&&await e.codebaseRepositoryBuildScript.createMany({data:i.map((e,A)=>({repositoryId:r.repositoryId,scriptId:e,position:A}))})}),this.project(e)}async waitForJob(e,A=12e4){let t=d.agentEventBus.iterate((0,d.agentJobChangedTopic)(e)),r=Date.now()+A;try{for(;Date.now()<r;){let A=await this.agentControl.getJob(e);if(!A)throw Error("Agent job disappeared");if(b.has(A.status))return A;await Promise.race([t.next(),new Promise(e=>setTimeout(e,Math.max(1,r-Date.now())))])}throw await this.agentControl.cancelJob(e),Error("Agent did not respond in time")}finally{await t.return?.()}}result(e){if("SUCCEEDED"!==e.status)throw Error(e.error||"Agent operation failed");return C(p(e.resultJson,{}),"agent result")}async discoverSources(e,A){let t=await this.requireWorktree(e,a.IOS_SOURCE_DISCOVER_JOB_KIND),r=await this.agentControl.createJob({agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,kind:a.IOS_SOURCE_DISCOVER_JOB_KIND,payload:this.identity(t),idempotencyKey:`ios:source:discover:${A}:${t.id}`,timeoutSeconds:60,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(r.id));return Array.isArray(e.sources)?e.sources:[]}finally{let e=await (0,s.getPrismaClient)();await e.agentJob.deleteMany({where:{id:r.id,visibility:"SYSTEM"}})}}async reparse(e,A,t){let r=await this.requireWorktree(A,a.IOS_SOURCE_PARSE_JOB_KIND),n=await (0,s.getPrismaClient)(),o=await n.buildConfiguration.findUnique({where:{id:e},include:{source:{include:{project:!0}}}});if(!o||o.source.project.repositoryId!==r.codebase.repositoryId)throw Error("Build configuration is not available for this worktree");let l=`worktree:${r.id}`,d=await n.buildSourceObservation.findUnique({where:{sourceId_scopeKey:{sourceId:o.sourceId,scopeKey:l}}}),u=new Date;await n.buildSourceObservation.upsert({where:{sourceId_scopeKey:{sourceId:o.sourceId,scopeKey:l}},create:{id:(0,i.randomUUID)(),sourceId:o.sourceId,scopeKey:l,codebaseId:r.codebaseId,worktreeId:r.id,status:"PARSING",lastParseAttemptAt:u},update:{status:"PARSING",error:null,lastParseAttemptAt:u}});let c=await this.agentControl.createJob({agentId:r.codebase.agentId,codebaseId:r.codebaseId,worktreeId:r.id,kind:a.IOS_SOURCE_PARSE_JOB_KIND,payload:{...this.identity(r),source:{kind:o.source.kind,relativePath:o.source.relativePath},scheme:o.scheme},idempotencyKey:`ios:source:parse:${t}:${o.id}:${r.id}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(c.id)),A=f(e.schemes),t=f(e.configurations),i=A.includes(o.scheme)&&t.includes(o.buildConfiguration);return n.buildSourceObservation.update({where:{sourceId_scopeKey:{sourceId:o.sourceId,scopeKey:l}},data:{status:i?"VALID":"INVALID",schemesJson:JSON.stringify(A),configurationsJson:JSON.stringify(t),testPlansJson:JSON.stringify(f(e.testPlans)),error:i?null:"The saved scheme or configuration is no longer available",stale:!1,headSha:"string"==typeof e.headSha?e.headSha:r.headSha,xcodeVersion:"string"==typeof e.xcodeVersion?e.xcodeVersion:null,lastParsedAt:new Date}})}catch(A){let e=A instanceof Error?A.message:String(A);return n.buildSourceObservation.update({where:{sourceId_scopeKey:{sourceId:o.sourceId,scopeKey:l}},data:{status:"ERROR",error:e,stale:!!d?.lastParsedAt}})}finally{await n.agentJob.deleteMany({where:{id:c.id,visibility:"SYSTEM"}})}}async inspectSource(e){let A=await this.requireWorktree(e.worktreeId,a.IOS_SOURCE_PARSE_JOB_KIND),t=(0,a.parseBuildSource)({kind:e.sourceKind,relativePath:e.sourcePath}),r=await this.agentControl.createJob({agentId:A.codebase.agentId,codebaseId:A.codebaseId,worktreeId:A.id,kind:a.IOS_SOURCE_PARSE_JOB_KIND,payload:{...this.identity(A),source:t,scheme:e.scheme?.trim()||null,configuration:e.configuration?.trim()||null},idempotencyKey:`ios:source:inspect:${e.requestId}:${A.id}:${t.relativePath}:${e.scheme??""}:${e.configuration??""}`,timeoutSeconds:120,visibility:"SYSTEM"});try{var i;let e=this.result(await this.waitForJob(r.id));return{source:t,schemes:f(e.schemes),configurations:f(e.configurations),testPlans:f(e.testPlans),signingRequirements:(i=e.signingRequirements,Array.isArray(i)?i.flatMap(e=>!e||"object"!=typeof e||Array.isArray(e)||"string"!=typeof e.bundleId||"string"!=typeof e.name||"string"!=typeof e.target?[]:[{bundleId:e.bundleId,name:e.name,target:e.target,platform:"string"==typeof e.platform?e.platform:null,teamId:"string"==typeof e.teamId?e.teamId:null,provisioningProfileSpecifier:"string"==typeof e.provisioningProfileSpecifier?e.provisioningProfileSpecifier:null}]):[]),headSha:"string"==typeof e.headSha?e.headSha:A.headSha,xcodeVersion:"string"==typeof e.xcodeVersion?e.xcodeVersion:null}}finally{let e=await (0,s.getPrismaClient)();await e.agentJob.deleteMany({where:{id:r.id,visibility:"SYSTEM"}})}}async destinations(e){let A=await this.requireWorktree(e.worktreeId,a.IOS_DESTINATIONS_JOB_KIND),t=await (0,s.getPrismaClient)(),r=await t.buildConfiguration.findUnique({where:{id:e.configurationId},include:{source:{include:{project:!0}}}});if(!r||r.source.project.repositoryId!==A.codebase.repositoryId)throw Error("Build configuration is not available for this worktree");let i=e.action??r.defaultAction;if(!a.BUILD_ACTIONS.includes(i))throw Error("Build action is invalid");let n=(0,a.genericBuildDestinations)(i);if("ARCHIVE"===i)return n;let o=await this.agentControl.createJob({agentId:A.codebase.agentId,codebaseId:A.codebaseId,worktreeId:A.id,kind:a.IOS_DESTINATIONS_JOB_KIND,payload:{...this.identity(A),source:{kind:r.source.kind,relativePath:r.source.relativePath},scheme:r.scheme,configuration:r.buildConfiguration,action:i},idempotencyKey:`ios:destinations:${e.requestId}:${r.id}:${A.id}:${i}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(o.id));return(Array.isArray(e.destinations)?e.destinations:[]).map(e=>(0,a.parseBuildDestination)(e)).filter(e=>!1!==e.available)}finally{await t.agentJob.deleteMany({where:{id:o.id,visibility:"SYSTEM"}})}}async signingOptionsForBuild(e){let A=await (0,s.getPrismaClient)(),t=await A.build.findUnique({where:{id:e},include:{artifacts:!0}}),r=t?.artifacts.find(e=>"ARCHIVE"===e.kind);if(!t||"SUCCEEDED"!==t.status||!t.worktreeId)throw Error("A successful archive build is required");if(!r)throw Error("Build does not contain an archive");let i=await this.requireWorktree(t.worktreeId,a.IOS_SIGNING_INSPECT_JOB_KIND),n=await this.agentControl.createJob({agentId:i.codebase.agentId,codebaseId:i.codebaseId,worktreeId:i.id,kind:a.IOS_SIGNING_INSPECT_JOB_KIND,payload:{buildId:t.id,codebaseId:i.codebaseId,artifactDirectory:t.artifactDirectory,archiveRelativePath:r.relativePath},idempotencyKey:`ios:signing:${t.id}:${r.id}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(n.id));return{teams:Array.isArray(e.teams)?e.teams:[],identities:Array.isArray(e.identities)?e.identities:[],profiles:Array.isArray(e.profiles)?e.profiles:[],bundles:Array.isArray(e.bundles)?e.bundles:[]}}finally{await A.agentJob.deleteMany({where:{id:n.id,visibility:"SYSTEM"}})}}async runAgentsForBuild(e){let A=await (0,s.getPrismaClient)(),t=await A.build.findUnique({where:{id:e},include:{artifacts:!0,agent:!0,worktree:!0}}),r=t?.artifacts.find(e=>"RUNNABLE_APP"===e.kind);if(!t||"SUCCEEDED"!==t.status||!r||!t.agentId)throw Error("A successful runnable build is required");let i=C(p(r.metadataJson,{}),"runnable metadata"),n=new Set(f(i.architectures).map(e=>"x64"===e?"x86_64":e)),o=await (0,c.cachedArtifact)(t.id,r.id),l=t.agent?w(t.agent):[];return(await A.agent.findMany({orderBy:{name:"asc"}})).map(e=>{let A=e.id===t.agentId,r=null;return e.osVersion.toLocaleLowerCase().startsWith("macos")?I(e)?A?w(e).includes(a.IOS_RUN_DESTINATIONS_JOB_KIND)&&w(e).includes(a.IOS_DEPLOY_JOB_KIND)||(r="AGENT_UPDATE_REQUIRED"):w(e).includes(a.IOS_AGENT_RUN_DESTINATIONS_JOB_KIND)&&w(e).includes(a.IOS_REMOTE_DEPLOY_JOB_KIND)?o||t.agent&&I(t.agent)&&l.includes(a.IOS_ARTIFACT_TRANSFER_UPLOAD_JOB_KIND)?"SIMULATOR"===t.destinationType&&n.size>0&&!n.has("x64"===e.architecture?"x86_64":e.architecture)&&(r="INCOMPATIBLE_ARCHITECTURE"):r="BUILD_AGENT_UNAVAILABLE":r="AGENT_UPDATE_REQUIRED":r="OFFLINE":r="NOT_MACOS",{agent:e,isBuildAgent:A,available:null===r,unavailableReason:r}}).sort((e,A)=>Number(A.isBuildAgent)-Number(e.isBuildAgent)||e.agent.name.localeCompare(A.agent.name))}async destinationsForBuild(e,A,t){let r=await (0,s.getPrismaClient)(),i=await r.build.findUnique({where:{id:e},include:{artifacts:!0}});if(!i||"SUCCEEDED"!==i.status||!i.artifacts.some(e=>"RUNNABLE_APP"===e.kind))throw Error("A successful runnable build is required");let n=i.artifacts.find(e=>"RUNNABLE_APP"===e.kind),o=C(p(n.metadataJson,{}),"runnable metadata"),l=t??i.agentId;if(!l)throw Error("Build agent is unavailable");if(l!==i.agentId){let e=(await this.runAgentsForBuild(i.id)).find(e=>e.agent.id===l);if(!e?.available)throw Error("The selected run agent is unavailable");let t=await this.agentControl.createJob({agentId:l,kind:a.IOS_AGENT_RUN_DESTINATIONS_JOB_KIND,payload:{destinationType:i.destinationType},idempotencyKey:`ios:agent-build-destinations:${m(A,"Request ID",200)}:${i.id}:${l}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(t.id));return(Array.isArray(e.destinations)?e.destinations:[]).map(e=>(0,a.parseBuildDestination)(e)).map(e=>y(e,o)).filter(e=>e.type===i.destinationType&&!e.generic)}finally{await r.agentJob.deleteMany({where:{id:t.id,visibility:"SYSTEM"}})}}if(!i.worktreeId)throw Error("The build worktree is unavailable");let d=await this.requireWorktree(i.worktreeId,a.IOS_RUN_DESTINATIONS_JOB_KIND);if(i.agentId!==d.codebase.agentId||i.codebaseId!==d.codebaseId)throw Error("The build no longer belongs to this worktree checkout");let u=await this.agentControl.createJob({agentId:d.codebase.agentId,codebaseId:d.codebaseId,worktreeId:d.id,kind:a.IOS_RUN_DESTINATIONS_JOB_KIND,payload:{...this.identity(d),destinationType:i.destinationType},idempotencyKey:`ios:build-destinations:${m(A,"Request ID",200)}:${i.id}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(u.id));return(Array.isArray(e.destinations)?e.destinations:[]).map(e=>(0,a.parseBuildDestination)(e)).map(e=>y(e,o)).filter(e=>e.type===i.destinationType&&!e.generic)}finally{await r.agentJob.deleteMany({where:{id:u.id,visibility:"SYSTEM"}})}}async startBuild(e){let A=m(e.requestId,"Request ID",200),t=`${e.worktreeId}:${A}`,r=await (0,s.getPrismaClient)(),o=await r.build.findUnique({where:{requestKey:t},include:k});if(o){if(this.telemetry){let e=p(o.snapshotJson,{}),A=C(e.configuration??{},"build configuration snapshot"),t=C(e.destination??{},"build destination snapshot");await this.telemetry.addBuildSeparator({buildId:o.id,name:`Build \xb7 ${String(A.name??"iOS")} \xb7 ${String(t.name??"Destination")}`,clientTime:o.createdAt})}return o}let l=await this.requireWorktree(e.worktreeId,a.IOS_BUILD_JOB_KIND);if(await this.diskSpace?.assertWorktreeCanStart(l.id),e.worktreeCoverage&&!w(l.codebase.agent).includes(a.IOS_COVERAGE_REPORT_JOB_KIND))throw Error("Build agent must be updated for worktree coverage");let d=await r.buildConfiguration.findUnique({where:{id:e.configurationId},include:{source:{include:{project:!0}}}});if(!d||d.source.project.repositoryId!==l.codebase.repositoryId)throw Error("Build configuration is not available for this worktree");let c=await r.buildSourceObservation.findUnique({where:{sourceId_scopeKey:{sourceId:d.sourceId,scopeKey:`worktree:${l.id}`}}}),h=e.action??d.defaultAction;if(!a.BUILD_ACTIONS.includes(h))throw Error("Build action is invalid");if(e.exportWhenComplete&&"ARCHIVE"!==h)throw Error("Export when complete is available only for Archive builds");let g="ARCHIVE"===h&&(e.exportWhenComplete??d.autoExport),f=e.exportSettings??p(d.exportSettingsJson,null),I=g||f?(0,a.parseBuildExportSettings)(f):null;if(g&&!I)throw Error("Export settings are required when automatic export is enabled");let E=(0,a.parseBuildDestination)(e.destination);if(!a.BUILD_DESTINATION_TYPES.includes(E.type))throw Error("Destination is invalid");if("ARCHIVE"===h&&("PHYSICAL_DEVICE"!==E.type||!E.generic))throw Error("Archive builds require the generic physical iOS destination");if(E.generic&&!a.GENERIC_BUILD_DESTINATION_ACTIONS.includes(h))throw Error("This build action requires a concrete destination");let y=C(p(d.advancedSettingsJson,{}),"saved advanced settings"),B=e.advancedSettings?C(e.advancedSettings,"advanced settings override"):{},Q=(0,a.parseBuildAdvancedSettings)({...y,...B,buildSettingOverrides:{...C(y.buildSettingOverrides??{},"saved overrides"),...C(B.buildSettingOverrides??{},"run overrides")}});if("TEST_WITHOUT_BUILDING"===h){if(!Q.priorBuildForTestingId)throw Error("Test Without Building requires a prior Build for Testing result");let e=await r.build.findUnique({where:{id:Q.priorBuildForTestingId},include:{artifacts:{where:{kind:{in:["TEST_PRODUCTS","XCTESTRUN"]}},orderBy:{createdAt:"asc"}}}});if(!e||"SUCCEEDED"!==e.status||"BUILD_FOR_TESTING"!==e.action)throw Error("Test Without Building requires a successful Build for Testing result");if(e.agentId!==l.codebase.agentId||e.worktreeId!==l.id||e.configurationId!==d.id)throw Error("The prior Build for Testing result is not compatible with this agent, worktree, and configuration");if(e.destinationType!==E.type)throw Error("The prior Build for Testing result uses a different destination type");let A=C(p(e.snapshotJson,{}),"prior Build for Testing snapshot"),t=C(A.configuration??{},"prior Build for Testing configuration snapshot"),i=(0,a.parseBuildAdvancedSettings)(t.advancedSettings??{});if(Q.testPlan&&i.testPlan&&Q.testPlan!==i.testPlan)throw Error("The selected test plan does not match the prior Build for Testing result");let o=Q.testPlan??i.testPlan??null,s=e.artifacts.filter(e=>"TEST_PRODUCTS"===e.kind&&e.relativePath.endsWith(".xctestproducts")),u=e.artifacts.filter(e=>"XCTESTRUN"===e.kind&&e.relativePath.endsWith(".xctestrun"));if(s.length>1)throw Error("The prior Build for Testing result contains multiple test-products artifacts");let c=s[0];if(c||1!==u.length||(c=u[0]),!c&&u.length>1&&o&&(c=u.find(e=>C(p(e.metadataJson,{}),"test-run artifact metadata").testPlan===o||e.relativePath.endsWith(`/${o}.xctestrun`)||e.relativePath===`${o}.xctestrun`)),!c&&u.length>1)throw Error("Select a test plan to choose among the captured .xctestrun artifacts");let h=c?.relativePath??"test-products.xctestproducts",g=(0,n.resolve)(e.artifactDirectory),f=(0,n.resolve)(g,h),I=(0,n.relative)(g,f);if(!I||I.startsWith("..")||(0,n.isAbsolute)(I))throw Error("The prior Build for Testing artifact path is invalid");Q={...Q,testPlan:o,priorTestProductsPath:h.endsWith(".xctestproducts")?f:null,priorXctestrunPath:h.endsWith(".xctestrun")?f:null}}let D=await r.codebaseRepositoryBuildScript.findMany({where:{repositoryId:l.codebase.repositoryId,script:{deletedAt:null}},orderBy:[{position:"asc"},{script:{name:"asc"}}],include:{script:!0}}),b=new Set(e.scriptIds??[]);if([...b].some(e=>!D.some(A=>A.scriptId===e)))throw Error("A selected build script is not allowed for this codebase");let S=D.filter(e=>b.has(e.scriptId)),R=(0,i.randomUUID)(),v=(0,u.effectiveBuildsDirectory)(l.codebase.agent);if(!v)throw Error("The agent builds directory is unavailable");let G=(0,n.join)(v,R),T={kind:d.source.kind,relativePath:d.source.relativePath},M=function(e){var A;let t=e.advancedSettings,r="TEST_WITHOUT_BUILDING"===e.action,i=["xcodebuild",...r?[]:[..."PACKAGE"===e.source.kind?[]:"PROJECT"===e.source.kind?["-project",e.source.relativePath]:["-workspace",e.source.relativePath],"-scheme",e.scheme,"-configuration",e.configuration],"-destination",(A=e.destination).generic?"SIMULATOR"===A.type?"generic/platform=iOS Simulator":"generic/platform=iOS":"SIMULATOR"===A.type?`platform=iOS Simulator,id=${A.id}`:`platform=iOS,id=${A.id}`,"-hideShellScriptEnvironment","-resultBundlePath",(0,n.join)(e.artifactDirectory,"result.xcresult")];for(let e of(!r&&("RESOLVED_ONLY"===t.packageResolution?i.push("-onlyUsePackageVersionsFromResolvedFile"):"SKIP_UPDATES"===t.packageResolution?i.push("-skipPackageUpdates"):"DISABLE_AUTOMATIC"===t.packageResolution&&i.push("-disableAutomaticPackageResolution"),t.disablePackageRepositoryCache&&i.push("-disablePackageRepositoryCache"),"PROJECT_DEFAULT"!==t.signingStyle&&i.push(`CODE_SIGN_STYLE=${"AUTOMATIC"===t.signingStyle?"Automatic":"Manual"}`),t.developmentTeam&&i.push(`DEVELOPMENT_TEAM=${t.developmentTeam}`),t.codeSignIdentity&&i.push(`CODE_SIGN_IDENTITY=${t.codeSignIdentity}`),t.provisioningProfileSpecifier&&i.push(`PROVISIONING_PROFILE_SPECIFIER=${t.provisioningProfileSpecifier}`),t.productBundleIdentifier&&i.push(`PRODUCT_BUNDLE_IDENTIFIER=${t.productBundleIdentifier}`),t.allowProvisioningUpdates&&i.push("-allowProvisioningUpdates"),t.allowProvisioningDeviceRegistration&&i.push("-allowProvisioningDeviceRegistration")),t.testPlan&&i.push("-testPlan",t.testPlan),t.codeCoverage&&i.push("-enableCodeCoverage","YES"),null!==t.parallelTesting&&i.push("-parallel-testing-enabled",t.parallelTesting?"YES":"NO"),null!==t.parallelTestingWorkers&&i.push("-parallel-testing-worker-count",String(t.parallelTestingWorkers)),t.onlyTesting))i.push(`-only-testing:${e}`);for(let e of t.skipTesting)i.push(`-skip-testing:${e}`);if(!r)for(let[e,A]of Object.entries(t.buildSettingOverrides))i.push(`${e}=${A}`);"ARCHIVE"===e.action&&i.push("-archivePath",(0,n.join)(e.artifactDirectory,"archive.xcarchive")),"BUILD_FOR_TESTING"===e.action&&i.push("-testProductsPath",(0,n.join)(e.artifactDirectory,"test-products.xctestproducts")),"TEST_WITHOUT_BUILDING"===e.action&&t.priorTestProductsPath&&i.push("-testProductsPath",t.priorTestProductsPath),"TEST_WITHOUT_BUILDING"===e.action&&!t.priorTestProductsPath&&t.priorXctestrunPath&&i.push("-xctestrun",t.priorXctestrunPath),i.push({BUILD:"build",TEST:"test",ANALYZE:"analyze",ARCHIVE:"archive",BUILD_FOR_TESTING:"build-for-testing",TEST_WITHOUT_BUILDING:"test-without-building"}[e.action]);let a=i.map(e=>/^[A-Za-z0-9_./:=,-]+$/.test(e)?e:JSON.stringify(e)).join(" ");return`cd ${JSON.stringify(e.folder)} && xcrun ${a}`}({folder:l.folder,source:T,scheme:d.scheme,configuration:d.buildConfiguration,destination:E,action:h,advancedSettings:Q,artifactDirectory:G}),N=S.map(({script:e,position:A})=>({id:e.id,name:e.name,preBuildScript:e.preBuildScript,postBuildScript:e.postBuildScript,timeoutSeconds:e.timeoutSeconds,failureBehavior:e.failureBehavior,position:A})),O=await this.telemetry?.buildSettings(E.type,{requestOrigin:e.telemetryRequestOrigin}),H={repository:{id:l.codebase.repository.id,name:l.codebase.repository.name,canonicalOrigin:l.codebase.repository.canonicalOrigin},codebase:{id:l.codebase.id,folder:l.codebase.folder},worktree:{id:l.id,folder:l.folder,branch:l.branch,headSha:l.headSha,codeStateHash:l.codeStateHash,hasStagedChanges:l.hasStagedChanges,hasUnstagedChanges:l.hasUnstagedChanges},agent:{id:l.codebase.agent.id,name:l.codebase.agent.name,hostname:l.codebase.agent.hostname},configuration:{id:d.id,name:d.name,iconKey:d.iconKey,source:T,scheme:d.scheme,buildConfiguration:d.buildConfiguration,action:h,advancedSettings:Q,autoExport:g,exportSettings:I,parse:c?{status:c.status,schemes:p(c.schemesJson,[]),configurations:p(c.configurationsJson,[]),testPlans:p(c.testPlansJson,[]),headSha:c.headSha,xcodeVersion:c.xcodeVersion,parsedAt:c.lastParsedAt?.toISOString()??null}:{status:"UNPARSED",schemes:[],configurations:[],testPlans:[],headSha:null,xcodeVersion:null,parsedAt:null}},destination:E,scripts:N,...O?{telemetry:O}:{},worktreeCoverage:!0===e.worktreeCoverage},U=new Date,_=r.build.create({data:{id:R,requestKey:t,requestId:A,agentId:l.codebase.agentId,codebaseId:l.codebaseId,worktreeId:l.id,repositoryId:l.codebase.repository.id,configurationId:d.id,status:"QUEUED",action:h,destinationType:E.type,destinationJson:JSON.stringify(E),snapshotJson:JSON.stringify(H),commandSummary:M,artifactDirectory:G,createdAt:U,scriptExecutions:{create:N.flatMap(e=>[...e.preBuildScript?[{id:(0,i.randomUUID)(),scriptId:e.id,phase:"PRE_BUILD",position:e.position,nameSnapshot:e.name,sourceSnapshot:e.preBuildScript,timeoutSeconds:e.timeoutSeconds,failureBehavior:e.failureBehavior}]:[],...e.postBuildScript?[{id:(0,i.randomUUID)(),scriptId:e.id,phase:"POST_BUILD",position:e.position,nameSnapshot:e.name,sourceSnapshot:e.postBuildScript,timeoutSeconds:e.timeoutSeconds,failureBehavior:e.failureBehavior}]:[]])}}});if(this.telemetry){let e=(0,i.randomUUID)();await r.$transaction([_,r.telemetryEntry.create({data:{id:e,entryType:"SEPARATOR",clientTime:U,receivedAt:U,separatorKind:"BUILD",separatorName:`Build \xb7 ${d.name} \xb7 ${E.name}`.slice(0,100),buildId:R}})]),this.telemetry.notifyChange([e],"BUILD_SEPARATOR_ADDED")}else await _;try{let t=await this.agentControl.createJob({agentId:l.codebase.agentId,codebaseId:l.codebaseId,worktreeId:l.id,kind:a.IOS_BUILD_JOB_KIND,payload:{...this.identity(l),buildId:R,artifactDirectory:G,source:T,scheme:d.scheme,configuration:d.buildConfiguration,action:h,destination:E,advancedSettings:Q,scripts:N,...O?{telemetry:O}:{},worktreeCoverage:!0===e.worktreeCoverage},idempotencyKey:`ios:build:${A}:${l.id}`,timeoutSeconds:604800});await r.build.update({where:{id:R},data:{jobId:t.id}})}catch(e){throw await r.build.update({where:{id:R},data:{status:"FAILED",errorCode:"QUEUE_FAILED",error:e instanceof Error?e.message:String(e),finishedAt:new Date}}),e}return this.publish(R),r.build.findUniqueOrThrow({where:{id:R},include:k})}async rebuildBuild(e,A,t){let r=await (0,s.getPrismaClient)(),i=await r.build.findUnique({where:{id:e},select:{worktreeId:!0,configurationId:!0,destinationJson:!0,action:!0,snapshotJson:!0}});if(!i)throw Error("Build not found");let n=C(p(i.snapshotJson,{}),"build snapshot"),a=C(n.worktree??{},"build worktree snapshot"),o=C(n.configuration??{},"build configuration snapshot"),l=Array.isArray(n.scripts)?n.scripts:[],d=i.worktreeId??("string"==typeof a.id?a.id:null),u=i.configurationId??("string"==typeof o.id?o.id:null);if(!d||!u)throw Error("The original build settings are unavailable");return this.startBuild({worktreeId:d,configurationId:u,destination:p(i.destinationJson,{}),scriptIds:l.flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];let A=e.id;return"string"==typeof A?[A]:[]}),action:i.action,advancedSettings:o.advancedSettings,exportWhenComplete:!0===o.autoExport,...Object.hasOwn(o,"exportSettings")?{exportSettings:o.exportSettings}:{},requestId:A,...t?{telemetryRequestOrigin:t}:{}})}async startWorktreeCoverage(e){let A=await (0,s.getPrismaClient)(),t=await A.worktree.findUnique({where:{id:e.worktreeId},select:{baseBranchOverride:!0,codebase:{select:{defaultBranch:!0}}}});if(!t||!(t.baseBranchOverride??t.codebase.defaultBranch))throw Error("A base branch is required for worktree coverage");let r=C(e.advancedSettings??{},"coverage advanced settings");return this.startBuild({...e,action:"TEST",advancedSettings:{...r,codeCoverage:!0,parseTestResults:!0},worktreeCoverage:!0})}async importCoverageReport(e){let A=await (0,s.getPrismaClient)(),t=await this.requireWorktree(e.worktreeId,o.COVERAGE_IMPORT_JOB_KIND,"Agent must be updated to import coverage reports"),r=t.baseBranchOverride??t.codebase.defaultBranch??null,a=(e.format||"AUTO").toUpperCase();if(!o.COVERAGE_REPORT_FORMATS.includes(a))throw Error("Coverage format must be AUTO, LCOV, or ISTANBUL");let l=m(e.buildName??"Coverage report","Build name",200),d=m(e.reportPath,"Coverage file",4e3),c=m(e.requestId,"Request ID",200),h=`coverage:${e.worktreeId}:${c}`,g=await A.build.findUnique({where:{requestKey:h}});if(g)return g;let p=(0,i.randomUUID)(),C=(0,u.effectiveBuildsDirectory)(t.codebase.agent);if(!C)throw Error("The agent builds directory is unavailable");let f={repository:{id:t.codebase.repository.id,name:t.codebase.repository.name,canonicalOrigin:t.codebase.repository.canonicalOrigin},codebase:{id:t.codebase.id,folder:t.codebase.folder},worktree:{id:t.id,folder:t.folder,branch:t.branch,headSha:t.headSha,codeStateHash:t.codeStateHash,hasStagedChanges:t.hasStagedChanges,hasUnstagedChanges:t.hasUnstagedChanges},agent:{id:t.codebase.agent.id,name:t.codebase.agent.name,hostname:t.codebase.agent.hostname},configuration:{name:l},coverageImport:{reportPath:d,format:a,baseBranch:r},worktreeCoverage:!0},I={type:"HOST",id:t.codebase.agent.id,name:t.codebase.agent.name,platform:t.codebase.agent.architecture,osVersion:t.codebase.agent.osVersion||null,state:"Connected"},w=await A.build.create({data:{id:p,requestKey:h,requestId:c,agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,repositoryId:t.codebase.repository.id,status:"RUNNING",action:"TEST",destinationType:"HOST",destinationJson:JSON.stringify(I),snapshotJson:JSON.stringify(f),commandSummary:`Import coverage from ${d}`,artifactDirectory:(0,n.join)(C,p),startedAt:new Date}}),E=null;try{await A.buildReport.create({data:{id:(0,i.randomUUID)(),buildId:p,kind:"CODE_COVERAGE",source:"WORKTREE",status:"PENDING"}}),this.publish(p);let e=await this.agentControl.createJob({agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,kind:o.COVERAGE_IMPORT_JOB_KIND,payload:{buildId:p,codebaseId:t.codebaseId,worktreeId:t.id,folder:t.folder,reportPath:d,format:a,baseBranch:r},idempotencyKey:`coverage:import:${c}:${p}`,timeoutSeconds:300,visibility:"SYSTEM"});return E=e.id,await A.build.update({where:{id:p},data:{jobId:e.id}}),{...w,jobId:e.id}}catch(r){E&&await this.agentControl.cancelJob(E).catch(()=>void 0);let e=r instanceof Error?r.message:String(r),t=new Date;throw await A.$transaction(async A=>{await A.buildReport.upsert({where:{buildId_kind:{buildId:p,kind:"CODE_COVERAGE"}},create:{id:(0,i.randomUUID)(),buildId:p,kind:"CODE_COVERAGE",source:"WORKTREE",status:"FAILED",error:e,finishedAt:t},update:{status:"FAILED",error:e,finishedAt:t}}),await A.build.update({where:{id:p},data:{status:"FAILED",errorCode:"QUEUE_FAILED",error:e,finishedAt:t}})}),this.publish(p),r}}async importedCoverageCompletion(e){let A=C(p(e.payloadJson,{}),"coverage import payload");if("string"!=typeof A.buildId)return;let t=A.buildId,r=C(p(e.resultJson,{}),"coverage import result"),n="SUCCEEDED"===e.status&&!!r.report&&"object"==typeof r.report,a=await (0,s.getPrismaClient)();await a.$transaction(async A=>{n?await this.upsertReportProjection(A,t,r.report,"WORKTREE"):await A.buildReport.upsert({where:{buildId_kind:{buildId:t,kind:"CODE_COVERAGE"}},create:{id:(0,i.randomUUID)(),buildId:t,kind:"CODE_COVERAGE",source:"WORKTREE",status:"FAILED",error:e.error||"Coverage import failed",finishedAt:new Date},update:{status:"FAILED",error:e.error||"Coverage import failed",finishedAt:new Date}}),await A.build.update({where:{id:t},data:{status:n?"SUCCEEDED":"FAILED",error:n?null:e.error||"Coverage import failed",finishedAt:new Date}})}),this.publish(t)}async generateReport(e,A,t){let r=await (0,s.getPrismaClient)(),n=await r.buildReport.findUnique({where:{buildId_kind:{buildId:e,kind:A}},include:{artifact:!0}});if(n?.status==="READY")return n;let o=await r.build.findUnique({where:{id:e},include:{agent:!0,artifacts:!0}});if(!o)throw Error("Build not found");if(S.includes(o.status))throw Error("Wait for the build to finish before generating reports");if(!o.agentId||!o.agent||!I(o.agent))throw Error("Build agent is offline");let l="TEST_RESULTS"===A?a.IOS_TEST_RESULTS_JOB_KIND:a.IOS_COVERAGE_REPORT_JOB_KIND;if(!w(o.agent).includes(l))throw Error("Build agent must be updated to generate reports");if(!o.artifacts.some(e=>"RESULT_BUNDLE"===e.kind))throw Error("The build result bundle is unavailable");if("TEST_RESULTS"===A&&!["TEST","TEST_WITHOUT_BUILDING"].includes(o.action))throw Error("This build did not run tests");let d=await r.buildReport.upsert({where:{buildId_kind:{buildId:e,kind:A}},create:{id:(0,i.randomUUID)(),buildId:e,kind:A,source:"MANUAL",status:"PENDING"},update:{source:"MANUAL",status:"PENDING",error:null,finishedAt:null}});this.publish(e);let u=B(o),c=await this.agentControl.createJob({agentId:o.agentId,codebaseId:u,worktreeId:o.worktreeId,kind:l,payload:{buildId:e,artifactDirectory:o.artifactDirectory,codebaseId:u,reportKind:A,source:"MANUAL"},idempotencyKey:`ios:report:${A}:${m(t,"Request ID",200)}:${e}`,timeoutSeconds:180,visibility:"SYSTEM"});try{return await this.waitForJob(c.id,17e4),r.buildReport.findUniqueOrThrow({where:{id:d.id},include:{artifact:!0}})}finally{await r.agentJob.deleteMany({where:{id:c.id,visibility:"SYSTEM"}})}}async coverageHistory(e){return(await (0,s.getPrismaClient)()).buildReport.findMany({where:{kind:"CODE_COVERAGE",source:"WORKTREE",build:{worktreeId:e}},orderBy:{createdAt:"desc"},take:50,select:{id:!0,buildId:!0,artifactId:!0,kind:!0,source:!0,status:!0,summaryJson:!0,error:!0,createdAt:!0,updatedAt:!0,finishedAt:!0,artifact:!0,build:{select:{id:!0,status:!0,action:!0,destinationType:!0,destinationJson:!0,snapshotJson:!0,createdAt:!0,startedAt:!0,finishedAt:!0,updatedAt:!0,worktree:{select:{headSha:!0,codeStateHash:!0,hasStagedChanges:!0,hasUnstagedChanges:!0,lastCheckedAt:!0,_count:{select:{builds:{where:{status:{in:S}}}}}}},artifacts:{orderBy:{createdAt:"asc"}}}}}})}async reportsForBuild(e,A,t=!0){return(await (0,s.getPrismaClient)()).buildReport.findMany({where:{buildId:e,...A?{kind:A}:{}},orderBy:{createdAt:"asc"},...t?{}:{omit:{dataJson:!0}},include:{artifact:!0}})}async reportData(e){let A=await (0,s.getPrismaClient)(),t=await A.buildReport.findUnique({where:{id:e},select:{dataJson:!0}});return t?.dataJson??"{}"}async builds(e={}){let A=await (0,s.getPrismaClient)(),t=Math.max(1,Math.min(e.first??50,200)),r=await A.build.findMany({where:{...e.status?{status:e.status}:{},...e.codebaseId?{codebaseId:e.codebaseId}:{},...e.worktreeId?{worktreeId:e.worktreeId}:{},...e.appId?{repository:{apps:{some:{appId:e.appId}}}}:{}},orderBy:[{createdAt:"desc"},{id:"desc"}],...e.after?{cursor:{id:e.after},skip:1}:{},take:t+1,include:k});return{items:r.slice(0,t),nextCursor:r.length>t?r[t-1].id:null}}async getBuild(e){return(await (0,s.getPrismaClient)()).build.findUnique({where:{id:e},include:k})}async deleteBuilds(e){let A=[...new Set(e)];if(!A.length)return 0;if(A.length>200)throw Error("At most 200 builds can be deleted at once");let t=await (0,s.getPrismaClient)(),r=await t.build.findMany({where:{id:{in:A}},select:{id:!0,status:!0,artifactDirectory:!0,snapshotJson:!0,agentId:!0,agent:{select:{capabilitiesJson:!0}},codebaseId:!0,worktreeId:!0,deployments:{where:{status:{in:S}},select:{id:!0}},exports:{where:{status:{in:S}},select:{id:!0}}}});if(r.some(e=>S.includes(e.status)))throw Error("Running builds cannot be deleted");if(r.some(e=>e.deployments.length>0||e.exports.length>0))throw Error("Builds with running deployments or exports cannot be deleted");for(let e of r){if(!(0,n.isAbsolute)(e.artifactDirectory)||(0,n.basename)(e.artifactDirectory)!==e.id)throw Error(`Build folder is invalid for ${e.id}`);if(e.agentId){let A=B(e);if(!e.agent||!w(e.agent).includes(a.IOS_BUILD_DELETE_JOB_KIND))throw Error("Build agent must be updated to delete builds");await this.agentControl.createJob({agentId:e.agentId,codebaseId:A,worktreeId:e.worktreeId,kind:a.IOS_BUILD_DELETE_JOB_KIND,payload:{buildId:e.id,artifactDirectory:e.artifactDirectory,codebaseId:A},idempotencyKey:`ios:build:delete:${e.id}`,timeoutSeconds:300,visibility:"SYSTEM"})}}let i=await t.build.deleteMany({where:{id:{in:r.map(e=>e.id)}}});for(let e of r)this.publish(e.id);return i.count}async artifactForInstall(e,A){let t=await (0,s.getPrismaClient)(),r=await t.buildArtifact.findFirst({where:{id:A,buildId:e}});return r?{id:r.id,kind:r.kind,relativePath:r.relativePath,sizeBytes:r.sizeBytes,checksum:r.checksum,createdAt:r.createdAt.toISOString(),metadata:C(p(r.metadataJson,{}),"build artifact metadata")}:null}async prepareArtifactDownload(e,A,t,r=17e4){let i=await (0,s.getPrismaClient)(),n=await i.buildArtifact.findFirst({where:{id:A,buildId:e},include:{build:{include:{agent:!0}}}});if(!n)throw Error("Build artifact not found");let{build:o}=n;if(!o.agentId||!o.agent)throw Error("The build agent is no longer available");if(!I(o.agent))throw Error("Build agent is offline");if(!w(o.agent).includes(a.IOS_ARTIFACT_DOWNLOAD_JOB_KIND))throw Error("Build agent must be updated to download artifacts");let l=B(o),d=await this.agentControl.createJob({agentId:o.agentId,codebaseId:l,worktreeId:o.worktreeId,kind:a.IOS_ARTIFACT_DOWNLOAD_JOB_KIND,payload:{buildId:o.id,artifactDirectory:o.artifactDirectory,artifactRelativePath:n.relativePath,uploadId:t,codebaseId:l},idempotencyKey:`ios:artifact:download:${t}`,timeoutSeconds:Math.ceil(r/1e3)+10,visibility:"SYSTEM"});try{this.result(await this.waitForJob(d.id,r))}finally{await i.agentJob.deleteMany({where:{id:d.id,visibility:"SYSTEM"}})}}async logChunks(e,A=null,t=1e3,r=[],i={}){if(r.some(e=>!Number.isInteger(e.fromSequence)||e.fromSequence<0||!Number.isInteger(e.throughSequence)||e.throughSequence<e.fromSequence))throw Error("Build log ranges must contain ordered non-negative sequence numbers");let n=await (0,s.getPrismaClient)(),a=A?await n.buildLogChunk.findFirst({where:{id:A,buildId:e},select:{id:!0,createdAt:!0,sequence:!0}}):null;if(A&&!a)throw Error("Build log cursor not found");let o=async A=>{if(!A)return null;let t=await n.buildLogChunk.findFirst({where:{id:A,buildId:e},select:{id:!0,createdAt:!0,sequence:!0}});if(!t)throw Error("Build log cursor not found");return t},[l,d]=await Promise.all([o(i.before),o(i.from)]),u=!!(i.latest||l),c=await n.buildLogChunk.findMany({where:{buildId:e,...l||d?{AND:[...l?[{OR:[{createdAt:{lt:l.createdAt}},{createdAt:l.createdAt,sequence:{lt:l.sequence}},{createdAt:l.createdAt,sequence:l.sequence,id:{lt:l.id}}]}]:[],...d?[{OR:[{createdAt:{gt:d.createdAt}},{createdAt:d.createdAt,sequence:{gt:d.sequence}},{createdAt:d.createdAt,sequence:d.sequence,id:{gte:d.id}}]}]:[]]}:{},...r.length?{NOT:r.map(e=>({scope:e.scope,scopeId:e.scopeId,sequence:{gte:e.fromSequence,lte:e.throughSequence}}))}:{},...a?{OR:[{createdAt:{gt:a.createdAt}},{createdAt:a.createdAt,sequence:{gt:a.sequence}},{createdAt:a.createdAt,sequence:a.sequence,id:{gt:a.id}}]}:{}},orderBy:[{createdAt:u?"desc":"asc"},{sequence:u?"desc":"asc"},{id:u?"desc":"asc"}],take:Math.max(1,Math.min(t,5e3))});return u?c.reverse():c}async cancelBuild(e){let A=await (0,s.getPrismaClient)(),t=await A.build.findUnique({where:{id:e}});if(!t)throw Error("Build not found");return S.includes(t.status)&&(t.jobId&&await this.agentControl.cancelJob(t.jobId),await A.build.update({where:{id:e},data:{status:"CANCELLED",finishedAt:new Date,errorCode:"CANCELLED"}}),this.publish(e)),this.getBuild(e)}async reportProgress(e,A){if(!["PREPARING","RUNNING"].includes(A.status))throw Error("Build progress status is invalid");let t=await (0,s.getPrismaClient)(),r=await t.build.findUnique({where:{id:A.buildId}});if(!r||r.agentId!==e)throw Error("Build not found for agent");if(!S.includes(r.status))return r;let i=await t.build.update({where:{id:A.buildId},data:{status:A.status,startedAt:r.startedAt??(A.startedAt?new Date(A.startedAt):new Date),errorCode:A.errorCode??void 0,error:A.error??void 0}});return this.publish(A.buildId),i}async appendLogChunks(e,A,t){if(!t.length||t.length>200)throw Error("Build log batches must contain 1 to 200 chunks");let r=await (0,s.getPrismaClient)(),n=await r.build.findUnique({where:{id:A}});if(!n||n.agentId!==e)throw Error("Build not found for agent");let a=t.map(e=>{if(!Number.isInteger(e.sequence)||e.sequence<0)throw Error("Log sequence must be a non-negative integer");if(!["STDOUT","STDERR","SYSTEM"].includes(e.stream))throw Error("Log stream is invalid");let t=Buffer.from(e.dataBase64,"base64");if(t.length!==e.byteLength||t.length>262144)throw Error("Log byte length is invalid");let r=Buffer.from(t.toString("utf8").replace(/(Bearer\s+)[A-Za-z0-9._~+\/-]+=*/gi,"$1[REDACTED]").replace(/([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^\s/@]+@/g,"$1[REDACTED]@").replace(/\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY)[A-Z0-9_]*)\s*=\s*[^\s]+/gi,"$1=[REDACTED]").replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g,"[REDACTED PRIVATE KEY]"),"utf8"),n=new Date(e.createdAt);if(Number.isNaN(n.valueOf()))throw Error("Log date is invalid");return{id:(0,i.randomUUID)(),buildId:A,scope:m(e.scope,"Log scope",40),scopeId:m(e.scopeId,"Log scope ID",200),sequence:e.sequence,phase:m(e.phase,"Log phase",80),stream:e.stream,dataBase64:r.toString("base64"),byteLength:r.byteLength,createdAt:n}}),o=[];for(let e of a){let t=await r.buildLogChunk.upsert({where:{scope_scopeId_sequence:{scope:e.scope,scopeId:e.scopeId,sequence:e.sequence}},create:e,update:{}});o.push(t),d.agentEventBus.publish((0,d.buildLogChunkTopic)(A),{buildLogChunkAdded:t})}return o}async runBuild(e){let A=await (0,s.getPrismaClient)(),t=await A.build.findUnique({where:{id:e.buildId},include:{artifacts:!0,worktree:{include:{codebase:{include:{agent:!0,repository:!0}}}}}});if(!t||"SUCCEEDED"!==t.status)throw Error("A successful build is required");let r=t.artifacts.find(e=>"RUNNABLE_APP"===e.kind);if(!r)throw Error("Build does not contain a runnable app");let n=C(p(r.metadataJson,{}),"runnable metadata"),o=m(String(n.bundleIdentifier??""),"Runnable bundle identifier",512),l=e.destinations.map(a.parseBuildDestination);if(!l.length)throw Error("Select at least one destination");if(new Set(l.map(e=>`${e.type}:${e.id}`)).size!==l.length)throw Error("Run destinations must be unique");if(l.some(e=>e.type!==t.destinationType))throw Error("Run destinations must match the build destination type");let d=t.agentId??t.worktree?.codebase.agentId,u=e.targetAgentId??d;if(!u)throw Error("Build agent is unavailable");let g=u===d;if(!g){let e=(await this.runAgentsForBuild(t.id)).find(e=>e.agent.id===u);if(!e?.available)throw Error("The selected run agent is unavailable")}let f=await this.destinationsForBuild(t.id,`${m(e.requestId,"Request ID",200)}:preflight`,u),I=l.map(e=>f.find(A=>A.type===e.type&&A.id===e.id));if(I.some(e=>!e)||(l=I).some(e=>!1===e.available))throw Error("A selected run destination is no longer available");if(g&&!t.worktree)throw Error("The build worktree is unavailable");let w=g?await this.requireWorktree(t.worktree.id,a.IOS_DEPLOY_JOB_KIND):null,E=(0,i.randomUUID)(),y=[];for(let r of l){let n=`${r.type}:${r.id}`,a=await A.buildDeployment.findUnique({where:{buildId_requestId_targetAgentId_destinationKey:{buildId:t.id,requestId:e.requestId,targetAgentId:u,destinationKey:n}}});y.push(a??await A.buildDeployment.create({data:{id:(0,i.randomUUID)(),buildId:t.id,batchId:E,requestId:e.requestId,destinationJson:JSON.stringify(r),destinationKey:n,targetAgentId:u,status:g?"QUEUED":"TRANSFERRING",commandSummary:"SIMULATOR"===r.type?`open -a Simulator --args -CurrentDeviceUDID ${r.id}; xcrun simctl install/launch ${r.id}`:`xcrun devicectl device install/process launch --device ${r.id}`}}))}let B=y.map((e,A)=>({id:e.id,destination:l[A]}));if(g&&w){let i=await this.agentControl.createJob({agentId:w.codebase.agentId,codebaseId:w.codebaseId,worktreeId:w.id,kind:a.IOS_DEPLOY_JOB_KIND,payload:{...this.identity(w),buildId:t.id,artifactDirectory:t.artifactDirectory,artifactRelativePath:r.relativePath,bundleIdentifier:o,deployments:B},idempotencyKey:`ios:deploy:${t.id}:${e.requestId}`,timeoutSeconds:3600});await A.buildDeployment.updateMany({where:{id:{in:y.map(e=>e.id)}},data:{jobId:i.id}})}else if(!y.find(e=>e.transferId)?.transferId){let n=(0,i.randomUUID)(),s=await (0,c.cachedArtifact)(t.id,r.id),l=s?await (0,h.buildArtifactFileChecksum)(s.path):null;await A.buildArtifactTransfer.create({data:{id:n,artifactId:r.id,sourceAgentId:t.agentId,targetAgentId:u,status:s?"READY":"QUEUED",uploadOffset:s?.size??0,uploadLength:s?.size??null,checksum:l,filename:s?.filename??null,contentType:s?.contentType??null,stagingPath:s?.path??null,expiresAt:new Date(Date.now()+216e5)}});try{let i=null;s||(i=(await this.agentControl.createJob({agentId:t.agentId,kind:a.IOS_ARTIFACT_TRANSFER_UPLOAD_JOB_KIND,payload:{transferId:n,buildId:t.id,artifactDirectory:t.artifactDirectory,artifactRelativePath:r.relativePath},idempotencyKey:`ios:artifact-transfer:${n}`,timeoutSeconds:3600,visibility:"SYSTEM"})).id,await A.buildArtifactTransfer.update({where:{id:n},data:{sourceJobId:i}}));let l=await this.agentControl.createJob({agentId:u,kind:a.IOS_REMOTE_DEPLOY_JOB_KIND,payload:{transferId:n,buildId:t.id,bundleIdentifier:o,deployments:B},idempotencyKey:`ios:remote-deploy:${t.id}:${e.requestId}:${u}`,timeoutSeconds:7200});await A.$transaction([A.buildArtifactTransfer.update({where:{id:n},data:{sourceJobId:i,targetJobId:l.id}}),A.buildDeployment.updateMany({where:{id:{in:y.map(e=>e.id)}},data:{jobId:l.id,transferId:n,targetAgentId:u}})])}catch(i){let e=i instanceof Error?i.message:String(i),r=new Date;throw await A.$transaction([A.buildArtifactTransfer.update({where:{id:n},data:{status:"FAILED",error:e,finishedAt:r}}),A.buildDeployment.updateMany({where:{id:{in:y.map(e=>e.id)}},data:{status:"FAILED",error:e,finishedAt:r}})]).catch(()=>{}),this.publish(t.id),i}}return this.publish(t.id),A.buildDeployment.findMany({where:{id:{in:y.map(e=>e.id)}},orderBy:{createdAt:"asc"}})}async exportArchive(e){let A=await (0,s.getPrismaClient)(),t=await A.buildExport.findUnique({where:{buildId_requestId:{buildId:e.buildId,requestId:e.requestId}}});if(t)return t;let r=await A.build.findUnique({where:{id:e.buildId},include:{artifacts:!0,worktree:!0}});if(!r||"SUCCEEDED"!==r.status||!r.worktree)throw Error("A successful archive build is required");let n=r.artifacts.find(e=>"ARCHIVE"===e.kind);if(!n)throw Error("Build does not contain an archive");let o=(0,a.parseBuildExportSettings)(e.settings),l=await this.requireWorktree(r.worktree.id,a.IOS_EXPORT_JOB_KIND),d=(0,i.randomUUID)(),u=await A.buildExport.create({data:{id:d,buildId:r.id,requestId:e.requestId,settingsSnapshotJson:JSON.stringify(o),commandSummary:`xcrun xcodebuild -exportArchive -archivePath ${JSON.stringify(n.relativePath)} -exportPath exports/${d}`}});try{let t=await this.agentControl.createJob({agentId:l.codebase.agentId,codebaseId:l.codebaseId,worktreeId:l.id,kind:a.IOS_EXPORT_JOB_KIND,payload:{...this.identity(l),buildId:r.id,exportId:d,artifactDirectory:r.artifactDirectory,archiveRelativePath:n.relativePath,settings:o},idempotencyKey:`ios:export:${r.id}:${e.requestId}`,timeoutSeconds:3600}),i=await A.buildExport.update({where:{id:u.id},data:{jobId:t.id}});return this.publish(r.id),i}catch(t){let e=await A.buildExport.update({where:{id:u.id},data:{status:"FAILED",error:t instanceof Error?t.message:String(t),finishedAt:new Date}});return this.publish(r.id),e}}async upsertArtifacts(e,A,t){for(let r of(0,a.parseBuildArtifactSnapshots)(t)){let t={kind:r.kind,sizeBytes:r.sizeBytes,checksum:r.checksum,metadataJson:JSON.stringify(r.metadata)};await e.buildArtifact.upsert({where:{buildId_relativePath:{buildId:A,relativePath:r.relativePath}},create:{id:(0,i.randomUUID)(),buildId:A,relativePath:r.relativePath,...t},update:t})}}async upsertReportProjection(e,A,t,r){let n=C(t,"build report");if("TEST_RESULTS"!==n.kind&&"CODE_COVERAGE"!==n.kind)return;let a=n.kind,o=n.artifact&&"object"==typeof n.artifact?C(n.artifact,"build report artifact"):null,s=o&&"string"==typeof o.relativePath?await e.buildArtifact.findUnique({where:{buildId_relativePath:{buildId:A,relativePath:o.relativePath}}}):null,l="READY"===n.status?"READY":"FAILED";await e.buildReport.upsert({where:{buildId_kind:{buildId:A,kind:a}},create:{id:(0,i.randomUUID)(),buildId:A,artifactId:s?.id??null,kind:a,source:r,status:l,summaryJson:JSON.stringify(n.summary&&"object"==typeof n.summary?n.summary:{}),dataJson:JSON.stringify(n.data&&"object"==typeof n.data?n.data:{}),error:"string"==typeof n.error?n.error:null,finishedAt:new Date},update:{artifactId:s?.id??null,source:r,status:l,summaryJson:JSON.stringify(n.summary&&"object"==typeof n.summary?n.summary:{}),dataJson:JSON.stringify(n.data&&"object"==typeof n.data?n.data:{}),error:"string"==typeof n.error?n.error:null,finishedAt:new Date}})}async projectBuildCompletion(e){let A=await (0,s.getPrismaClient)(),t=await A.build.findFirst({where:{jobId:e.id},include:{worktree:{select:{highlightColor:!0}}}});if(!t)return;let r=C(p(e.resultJson,{}),"build result"),n="CANCELLED"===t.status?"CANCELLED":Q(e.status),a="string"==typeof r.sourceStateHash?r.sourceStateHash:null,o="string"==typeof r.finalStateHash?r.finalStateHash:null,l="string"==typeof r.codeStateObservedAt&&Number.isFinite(Date.parse(r.codeStateObservedAt))?new Date(r.codeStateObservedAt):new Date,d=o?l:new Date,u=t.snapshotJson;if(a){let e=C(p(t.snapshotJson,{}),"build snapshot"),A=C(e.worktree??{},"build worktree snapshot");u=JSON.stringify({...e,worktree:{...A,codeStateHash:a}})}let c=null;await A.$transaction(async A=>{if(await A.build.update({where:{id:t.id},data:{status:n,errorCode:"string"==typeof r.errorCode?r.errorCode:"TIMED_OUT"===e.status?"TIMEOUT":"FAILED"===n?"XCODEBUILD_FAILED":t.errorCode,error:e.error??("string"==typeof r.error?r.error:t.error),startedAt:t.startedAt??new Date,finishedAt:d,snapshotJson:u}}),t.worktreeId&&o&&await A.worktree.updateMany({where:{id:t.worktreeId,OR:[{lastCheckedAt:null},{lastCheckedAt:{lt:l}}]},data:{codeStateHash:o,lastCheckedAt:l}}),Array.isArray(r.artifacts))for(let e of r.artifacts){let r=C(e,"build artifact");"string"==typeof r.relativePath&&"string"==typeof r.kind&&await A.buildArtifact.upsert({where:{buildId_relativePath:{buildId:t.id,relativePath:r.relativePath}},create:{id:(0,i.randomUUID)(),buildId:t.id,kind:r.kind,relativePath:r.relativePath,sizeBytes:"number"==typeof r.sizeBytes?r.sizeBytes:null,checksum:"string"==typeof r.checksum?r.checksum:null,metadataJson:JSON.stringify(r.metadata&&"object"==typeof r.metadata?r.metadata:{})},update:{}})}if(Array.isArray(r.scriptExecutions))for(let e of r.scriptExecutions){let r=C(e,"script execution");"string"==typeof r.phase&&"number"==typeof r.position&&await A.buildScriptExecution.updateMany({where:{buildId:t.id,phase:r.phase,position:r.position},data:{status:"string"==typeof r.status?r.status:"FAILED",exitCode:"number"==typeof r.exitCode?r.exitCode:null,durationMs:"number"==typeof r.durationMs?r.durationMs:null,causedBuildFailure:!0===r.causedBuildFailure,outputRelativePath:"string"==typeof r.outputRelativePath?r.outputRelativePath:null,error:"string"==typeof r.error?r.error:null}})}if(Array.isArray(r.reports))for(let e of r.reports){let r=e&&"object"==typeof e&&!Array.isArray(e)?e:{};await this.upsertReportProjection(A,t.id,e,"CODE_COVERAGE"===r.kind?"WORKTREE":"AUTOMATIC")}if(this.notifications&&("SUCCEEDED"===n||"FAILED"===n)){let e=C(p(u,{}),"build notification snapshot"),r=C(e.repository??{},"build repository snapshot"),i=C(e.configuration??{},"build configuration snapshot"),a=C(e.worktree??{},"build worktree snapshot"),o=["string"==typeof r.name?r.name:null,"string"==typeof i.name?i.name:null,"string"==typeof a.branch?a.branch:"string"==typeof a.folder?a.folder:null].filter(e=>!!e);c=await this.notifications.recordInTransaction(A,{dedupeKey:`ios-build:${t.id}:${n}`,typeKey:"SUCCEEDED"===n?"IOS_BUILD_SUCCEEDED":"IOS_BUILD_FAILED",title:"SUCCEEDED"===n?"iOS build succeeded":"iOS build failed",body:o.join(" · ")||`Build ${t.id}`,href:`/builds/${t.id}`,resourceKind:"BUILD",resourceId:t.id,worktreeId:t.worktreeId,highlightColor:t.worktree?.highlightColor??null})}}),this.publish(t.id),this.notifications?.created(c),"SUCCEEDED"===n&&await this.queueAutomaticExport(t.id,u)}async queueAutomaticExport(e,A){let t=C(p(A,{}),"build snapshot"),r=C(t.configuration??{},"build configuration snapshot");if(!0!==r.autoExport)return;let n=r.exportSettings;try{await this.exportArchive({buildId:e,requestId:"automatic",settings:n})}catch(r){let A=await (0,s.getPrismaClient)(),t=r instanceof Error?r.message:String(r);await A.buildExport.upsert({where:{buildId_requestId:{buildId:e,requestId:"automatic"}},create:{id:(0,i.randomUUID)(),buildId:e,requestId:"automatic",status:"FAILED",settingsSnapshotJson:JSON.stringify(n??{}),commandSummary:"Automatic archive export",error:t,finishedAt:new Date},update:{status:"FAILED",error:t,finishedAt:new Date}}),this.publish(e)}}async projectGeneratedReportCompletion(e){let A=C(p(e.payloadJson,{}),"build report payload");if("string"!=typeof A.buildId)return;let t=A.buildId,r=C(p(e.resultJson,{}),"build report result"),n=await (0,s.getPrismaClient)();await n.$transaction(async n=>{if(await this.upsertArtifacts(n,t,r.artifacts),r.report&&"object"==typeof r.report)await this.upsertReportProjection(n,t,r.report,"WORKTREE"===A.source?"WORKTREE":"MANUAL");else{let r="CODE_COVERAGE"===A.reportKind?"CODE_COVERAGE":"TEST_RESULTS";await n.buildReport.upsert({where:{buildId_kind:{buildId:t,kind:r}},create:{id:(0,i.randomUUID)(),buildId:t,kind:r,source:"WORKTREE"===A.source?"WORKTREE":"MANUAL",status:"FAILED",error:e.error||"Report generation failed",finishedAt:new Date},update:{status:"FAILED",error:e.error||"Report generation failed",finishedAt:new Date}})}}),this.publish(t)}async projectDeploymentCompletion(e){let A=await (0,s.getPrismaClient)(),t=await A.buildDeployment.findMany({where:{jobId:e.id}});if(!t.length)return;let r=C(p(e.resultJson,{}),"deployment result"),i=Array.isArray(r.deployments)?r.deployments:[];for(let r of t){let t=i.map(e=>C(e,"deployment outcome")).find(e=>e.id===r.id);await A.buildDeployment.update({where:{id:r.id},data:{status:"string"==typeof t?.status?t.status:Q(e.status),error:"string"==typeof t?.error?t.error:e.error,outputRelativePath:"string"==typeof t?.outputRelativePath?t.outputRelativePath:null,startedAt:r.startedAt??new Date,finishedAt:new Date}})}for(let r of[...new Set(t.map(e=>e.transferId).filter(e=>!!e))]){let n=t.some(e=>{let A=i.map(e=>C(e,"deployment outcome")).find(A=>A.id===e.id);return A?.status!=="SUCCEEDED"});await A.buildArtifactTransfer.update({where:{id:r},data:{status:n||"SUCCEEDED"!==e.status?"FAILED":"SUCCEEDED",error:n||"SUCCEEDED"!==e.status?e.error||"One or more remote deployments failed":null,finishedAt:new Date}})}this.publish(t[0].buildId)}async projectExportCompletion(e){let A=await (0,s.getPrismaClient)(),t=await A.buildExport.findFirst({where:{jobId:e.id}});if(!t)return;let r=C(p(e.resultJson,{}),"export result");if(await A.buildExport.update({where:{id:t.id},data:{status:Q(e.status),error:e.error??("string"==typeof r.error?r.error:null),outputRelativePath:"string"==typeof r.outputRelativePath?r.outputRelativePath:null,startedAt:t.startedAt??new Date,finishedAt:new Date}}),"SUCCEEDED"===e.status&&"string"==typeof r.outputRelativePath){let e=r.outputRelativePath;await A.$transaction(async A=>{await A.buildArtifact.upsert({where:{buildId_relativePath:{buildId:t.buildId,relativePath:e}},create:{id:(0,i.randomUUID)(),buildId:t.buildId,kind:"EXPORT",relativePath:e,sizeBytes:"number"==typeof r.sizeBytes?r.sizeBytes:null,metadataJson:JSON.stringify({exportId:t.id})},update:{}}),await this.upsertArtifacts(A,t.buildId,r.artifacts)})}this.publish(t.buildId)}}t()}catch(e){t(e)}},!1),988438,e=>{"use strict";var A=e.i(750227);e.s(["effectiveBuildsDirectory",0,function(e){var t;return e.buildsDirectory??((t=e.baseRepoDirectory)?/^[a-z]:[\\/]/i.test(t)||t.startsWith("\\\\")?A.win32.join(t,"Builds"):A.posix.join(t,"Builds"):null)}])},89003,e=>{"use strict";var A=e.i(749906);let t=A.object({status:A.string().optional(),codebaseId:A.string().optional(),worktreeId:A.string().optional(),first:A.number().int().min(1).max(200).default(50),after:A.string().optional()}),r=A.object({builds:A.array(A.unknown()),nextCursor:A.string().nullable()}),i=A.object({buildId:A.string().min(1),afterLogId:A.string().min(1).nullable().default(null),logLimit:A.number().int().min(1).max(5e3).default(1e3)}),n=A.object({build:A.unknown(),logs:A.array(A.unknown())}),a=A.object({worktreeId:A.string().min(1)}),o=A.object({project:A.unknown().nullable()}),s=A.union([A.object({buildId:A.string().min(1),requestId:A.string().min(1)}),A.object({worktreeId:A.string().min(1),configurationId:A.string().min(1),action:A.string().optional(),requestId:A.string().min(1)})]),l=A.object({destinations:A.array(A.unknown())}),d=A.object({worktreeId:A.string().min(1),configurationId:A.string().min(1),destination:A.record(A.string(),A.unknown()),scriptIds:A.array(A.string()).default([]),action:A.string().optional(),advancedSettings:A.record(A.string(),A.unknown()).optional(),requestId:A.string().min(1)}),u=A.object({build:A.unknown()}),c=A.object({worktreeId:A.string().min(1),reportPath:A.string().min(1).max(4e3),format:A.enum(["AUTO","LCOV","ISTANBUL"]).default("AUTO"),requestId:A.string().min(1)}),h=A.object({build:A.unknown()}),g=A.object({buildId:A.string().min(1),requestId:A.string().min(1)}),p=A.object({build:A.unknown()}),C=A.object({buildId:A.string().min(1),destinations:A.array(A.record(A.string(),A.unknown())).min(1),requestId:A.string().min(1)}),f=A.object({deployments:A.array(A.unknown())}),I=A.object({buildId:A.string().min(1),settings:A.record(A.string(),A.unknown()),requestId:A.string().min(1)}),w=A.object({export:A.unknown()});e.s(["CancelBuildToolInputSchema",0,g,"CancelBuildToolOutputSchema",0,p,"ExportBuildToolInputSchema",0,I,"ExportBuildToolOutputSchema",0,w,"GetBuildConfigurationsInputSchema",0,a,"GetBuildConfigurationsOutputSchema",0,o,"GetBuildDestinationsInputSchema",0,s,"GetBuildDestinationsOutputSchema",0,l,"GetBuildInputSchema",0,i,"GetBuildOutputSchema",0,n,"GetBuildsInputSchema",0,t,"GetBuildsOutputSchema",0,r,"ImportCoverageReportToolInputSchema",0,c,"ImportCoverageReportToolOutputSchema",0,h,"RunBuildToolInputSchema",0,C,"RunBuildToolOutputSchema",0,f,"StartBuildToolInputSchema",0,d,"StartBuildToolOutputSchema",0,u])},108829,e=>e.a(async(A,t)=>{try{e.s([]);var r=e.i(868756);e.i(89003);var i=A([r]);[r]=i.then?(await i)():i,t()}catch(e){t(e)}},!1),933653,e=>{"use strict";var A=e.i(794231),t=e.i(666680),r=e.i(591135),i=e.i(380592),n=e.i(135475),a=e.i(751976),o=e.i(454228);e.i(256554);var s=e.i(118387),l=e.i(848201),d=e.i(999585);let u="default";function c(e){if("SUCCEEDED"!==e.status||!e.resultJson)throw Error(e.error||`${e.kind} failed`);let A=JSON.parse(e.resultJson);if(!A||"object"!=typeof A||Array.isArray(A))throw Error(`${e.kind} returned an invalid result`);return A}function h(e){try{let A=JSON.parse(e.capabilitiesJson);return Array.isArray(A)?A.filter(e=>"string"==typeof e):[]}catch{return[]}}function g(e){return null!==e.lastSeenAt&&Date.now()-e.lastSeenAt.getTime()<=(0,s.agentOnlineWindowMs)(e)&&null===e.disconnectedAt}e.s(["CodebasesService",0,class{agentControl;skillsService;stateInspections;cleanupInFlight;lastCleanupAt;constructor(e,A){for(const t of(this.agentControl=e,this.skillsService=A,this.stateInspections=new Map,this.cleanupInFlight=null,this.lastCleanupAt=0,[r.CODEBASE_REFRESH_JOB_KIND,r.CODEBASE_FETCH_JOB_KIND]))this.agentControl.registerCompletionHandler(t,e=>this.projectJob(e));this.agentControl.registerCompletionHandler(r.CODEBASE_GIT_OPERATION_JOB_KIND,e=>this.projectGitOperation(e))}async overview(e){return await this.cleanupInternalJobs(),(await (0,n.getPrismaClient)()).codebaseRepository.findMany({...e?{where:{codebases:{some:{agentId:e}}}}:{},orderBy:[{name:"asc"},{canonicalOrigin:"asc"}],include:{skillGroups:{include:{group:!0}},quickActionWorkflows:{include:{workflow:!0}},codebases:{...e?{where:{agentId:e}}:{},orderBy:{folder:"asc"},include:{agent:!0,repository:!0,jobs:{where:o.ACTIVE_CODEBASE_BLOCKING_JOB_WHERE,orderBy:{createdAt:"desc"},take:1}}}}})}async repositoryDetail(e){return await this.cleanupInternalJobs(),(await (0,n.getPrismaClient)()).codebaseRepository.findUnique({where:{id:e},include:{skillGroups:{include:{group:!0}},quickActionWorkflows:{include:{workflow:!0}},codebases:{orderBy:[{agent:{name:"asc"}},{folder:"asc"}],include:{agent:!0,repository:!0,jobs:{where:o.ACTIVE_CODEBASE_BLOCKING_JOB_WHERE,orderBy:{createdAt:"desc"},take:1}}}}})}async repositoryPreparations(e){let A=await (0,n.getPrismaClient)();if(!await A.codebaseRepository.findUnique({where:{id:e},select:{id:!0}}))throw Error("Repository not found");return A.codebaseRepositoryPreparation.findMany({where:{repositoryId:e},orderBy:[{kind:"asc"},{path:"asc"}]})}async detail(e){return await this.cleanupInternalJobs(),(await (0,n.getPrismaClient)()).codebase.findUnique({where:{id:e},include:{agent:!0,repository:{include:{skillGroups:{include:{group:!0}}}},jobs:{where:o.ACTIVE_CODEBASE_BLOCKING_JOB_WHERE,orderBy:{createdAt:"desc"},take:1}}})}async agentCodebases(e){return(await (0,n.getPrismaClient)()).codebase.findMany({where:{agentId:e},orderBy:{folder:"asc"},select:{id:!0,folder:!0,defaultBranch:!0,lastFetchedAt:!0,lastFetchAttemptAt:!0,repository:{select:{canonicalOrigin:!0,keepBaseBranchUpToDate:!0}},worktrees:{where:{missingAt:null},select:{id:!0,folder:!0,branch:!0,gitDirectory:!0,baseBranchOverride:!0}}}})}async settings(){let e=await (0,n.getPrismaClient)(),A=await e.codebaseSettings.findUnique({where:{id:u}});return A||e.codebaseSettings.upsert({where:{id:u},create:{id:u,refreshIntervalSeconds:r.DEFAULT_CODEBASE_RECONCILE_INTERVAL_SECONDS,fetchIntervalSeconds:i.DEFAULT_WORKTREE_FETCH_INTERVAL_SECONDS,defaultJiraBranchRegex:i.DEFAULT_JIRA_BRANCH_REGEX},update:{}})}async agentConfiguration(e){let A=await (0,n.getPrismaClient)(),[t,r,i]=await Promise.all([this.settings(),A.agent.findUnique({where:{id:e},select:{codebaseScanIntervalSeconds:!0,gitFetchIntervalSeconds:!0}}),this.agentCodebases(e)]);return{refreshIntervalSeconds:r?.codebaseScanIntervalSeconds??t.refreshIntervalSeconds,fetchIntervalSeconds:r?.gitFetchIntervalSeconds??t.fetchIntervalSeconds,codebases:i}}async updateSettings(e){let A="number"==typeof e?e:e.refreshIntervalSeconds,t="number"==typeof e?i.DEFAULT_WORKTREE_FETCH_INTERVAL_SECONDS:e.fetchIntervalSeconds;if(!Number.isInteger(A)||A<r.MIN_CODEBASE_RECONCILE_INTERVAL_SECONDS||A>r.MAX_CODEBASE_RECONCILE_INTERVAL_SECONDS)throw Error(`Refresh interval must be an integer from ${r.MIN_CODEBASE_RECONCILE_INTERVAL_SECONDS} to ${r.MAX_CODEBASE_RECONCILE_INTERVAL_SECONDS} seconds`);if(!Number.isInteger(t)||t<i.MIN_WORKTREE_FETCH_INTERVAL_SECONDS||t>i.MAX_WORKTREE_FETCH_INTERVAL_SECONDS)throw Error(`Fetch interval must be an integer from ${i.MIN_WORKTREE_FETCH_INTERVAL_SECONDS} to ${i.MAX_WORKTREE_FETCH_INTERVAL_SECONDS} seconds`);let o="number"==typeof e?i.DEFAULT_JIRA_BRANCH_REGEX:e.defaultJiraBranchRegex.trim();o&&(0,a.compileRe2)(o,{flags:"i",label:"Default Jira branch regex"});let s=await (0,n.getPrismaClient)(),l="number"==typeof e?{refreshIntervalSeconds:A}:{refreshIntervalSeconds:A,fetchIntervalSeconds:t,defaultJiraBranchRegex:o},d=await s.codebaseSettings.upsert({where:{id:u},create:{id:u,...l},update:l});return this.publish(null,null),d}async browse(e,A,t){await this.cleanupInternalJobs(),await this.requireAgentCapability(e,r.CODEBASE_BROWSE_JOB_KIND);let i=await this.agentControl.createJob({agentId:e,kind:r.CODEBASE_BROWSE_JOB_KIND,payload:{path:A},idempotencyKey:`codebase:browse:${t}`,timeoutSeconds:30,visibility:"SYSTEM"}),a=await this.waitForJob(i.id),o=(0,r.parseCodebaseDirectoryListing)(c(a).listing),s=await (0,n.getPrismaClient)();return await s.agentJob.deleteMany({where:{id:i.id}}),o}async inspect(e,A,t){await this.cleanupInternalJobs(),await this.requireAgentCapability(e,r.CODEBASE_INSPECT_JOB_KIND);let i=await this.agentControl.createJob({agentId:e,kind:r.CODEBASE_INSPECT_JOB_KIND,payload:{folder:A},idempotencyKey:`codebase:inspect:${t}`,timeoutSeconds:30,visibility:"SYSTEM"}),a=await this.waitForJob(i.id),o=(0,r.parseCodebaseSnapshot)(c(a).snapshot);if("AVAILABLE"!==o.availability)throw Error(o.error||"The selected folder is unavailable");if(o.linkedWorktree)throw Error("Linked Git worktrees are not supported yet");if(!o.canonicalOrigin)throw Error("Git origin is required");let s=await (0,n.getPrismaClient)(),l=await s.codebaseRepository.findUnique({where:{canonicalOrigin:o.canonicalOrigin}});return{jobId:i.id,snapshot:o,repository:l}}async confirm(e){let A=await (0,n.getPrismaClient)(),i=await A.agentJob.findUnique({where:{id:e.inspectionJobId}});if(!i||i.kind!==r.CODEBASE_INSPECT_JOB_KIND)throw Error("Codebase inspection was not found");if(!i.finishedAt||Date.now()-i.finishedAt.getTime()>9e5)throw Error("Codebase inspection expired; inspect the folder again");let a=(0,r.parseCodebaseSnapshot)(c(i).snapshot);if("AVAILABLE"!==a.availability||a.linkedWorktree||!a.canonicalOrigin||!a.displayOrigin||!a.observedOrigin)throw Error("Codebase inspection is not eligible for confirmation");let o=e.name?.trim()??"",s=e.description?.trim()??"";if(o.length>120)throw Error("Name must be 120 characters or fewer");if(s.length>2e3)throw Error("Description must be 2,000 characters or fewer");let l=await A.$transaction(async e=>{let A=await e.codebaseRepository.findUnique({where:{canonicalOrigin:a.canonicalOrigin}});if(!A){if(!o)throw Error("Name is required for a new repository");A=await e.codebaseRepository.upsert({where:{canonicalOrigin:a.canonicalOrigin},create:{id:(0,t.randomUUID)(),canonicalOrigin:a.canonicalOrigin,displayOrigin:a.displayOrigin,name:o,description:s},update:{}})}let r=await e.codebase.findUnique({where:{agentId_folder:{agentId:i.agentId,folder:a.folder}},select:{lastFetchedAt:!0}}),n=a.fetchedAt?new Date(a.fetchedAt):null,l=n&&(!r?.lastFetchedAt||n>r.lastFetchedAt)?n:r?.lastFetchedAt??null;return e.codebase.upsert({where:{agentId_folder:{agentId:i.agentId,folder:a.folder}},create:{id:(0,t.randomUUID)(),agentId:i.agentId,repositoryId:A.id,...this.snapshotData(a,l)},update:{repositoryId:A.id,...this.snapshotData(a,l)},include:{agent:!0,repository:!0,jobs:!0}})});return this.publish(l.id,l.repositoryId),await A.agentJob.deleteMany({where:{id:e.inspectionJobId,visibility:"SYSTEM"}}),await this.agentControl.requestCodebaseReconcile([l.agentId]),await this.skillsService?.requestAutoReconcile(),l}async updateRepository(e,A,t,r,i=!0,o){let s=A.trim(),l=t.trim();if(!s)throw Error("Name is required");if(s.length>120)throw Error("Name must be 120 characters or fewer");if(l.length>2e3)throw Error("Description must be 2,000 characters or fewer");let d=r?.trim()||null;d&&(0,a.compileRe2)(d,{flags:"i",label:"Jira branch regex"});let u=null==o?null:await this.skillsService?.validateGroupIds(o),c=await (0,n.getPrismaClient)(),h=await c.codebaseRepository.update({where:{id:e},data:{name:s,description:l,jiraBranchRegex:d,keepBaseBranchUpToDate:i}});return u&&await this.skillsService?.setRepositoryGroups(e,u),this.publish(null,e),h}async saveRepositoryPreparations(e,A){if(A.length>d.MAX_REPOSITORY_PREPARATIONS)throw Error("A repository can have at most 500 preparations");let r=await (0,n.getPrismaClient)(),a=await r.codebaseRepository.findUnique({where:{id:e},include:{preparations:{include:{statuses:!0}}}});if(!a)throw Error("Repository not found");let o=new Map(a.preparations.map(e=>[e.id,e])),s=new Set,l=new Set,u=0,c=A.map((e,A)=>{if(!i.WORKTREE_PREPARATION_KINDS.includes(e.kind))throw Error(`Preparation ${A+1} has an invalid kind`);let t=(0,d.normalizePreparationPath)(e.path);if(l.has(t))throw Error(`Preparation path ${t} is duplicated`);l.add(t);let r=e.id?.trim()||null,n=r?o.get(r):null;if(r&&!n)throw Error(`Preparation ${r} does not belong to this repository`);if(r&&s.has(r))throw Error(`Preparation ${r} is duplicated`);r&&s.add(r);let a=null;if("WRITE"===e.kind){if(null===(a=null!==e.contentBase64&&void 0!==e.contentBase64?(0,d.decodePreparationContents)(e.contentBase64):n?.kind==="WRITE"&&n.contents?Buffer.from(n.contents):null))throw Error(`Uploaded contents are required for ${t}`);u+=a.byteLength}else if(null!==e.contentBase64&&void 0!==e.contentBase64)throw Error("Uploaded contents are only supported for write preparations");return{id:r,kind:e.kind,path:t,contents:a,definitionHash:(0,d.preparationDefinitionHash)({kind:e.kind,path:t,contents:a})}});if(u>d.MAX_PREPARATION_TOTAL_BYTES)throw Error("Repository preparation uploads must total 20 MiB or less");let h=a.preparations.filter(e=>{let A=c.find(A=>A.id===e.id);return(!A||A.kind!==e.kind||A.path!==e.path)&&(e.statuses?.some(e=>"UNDONE"!==e.state&&"NOT_APPLICABLE"!==e.state)??!1)});if(h.length>0)throw Error(`Undo preparation ${h[0].path} on all worktrees before removing or moving it`);return await r.$transaction(async A=>{let r=c.flatMap(e=>e.id?[e.id]:[]);for(let i of(await A.codebaseRepositoryPreparation.deleteMany({where:{repositoryId:e,...r.length?{id:{notIn:r}}:{}}}),c)){let e=i.id?o.get(i.id):null;e&&e.path!==i.path&&await A.codebaseRepositoryPreparation.update({where:{id:e.id},data:{path:`.aide-preparation-replacement/${(0,t.randomUUID)()}`}})}for(let r of c){let i=r.id??(0,t.randomUUID)(),n={kind:r.kind,path:r.path,contents:r.contents?Uint8Array.from(r.contents):null,contentSha256:r.contents?(0,d.preparationContentSha256)(r.contents):null,byteCount:r.contents?.byteLength??null,definitionHash:r.definitionHash};r.id?await A.codebaseRepositoryPreparation.update({where:{id:i},data:n}):await A.codebaseRepositoryPreparation.create({data:{id:i,repositoryId:e,...n}})}}),this.publish(null,e),this.repositoryDetail(e)}async removeCodebase(e){let A=await (0,n.getPrismaClient)(),t=await A.$transaction(async A=>{let t=await A.codebase.findUnique({where:{id:e},select:{id:!0,repositoryId:!0,agentId:!0}});if(!t)throw Error("Codebase not found");await A.codebase.delete({where:{id:e}});let r=await A.codebase.count({where:{repositoryId:t.repositoryId}}),i=await A.appRepository.count({where:{repositoryId:t.repositoryId}}),n=0===r&&0===i;return n&&await A.codebaseRepository.delete({where:{id:t.repositoryId}}),{id:t.id,agentId:t.agentId,repositoryId:t.repositoryId,repositoryRemoved:n}});return this.publish(t.id,t.repositoryId,t.agentId),t}async report(e,A){let t=[],i=!1;try{for(let n of A.slice(0,500)){let A=(0,r.parseCodebaseSnapshot)(n.snapshot),a=await this.applySnapshot(e,n.codebaseId,A);t.push(a.codebase),i||=a.changed}}finally{i&&this.publish(null,null)}return t}async runOperation(e,A,t){if(!t.trim())throw Error("requestId is required");let i=await (0,n.getPrismaClient)(),a=await i.codebase.findMany({where:{id:{in:[...new Set(A)].slice(0,500)}},include:{agent:!0,repository:!0,jobs:{where:o.ACTIVE_CODEBASE_BLOCKING_JOB_WHERE,select:{id:!0},take:1}}}),s=[],l=[];for(let A of a){if(A.jobs.length>0){l.push({codebaseId:A.id,reason:"ACTIVE_OPERATION"});continue}if(!g(A.agent)){l.push({codebaseId:A.id,reason:"OFFLINE"});continue}if(!h(A.agent).includes(e)){l.push({codebaseId:A.id,reason:"UNSUPPORTED"});continue}if(e===r.CODEBASE_FETCH_JOB_KIND&&"AVAILABLE"!==A.availability){l.push({codebaseId:A.id,reason:A.availability});continue}try{s.push(await this.agentControl.createJob({agentId:A.agentId,codebaseId:A.id,kind:e,payload:{codebaseId:A.id,folder:A.folder,expectedOrigin:A.repository.canonicalOrigin,...e===r.CODEBASE_FETCH_JOB_KIND&&A.defaultBranch?{baseBranch:A.defaultBranch}:{},...e===r.CODEBASE_FETCH_JOB_KIND?{keepBaseBranchUpToDate:A.repository.keepBaseBranchUpToDate}:{}},idempotencyKey:`codebase:${e}:${t}:${A.id}`,timeoutSeconds:e===r.CODEBASE_FETCH_JOB_KIND?300:30}))}catch(e){if(!await i.agentJob.findFirst({where:{codebaseId:A.id,...o.ACTIVE_CODEBASE_BLOCKING_JOB_WHERE},select:{id:!0}}))throw e;l.push({codebaseId:A.id,reason:"ACTIVE_OPERATION"})}}return{jobs:s,skipped:l}}inspectGitState(e,A){if(!A.trim())return Promise.reject(Error("requestId is required"));let t=this.stateInspections.get(e);if(t)return t;let r=this.inspectGitStateOnce(e,A).finally(()=>{this.stateInspections.get(e)===r&&this.stateInspections.delete(e)});return this.stateInspections.set(e,r),r}async inspectGitStateOnce(e,A){if(!A.trim())throw Error("requestId is required");let t=await this.requireRunnableCodebase(e,r.CODEBASE_GIT_INSPECT_JOB_KIND),i=await this.agentControl.createJob({agentId:t.agentId,codebaseId:t.id,kind:r.CODEBASE_GIT_INSPECT_JOB_KIND,payload:{action:"STATE",codebaseId:t.id,folder:t.folder,expectedOrigin:t.repository.canonicalOrigin},idempotencyKey:`codebase:git:state:${A}:${t.id}`,timeoutSeconds:30,visibility:"SYSTEM"}),a=await (0,n.getPrismaClient)();try{let e=await this.waitForJob(i.id);return(0,r.parseCodebaseGitState)(c(e).state)}finally{await a.agentJob.deleteMany({where:{id:i.id,visibility:"SYSTEM"}})}}async inspectStash(e,A,t){if(!t.trim())throw Error("requestId is required");let i=await this.requireRunnableCodebase(e,r.CODEBASE_GIT_INSPECT_JOB_KIND),a=await this.agentControl.createJob({agentId:i.agentId,codebaseId:i.id,kind:r.CODEBASE_GIT_INSPECT_JOB_KIND,payload:{action:"STASH_DIFF",codebaseId:i.id,folder:i.folder,expectedOrigin:i.repository.canonicalOrigin,stashOid:A},idempotencyKey:`codebase:git:stash:${t}:${i.id}`,timeoutSeconds:30,visibility:"SYSTEM"}),o=await (0,n.getPrismaClient)();try{let e=await this.waitForJob(a.id);return(0,r.parseCodebaseStashDiff)(c(e).diff)}finally{await o.agentJob.deleteMany({where:{id:a.id,visibility:"SYSTEM"}})}}async runGitOperation(e){if(!e.requestId.trim())throw Error("requestId is required");let A=await this.requireRunnableCodebase(e.codebaseId,r.CODEBASE_GIT_OPERATION_JOB_KIND);return this.agentControl.createJob({agentId:A.agentId,codebaseId:A.id,kind:r.CODEBASE_GIT_OPERATION_JOB_KIND,payload:{codebaseId:A.id,folder:A.folder,expectedOrigin:A.repository.canonicalOrigin,defaultBranch:A.defaultBranch,operation:e.operation,...e.branch?{branch:e.branch}:{},...e.stashOid?{stashOid:e.stashOid}:{},..."SWITCH_BRANCH"===e.operation?{stashChanges:!!e.stashChanges}:{}},idempotencyKey:`codebase:git:${e.operation}:${e.requestId}:${A.id}`,timeoutSeconds:"PULL_BRANCH"===e.operation?300:60})}subscribe(e){let t=l.agentEventBus.iterate(l.CODEBASE_CHANGED_TOPIC);return e?(0,A.filterAsyncIterator)(t,async A=>{let t=A.codebaseOverviewChanged;if(t.agentId)return t.agentId===e;let r=await (0,n.getPrismaClient)();if(t.codebaseId){let A=await r.codebase.findUnique({where:{id:t.codebaseId},select:{agentId:!0}});return!A||A.agentId===e}return!t.repositoryId||!!await r.codebase.findFirst({where:{repositoryId:t.repositoryId,agentId:e},select:{id:!0}})}):t}async projectJob(e){if(!e.codebaseId||!e.resultJson)return;let A=JSON.parse(e.resultJson);if(!A||"object"!=typeof A||Array.isArray(A))return;let t=A.snapshot;if(!t)return;let i=await this.applySnapshot(e.agentId,e.codebaseId,(0,r.parseCodebaseSnapshot)(t));i.changed&&this.publish(i.codebase.id,i.codebase.repositoryId)}async projectGitOperation(e){if("SUCCEEDED"===e.status)try{await this.projectJob(e)}catch(e){console.error("Could not project codebase Git operation:",e instanceof Error?e.message:e)}try{await this.agentControl.requestCodebaseReconcile([e.agentId])}catch(e){console.error("Could not request codebase reconciliation:",e instanceof Error?e.message:e)}}async applySnapshot(e,A,t){let r=await (0,n.getPrismaClient)(),i=await r.codebase.findUnique({where:{id:A},include:{repository:!0}});if(!i||i.agentId!==e)throw Error("Codebase not found for this agent");let a=new Date(t.checkedAt),o=null!==t.canonicalOrigin&&t.canonicalOrigin!==i.repository.canonicalOrigin,s=t.fetchedAt?new Date(t.fetchedAt):null,l=await r.codebase.updateMany({where:{id:A,agentId:e,OR:[{lastCheckedAt:null},{lastCheckedAt:{lt:a}}]},data:{folder:t.folder,...null===t.observedOrigin?{}:{observedOrigin:t.observedOrigin},branch:t.branch,headSha:t.headSha,upstream:t.upstream,ahead:t.ahead,behind:t.behind,syncState:t.syncState,availability:o?"ORIGIN_MISMATCH":t.availability,statusError:o?`Origin changed to ${t.displayOrigin??"an unknown remote"}`:t.error,lastCheckedAt:a}});l.count>0&&s&&await r.codebase.updateMany({where:{id:A,agentId:e,OR:[{lastFetchedAt:null},{lastFetchedAt:{lt:s}}]},data:{lastFetchedAt:s}});let d=await r.codebase.findUnique({where:{id:A},include:{agent:!0,repository:!0,jobs:!0}});if(!d||d.agentId!==e)throw Error("Codebase not found for this agent");return{codebase:d,changed:l.count>0}}snapshotData(e,A){return{folder:e.folder,observedOrigin:e.observedOrigin??"",branch:e.branch,headSha:e.headSha,upstream:e.upstream,ahead:e.ahead,behind:e.behind,syncState:e.syncState,availability:e.availability,statusError:e.error,lastCheckedAt:new Date(e.checkedAt),lastFetchedAt:A}}async requireAgentCapability(e,A){let t=await this.agentControl.getAgent(e);if(!t)throw Error("Agent not found");if(!g(t))throw Error("Agent is offline");if(!h(t).includes(A))throw Error("Agent must be updated to use codebases")}async requireRunnableCodebase(e,A){await this.cleanupInternalJobs();let t=await (0,n.getPrismaClient)(),r=await t.codebase.findUnique({where:{id:e},include:{agent:!0,repository:!0,jobs:{where:o.ACTIVE_CODEBASE_BLOCKING_JOB_WHERE,select:{id:!0},take:1}}});if(!r)throw Error("Codebase not found");if(!g(r.agent))throw Error("Agent is offline");if(!h(r.agent).includes(A))throw Error("Agent must be updated to manage Git branches and stashes");if("AVAILABLE"!==r.availability)throw Error(r.statusError||"Codebase is unavailable");if(r.jobs.length)throw Error("Another codebase operation is already running");return r}async waitForJob(e){let A=l.agentEventBus.iterate((0,l.agentJobChangedTopic)(e)),t=Date.now()+3e4;try{for(;Date.now()<t;){let r=await this.agentControl.getJob(e);if(!r)throw Error("Agent job disappeared");if(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"].includes(r.status))return r;await Promise.race([A.next(),new Promise(e=>setTimeout(e,t-Date.now()))])}throw await this.agentControl.cancelJob(e),Error("Agent did not respond in time")}finally{await A.return?.()}}publish(e,A,t){l.agentEventBus.publish(l.CODEBASE_CHANGED_TOPIC,{codebaseOverviewChanged:{codebaseId:e,repositoryId:A,agentId:t}})}async cleanupInternalJobs(){return this.cleanupInFlight?this.cleanupInFlight:Date.now()-this.lastCleanupAt<6e4?void 0:(this.cleanupInFlight=this.deleteExpiredInternalJobs().then(()=>{this.lastCleanupAt=Date.now()}).finally(()=>{this.cleanupInFlight=null}),this.cleanupInFlight)}async deleteExpiredInternalJobs(){let e=await (0,n.getPrismaClient)();await e.agentJob.deleteMany({where:{visibility:"SYSTEM",kind:{in:[...r.CODEBASE_JOB_KINDS]},finishedAt:{lt:new Date(Date.now()-9e5)}}})}}])},505228,e=>{"use strict";var A=e.i(749906);e.i(256554);var t=e.i(118387);let r=A.enum(["IN_SYNC","AHEAD","BEHIND","DIVERGED","NO_UPSTREAM","DETACHED","UNKNOWN"]),i=A.enum(["AVAILABLE","MISSING","NOT_REPOSITORY","ORIGIN_MISMATCH","ERROR"]),n=A.object({id:A.string(),path:A.string(),observedOrigin:A.string(),branch:A.string().nullable(),headSha:A.string().nullable(),upstream:A.string().nullable(),ahead:A.number().int().nullable(),behind:A.number().int().nullable(),syncState:r,availability:i,statusError:A.string().nullable(),lastCheckedAt:A.string().nullable(),lastFetchedAt:A.string().nullable(),lastFetchAttemptAt:A.string().nullable().optional(),lastFetchError:A.string().nullable().optional(),defaultBranch:A.string().nullable().optional(),localBranches:A.array(A.string()).optional(),remoteBranches:A.array(A.string()).optional(),createdAt:A.string().optional(),updatedAt:A.string().optional(),repository:A.object({id:A.string(),name:A.string(),description:A.string(),canonicalOrigin:A.string(),displayOrigin:A.string()}),agent:A.object({id:A.string(),name:A.string(),hostname:A.string(),connectionStatus:A.enum(["ONLINE","OFFLINE"])}),activeJob:A.object({id:A.string(),kind:A.string(),status:A.enum(["QUEUED","RUNNING"])}).nullable()}),a=A.object({codebases:A.array(n)}),o=A.object({}),s=A.union([A.object({id:A.string().min(1).describe("Registered codebase ID")}),A.object({path:A.string().min(1).describe("Exact absolute folder path of the codebase"),agentId:A.string().min(1).optional().describe("Agent ID used to disambiguate a shared folder path")})]),l=A.object({codebase:n}),d=A.object({query:A.string().min(1).optional(),agentId:A.string().min(1).optional(),repositoryId:A.string().min(1).optional(),branch:A.string().min(1).optional(),availability:i.optional(),syncState:r.optional(),limit:A.number().int().min(1).max(500).default(100)}).refine(({query:e,agentId:A,repositoryId:t,branch:r,availability:i,syncState:n})=>!!(e||A||t||r||i||n),{message:"At least one codebase search criterion is required"}),u=A.object({codebases:A.array(n),matchingCount:A.number().int().nonnegative()}),c=A.object({id:A.string(),name:A.string(),description:A.string(),canonicalOrigin:A.string(),displayOrigin:A.string(),jiraBranchRegex:A.string().nullable(),keepBaseBranchUpToDate:A.boolean(),codebaseCount:A.number().int().nonnegative(),agentIds:A.array(A.string()),createdAt:A.string(),updatedAt:A.string()}),h=A.object({repositories:A.array(c)}),g=A.object({id:A.string().min(1)}),p=A.object({repository:c.extend({codebases:A.array(n)})});class C extends Error{code;matches;constructor(e,A,t=[]){super(A),this.code=e,this.matches=t,this.name="CodebaseLookupError"}}e.s(["CodebaseToolRecordSchema",0,n,"CodebaseToolsService",0,class{codebasesService;constructor(e){this.codebasesService=e}stringArray(e){try{let A=JSON.parse(e);return Array.isArray(A)?A.filter(e=>"string"==typeof e):[]}catch{return[]}}record(e,A){var r;let i=A.jobs[0]??null;return n.parse({id:A.id,path:A.folder,observedOrigin:A.observedOrigin,branch:A.branch,headSha:A.headSha,upstream:A.upstream,ahead:A.ahead,behind:A.behind,syncState:A.syncState,availability:A.availability,statusError:A.statusError,lastCheckedAt:A.lastCheckedAt?.toISOString()??null,lastFetchedAt:A.lastFetchedAt?.toISOString()??null,lastFetchAttemptAt:A.lastFetchAttemptAt?.toISOString()??null,lastFetchError:A.lastFetchError,defaultBranch:A.defaultBranch,localBranches:this.stringArray(A.localBranchesJson),remoteBranches:this.stringArray(A.remoteBranchesJson),createdAt:A.createdAt.toISOString(),updatedAt:A.updatedAt.toISOString(),repository:{id:e.id,name:e.name,description:e.description,canonicalOrigin:e.canonicalOrigin,displayOrigin:e.displayOrigin},agent:{id:A.agent.id,name:A.agent.name,hostname:A.agent.hostname,connectionStatus:null!==(r=A.agent).lastSeenAt&&Date.now()-r.lastSeenAt.getTime()<=(0,t.agentOnlineWindowMs)(r)&&null===r.disconnectedAt?"ONLINE":"OFFLINE"},activeJob:i?{id:i.id,kind:i.kind,status:i.status}:null})}async list(){return(await this.codebasesService.overview()).flatMap(e=>e.codebases.map(A=>this.record(e,A)))}async getByPath(e,A){if("string"!=typeof e||0===e.trim().length)throw new C("INVALID_PATH","A non-empty codebase path is required");let t=(await this.list()).filter(t=>t.path===e&&(!A||t.agent.id===A));if(0===t.length)throw new C("CODEBASE_NOT_FOUND",`No codebase is registered at path ${e}`);if(t.length>1)throw new C("AMBIGUOUS_PATH",`More than one agent has a codebase registered at path ${e}`,t.map(({agent:e})=>({agentId:e.id,name:e.name,hostname:e.hostname})));return t[0]}async getById(e){let A=(await this.list()).find(A=>A.id===e);if(!A)throw new C("CODEBASE_NOT_FOUND",`No codebase is registered with id ${e}`);return A}async get(e){return"id"in e?this.getById(e.id):this.getByPath(e.path,e.agentId)}async search(e){let A=e.query?.toLocaleLowerCase(),t=(await this.list()).filter(t=>(!e.agentId||t.agent.id===e.agentId)&&(!e.repositoryId||t.repository.id===e.repositoryId)&&(!e.branch||t.branch===e.branch)&&(!e.availability||t.availability===e.availability)&&(!e.syncState||t.syncState===e.syncState)&&(!A||[t.id,t.path,t.observedOrigin,t.branch??"",t.repository.name,t.repository.description,t.repository.canonicalOrigin,t.agent.name,t.agent.hostname].some(e=>e.toLocaleLowerCase().includes(A))));return{codebases:t.slice(0,e.limit),matchingCount:t.length}}async repositories(){return(await this.codebasesService.overview()).map(e=>({id:e.id,name:e.name,description:e.description,canonicalOrigin:e.canonicalOrigin,displayOrigin:e.displayOrigin,jiraBranchRegex:e.jiraBranchRegex,keepBaseBranchUpToDate:e.keepBaseBranchUpToDate,codebaseCount:e.codebases.length,agentIds:[...new Set(e.codebases.map(e=>e.agentId))],createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}))}async repository(e){let A=(await this.codebasesService.overview()).find(A=>A.id===e);if(!A)throw Error("Codebase repository not found");return{...(await this.repositories()).find(A=>A.id===e),codebases:A.codebases.map(e=>this.record(A,e))}}},"GetCodebaseInputSchema",0,s,"GetCodebaseOutputSchema",0,l,"GetCodebaseRepositoriesOutputSchema",0,h,"GetCodebaseRepositoryInputSchema",0,g,"GetCodebaseRepositoryOutputSchema",0,p,"GetCodebasesInputSchema",0,o,"GetCodebasesOutputSchema",0,a,"SearchCodebasesInputSchema",0,d,"SearchCodebasesOutputSchema",0,u])},665537,e=>{"use strict";e.i(933653);var A=e.i(505228);e.i(404482).toJSONSchema(A.CodebaseToolRecordSchema),Object.fromEntries([["BadRequest","The path is missing or invalid"],["NotFound","No codebase uses the requested path"],["AmbiguousPath","Multiple agents use the requested path"],["Unauthorized","A Better Auth user session is required"],["InternalError","Unexpected server error"]].map(([e,A])=>[e,{description:A,content:{"application/json":{schema:{$ref:"#/components/schemas/ErrorResponse"}}}}])),e.s([],665537)},611377,e=>{"use strict";var A=e.i(404165),t=e.i(666680),r=e.i(591135),i=e.i(135475),n=e.i(532982);e.i(592299);var a=e.i(972425),o=e.i(863568),s=e.i(747461);e.i(256554);var l=e.i(848201);let d="default",u="gitlab:pipeline-status-changed",c={merge_requests_events:!0,note_events:!0,pipeline_events:!0,job_events:!0,push_events:!0,enable_ssl_verification:!0};class h extends Error{statusCode;requestId;constructor(e,A,t=null){super(e),this.statusCode=A,this.requestId=t,this.name="GitLabRequestError"}}function g(e){try{return JSON.parse(e)}catch{return null}}function p(e){return JSON.stringify(function e(A){return Array.isArray(A)?A.map(e):A&&"object"==typeof A?Object.fromEntries(Object.keys(A).sort().map(t=>[t,e(A[t])])):A}(e))}let C=/(?:authorization|password|private.?key|secret|signature|token)$/i;function f(e){return p(function e(A,t="",r=!1){if(C.test(t)||r&&"value"===t)return"[REDACTED]";let i=r||"variables"===t;return Array.isArray(A)?A.map(A=>e(A,"",i)):A&&"object"==typeof A?Object.fromEntries(Object.entries(A).map(([A,t])=>[A,e(t,A,i)])):A}(e??{})).slice(0,1e3)}function I(e,A){let t=e instanceof Error?e.message:String(e);return(A?t.replaceAll(A,"[REDACTED]"):t).slice(0,1e3)}function w(e){if(!e)return null;let A=Number(e);return Number.isSafeInteger(A)&&A>=0?A:null}function m(e){let A=w(e);return A&&A>0?A:null}function E(e){return{id:String(e.id),username:e.username,name:e.name,avatarUrl:e.avatar_url??null,webUrl:e.web_url}}function y(e){let A=e.toUpperCase();return new Set(["CREATED","WAITING_FOR_RESOURCE","PREPARING","PENDING","RUNNING","SUCCESS","FAILED","CANCELED","SKIPPED","MANUAL","SCHEDULED"]).has(A)?A:"UNKNOWN"}function B(e){return{id:String(e.id),projectId:String(e.project_id),iid:null==e.iid?null:String(e.iid),ref:e.ref,branch:e.ref,sha:e.sha,source:e.source,status:y(e.status),webUrl:e.web_url,mergeRequests:[],worktreeId:null,worktreeHighlightColor:null,startedAt:e.started_at??e.created_at??null,createdAt:e.created_at??null,updatedAt:e.updated_at??null,finishedAt:e.finished_at??null,duration:e.duration??null,queuedDuration:e.queued_duration??null}}function Q(e){return{id:String(e.id),pipelineId:String(e.pipeline.id),name:e.name,stage:e.stage,status:y(e.status),ref:e.ref,webUrl:e.web_url,allowFailure:e.allow_failure,createdAt:e.created_at??null,startedAt:e.started_at??null,finishedAt:e.finished_at??null,duration:e.duration??null,queuedDuration:e.queued_duration??null,retried:e.retried??!1}}function D(e){return{id:String(e.id),iid:e.iid,projectId:String(e.project_id),title:e.title,description:e.description??"",state:e.state.toUpperCase(),draft:e.draft??!1,webUrl:e.web_url,sourceBranch:e.source_branch,targetBranch:e.target_branch,sha:e.sha,author:E(e.author),reviewers:(e.reviewers??[]).map(E),labels:e.labels??[],detailedMergeStatus:e.detailed_merge_status??"unchecked",mergeWhenPipelineSucceeds:e.merge_when_pipeline_succeeds??!1,squashOnMerge:e.squash_on_merge??!1,hasConflicts:e.has_conflicts??!1,blockingDiscussionsResolved:e.blocking_discussions_resolved??!0,createdAt:e.created_at,updatedAt:e.updated_at,mergedAt:e.merged_at??null}}function b(e){return{id:e.id,individualNote:e.individual_note,notes:e.notes.map(e=>({id:String(e.id),body:e.body,author:E(e.author),createdAt:e.created_at,updatedAt:e.updated_at,system:e.system,resolvable:e.resolvable,resolved:e.resolved??!1,resolvedBy:e.resolved_by?E(e.resolved_by):null}))}}function S(e){return{...e,webhookConfiguredAt:e.webhookConfiguredAt?.toISOString()??null,webhookLastReceivedAt:e.webhookLastReceivedAt?.toISOString()??null}}function k(e){let A=new URLSearchParams;for(let t of Object.keys(e??{}).sort())for(let r of(Array.isArray(e?.[t])?e?.[t]:[e?.[t]])??[])null!=r&&A.append(t,String(r));return A}function R(e){return JSON.stringify(Object.fromEntries(e.entries()))}function v(e){if(!e)return new Headers;try{let A=JSON.parse(e);if(!A||"object"!=typeof A||Array.isArray(A))return new Headers;return new Headers(Object.fromEntries(Object.entries(A).filter(e=>"string"==typeof e[1])))}catch{return new Headers}}function G(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function T(e,A){return Object.prototype.hasOwnProperty.call(e,A)}e.s(["GitLabService",0,class{credentials;workflowEvents;polling;notifications;autoRetryTimer;cacheGeneration;getRequests;invalidatePendingGets(){this.cacheGeneration+=1,this.getRequests.clear()}constructor(e=new o.CredentialService,A,t,r){this.credentials=e,this.workflowEvents=A,this.polling=t,this.notifications=r,this.autoRetryTimer=null,this.cacheGeneration=0,this.getRequests=new Map,this.polling&&(this.polling.register({id:"server:gitlab-auto-retry",kind:"GITLAB_AUTO_RETRY",runtime:"SERVER",enabled:!0,cadenceSeconds:60,details:{}}),queueMicrotask(()=>void this.pollAutoRetry()))}subscribePipelineStatuses(){return l.agentEventBus.iterate(u)}publishPipeline(e){l.agentEventBus.publish(u,{gitlabPipelineStatusChanged:e})}scheduleAutoRetry(e){if(!this.polling)return;this.autoRetryTimer&&clearTimeout(this.autoRetryTimer);let A=1e3*Math.max(30,e);this.autoRetryTimer=setTimeout(()=>void this.pollAutoRetry(),A),this.autoRetryTimer.unref(),this.polling.schedule("server:gitlab-auto-retry",new Date(Date.now()+A))}async pollAutoRetry(){if(!this.polling)return;let e=60;try{let A=await this.getSettings();e=A.pipelinePollIntervalSeconds,this.polling.configure("server:gitlab-auto-retry",{enabled:A.configured,cadenceSeconds:e}),A.configured&&await this.polling.run("server:gitlab-auto-retry",()=>this.reconcileAutoRetries(),e=>({activeRules:e}))}catch{}finally{this.scheduleAutoRetry(e)}}async connection(){let[e,A]=await Promise.all([(0,s.readConnectionSettings)(this.credentials,a.CREDENTIALS.gitlabConnectionSettings,s.gitlabConnectionSettings),this.credentials.getText(a.CREDENTIALS.gitlabAccessToken)]);if(!e||!A)throw Error("GitLab credentials are not configured");return{baseUrl:e.value.baseUrl,token:A}}endpoint(e,A,t){let r;if(!A.startsWith("/"))throw Error("GitLab API paths must be relative");let i=((r=new URL(e)).pathname=`${r.pathname.replace(/\/+$/,"")}/api/v4/`,r),n=new URL(A.slice(1),i);if(n.origin!==i.origin||!n.pathname.startsWith(i.pathname))throw Error("GitLab API request escaped the configured instance root");return n.search=k(t).toString(),n}async fetchRaw(e){var A;let t,r=this.endpoint(e.baseUrl,e.path,e.query),i=await fetch(r,{method:e.method??"GET",headers:{Accept:"application/json","PRIVATE-TOKEN":e.token,...void 0===e.body?{}:{"Content-Type":"application/json"}},body:void 0===e.body?void 0:JSON.stringify(e.body),cache:"no-store",redirect:"manual"}),n=(t=w((A=i.headers).get("ratelimit-reset")),{limit:w(A.get("ratelimit-limit")),remaining:w(A.get("ratelimit-remaining")),resetAt:null===t?null:new Date(1e3*t),requestId:A.get("x-request-id")});if(i.status>=300&&i.status<400)throw new h("GitLab redirected the API request; configure the canonical instance URL",i.status,n.requestId);let a=await i.text(),o=a?g(a):null;if(!i.ok){let e=o&&"object"==typeof o&&"message"in o?JSON.stringify(o.message):a;throw new h(`GitLab API request failed (${i.status})${e?`: ${e.slice(0,500)}`:""}`,i.status,n.requestId)}return{data:o,status:i.status,headers:i.headers,endpoint:r.toString(),rateLimit:n}}async recordRateLimit(e){if(null===e.limit||null===e.remaining)return;let A=await (0,i.getPrismaClient)();await A.gitLabRateLimitSnapshot.upsert({where:{resource:"REST"},create:{id:(0,t.randomUUID)(),resource:"REST",limit:e.limit,remaining:e.remaining,resetAt:e.resetAt,observedAt:new Date},update:{limit:e.limit,remaining:e.remaining,resetAt:e.resetAt,observedAt:new Date}})}async logCall(e){let A=await (0,i.getPrismaClient)();await A.gitLabApiCallLog.create({data:{id:(0,t.randomUUID)(),method:e.method,endpoint:e.endpoint,operation:e.operation,requestSource:e.requestSource,requestSummary:e.requestSummary,source:e.source,durationMs:e.durationMs,statusCode:e.statusCode??null,error:e.error??null,servedStale:e.servedStale??!1,rateLimitLimit:e.rateLimit?.limit??null,rateLimitRemaining:e.rateLimit?.remaining??null,rateLimitResetAt:e.rateLimit?.resetAt??null,requestId:e.rateLimit?.requestId??null}})}async ttl(e){let A=await (0,i.getPrismaClient)(),[t,r]=await Promise.all([A.gitLabRestCacheTtlOverride.findUnique({where:{operation:e}}),A.gitLabSettings.upsert({where:{id:d},create:{id:d},update:{}})]);return t?.ttlSeconds??r.cacheTtlSeconds}async get(e){var A;let r=this.cacheGeneration,n=await this.connection(),a=this.endpoint(n.baseUrl,e.path,e.query).toString(),o={path:e.path,query:e.query??{}},s=(A={baseUrl:n.baseUrl,operation:e.operation,path:e.path,query:e.query},(0,t.createHash)("sha256").update(p({instance:(0,t.createHash)("sha256").update(A.baseUrl).digest("hex"),operation:A.operation,path:A.path,query:[...k(A.query).entries()].sort(([e,A],[t,r])=>e.localeCompare(t)||A.localeCompare(r))})).digest("hex")),l=await (0,i.getPrismaClient)(),d=await l.gitLabRestCacheEntry.findUnique({where:{cacheKey:s}}),u=await this.ttl(e.operation);if(d&&!0!==e.force&&Date.now()-d.fetchedAt.getTime()<1e3*u)return await this.logCall({method:"GET",endpoint:a,operation:e.operation,requestSource:e.source,requestSummary:p(o),source:"CACHE",durationMs:0,statusCode:200}),{data:g(d.responseJson),status:200,headers:v(d.responseHeadersJson),endpoint:a,rateLimit:{limit:null,remaining:null,resetAt:null,requestId:null}};let c=Date.now();try{let A=`${r}\0${(0,t.createHash)("sha256").update(n.token).digest("hex")}\0${s}`,i=this.getRequests.get(A);if(!i){i=(async()=>{let A=await this.fetchRaw({...n,path:e.path,query:e.query});return await Promise.all([r===this.cacheGeneration?l.gitLabRestCacheEntry.upsert({where:{cacheKey:s},create:{id:(0,t.randomUUID)(),cacheKey:s,endpoint:a,operation:e.operation,requestJson:p(o),responseJson:JSON.stringify(A.data),responseHeadersJson:R(A.headers),fetchedAt:new Date},update:{endpoint:a,operation:e.operation,requestJson:p(o),responseJson:JSON.stringify(A.data),responseHeadersJson:R(A.headers),fetchedAt:new Date}}):Promise.resolve(),this.recordRateLimit(A.rateLimit),this.logCall({method:"GET",endpoint:a,operation:e.operation,requestSource:e.source,requestSummary:p(o),source:"LIVE",durationMs:Date.now()-c,statusCode:A.status,rateLimit:A.rateLimit})]),A})(),this.getRequests.set(A,i);let d=()=>{this.getRequests.get(A)===i&&this.getRequests.delete(A)};i.then(d,d)}return await i}catch(t){let A=t instanceof h?t.statusCode:null;if(d&&!1!==e.allowStaleOnError)return await this.logCall({method:"GET",endpoint:a,operation:e.operation,requestSource:e.source,requestSummary:p(o),source:"CACHE",durationMs:Date.now()-c,statusCode:A,error:I(t,n.token),servedStale:!0}),{data:g(d.responseJson),status:200,headers:v(d.responseHeadersJson),endpoint:a,rateLimit:{limit:null,remaining:null,resetAt:null,requestId:null}};throw await this.logCall({method:"GET",endpoint:a,operation:e.operation,requestSource:e.source,requestSummary:p(o),source:"ERROR",durationMs:Date.now()-c,statusCode:A,error:I(t,n.token)}),t}}async mutate(e){this.invalidatePendingGets();let A=await this.connection(),t=this.endpoint(A.baseUrl,e.path).toString(),r=Date.now();try{let i=await this.fetchRaw({...A,path:e.path,method:e.method,body:e.body});return await Promise.all([this.recordRateLimit(i.rateLimit),this.logCall({method:e.method,endpoint:t,operation:e.operation,requestSource:e.source,requestSummary:f(e.body),source:"LIVE",durationMs:Date.now()-r,statusCode:i.status,rateLimit:i.rateLimit}),this.invalidateCache(e.invalidateProjectId)]),i.data}catch(i){throw await this.logCall({method:e.method,endpoint:t,operation:e.operation,requestSource:e.source,requestSummary:f(e.body),source:"ERROR",durationMs:Date.now()-r,statusCode:i instanceof h?i.statusCode:null,error:I(i,A.token)}),i}}async invalidateCache(e){this.invalidatePendingGets();let A=await (0,i.getPrismaClient)();await A.gitLabRestCacheEntry.deleteMany(e?{where:{endpoint:{contains:`/projects/${encodeURIComponent(e)}/`}}}:void 0)}async getSettings(){let e=await (0,i.getPrismaClient)(),[A,t,r]=await Promise.all([e.gitLabSettings.upsert({where:{id:d},create:{id:d},update:{}}),(0,s.readConnectionSettings)(this.credentials,a.CREDENTIALS.gitlabConnectionSettings,s.gitlabConnectionSettings),this.credentials.isConfigured(a.CREDENTIALS.gitlabAccessToken)]),n=A.currentUserId&&A.currentUsername&&A.currentUserName&&A.currentUserWebUrl?{id:A.currentUserId,username:A.currentUsername,name:A.currentUserName,avatarUrl:A.currentUserAvatarUrl,webUrl:A.currentUserWebUrl}:null;return{configured:!!(t&&r&&A.verifiedAt),tokenConfigured:r,baseUrl:t?.value.baseUrl??null,version:A.version,revision:A.revision,viewer:n,pipelinePollIntervalSeconds:A.pipelinePollIntervalSeconds,cacheTtlSeconds:A.cacheTtlSeconds,verifiedAt:A.verifiedAt?.toISOString()??null,updatedAt:A.updatedAt.toISOString()}}async verify(e,A){let[t,r]=await Promise.all([this.fetchRaw({baseUrl:e.baseUrl,token:A,path:"/user"}),this.fetchRaw({baseUrl:e.baseUrl,token:A,path:"/version"})]);if(!function(e){let A=e.match(/^(\d+)\.(\d+)/);if(!A)return!1;let t=Number(A[1]),r=Number(A[2]);return t>19||19===t&&r>=2}(r.data.version))throw Error(`GitLab 19.2 or later is required; the instance reported ${r.data.version}`);return{user:t.data,version:r.data}}async saveSettings(e){let A=function(e){let A;try{A=new URL(e.trim())}catch{throw Error("The GitLab instance URL is not a valid URL")}if("https:"!==A.protocol)throw Error("The GitLab instance URL must use HTTPS");if(A.username||A.password||A.search||A.hash)throw Error("The GitLab instance URL must not contain credentials, a query, or a fragment");return A.pathname=A.pathname.replace(/\/+$/,""),A.toString().replace(/\/$/,"")}(e.baseUrl),t=await this.credentials.getText(a.CREDENTIALS.gitlabAccessToken),r=e.accessToken?.trim()||t;if(!r)throw Error("A GitLab access token with api scope is required");let i=e.pipelinePollIntervalSeconds??60;if(!Number.isInteger(i)||i<30||i>3600)throw Error("GitLab pipeline polling interval must be from 30 to 3600 seconds");let n=await this.verify({baseUrl:A},r),o=[{descriptor:a.CREDENTIALS.gitlabConnectionSettings,value:(0,a.encodeJsonCredential)({baseUrl:A})},...e.accessToken?.trim()||!t?[{descriptor:a.CREDENTIALS.gitlabAccessToken,value:Buffer.from(r,"utf8")}]:[]];return await this.credentials.setMany(o,async e=>{await e.gitLabSettings.upsert({where:{id:d},create:{id:d,currentUserId:String(n.user.id),currentUsername:n.user.username,currentUserName:n.user.name,currentUserAvatarUrl:n.user.avatar_url??null,currentUserWebUrl:n.user.web_url,version:n.version.version,revision:n.version.revision??null,verifiedAt:new Date,pipelinePollIntervalSeconds:i},update:{currentUserId:String(n.user.id),currentUsername:n.user.username,currentUserName:n.user.name,currentUserAvatarUrl:n.user.avatar_url??null,currentUserWebUrl:n.user.web_url,version:n.version.version,revision:n.version.revision??null,verifiedAt:new Date,pipelinePollIntervalSeconds:i}})}),await this.invalidateCache(),this.getSettings()}async testConnection(){let e=await this.connection(),A=await this.verify({baseUrl:e.baseUrl},e.token),t=await (0,i.getPrismaClient)();return await t.gitLabSettings.upsert({where:{id:d},create:{id:d,currentUserId:String(A.user.id),currentUsername:A.user.username,currentUserName:A.user.name,currentUserAvatarUrl:A.user.avatar_url??null,currentUserWebUrl:A.user.web_url,version:A.version.version,revision:A.version.revision??null,verifiedAt:new Date},update:{currentUserId:String(A.user.id),currentUsername:A.user.username,currentUserName:A.user.name,currentUserAvatarUrl:A.user.avatar_url??null,currentUserWebUrl:A.user.web_url,version:A.version.version,revision:A.version.revision??null,verifiedAt:new Date}}),this.getSettings()}async clearCredentials(e=!1){let A=await this.projects(),t=[];for(let e of A.filter(e=>e.webhookId))try{await this.removeProjectWebhook(e.id)}catch{t.push(e.pathWithNamespace)}if(t.length&&!e)throw Error(`Could not remove AIDE-managed webhooks from: ${t.join(", ")}. Retry or force removal.`);await this.credentials.deleteMany([a.CREDENTIALS.gitlabConnectionSettings,a.CREDENTIALS.gitlabAccessToken,a.CREDENTIALS.gitlabWebhookSigningSecrets]),this.invalidatePendingGets();let r=await (0,i.getPrismaClient)();return await r.$transaction([r.gitLabProject.deleteMany(),r.gitLabRestCacheEntry.deleteMany(),r.gitLabSettings.upsert({where:{id:d},create:{id:d},update:{currentUserId:null,currentUsername:null,currentUserName:null,currentUserAvatarUrl:null,currentUserWebUrl:null,version:null,revision:null,verifiedAt:null}})]),this.getSettings()}async projects(){let e=await (0,i.getPrismaClient)();return(await e.gitLabProject.findMany({orderBy:{pathWithNamespace:"asc"}})).map(S)}async projectForCanonicalOrigin(e){let A=await this.getSettings();if(!A.configured||!A.baseUrl)return null;let t=new URL(A.baseUrl),r=`${t.host}${t.pathname}`.replace(/\/+$/,"").toLowerCase(),i=e.trim().replace(/^https?:\/\//i,"").replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase();return(await this.projects()).find(e=>i===`${r}/${e.pathWithNamespace}`.replace(/\/+/g,"/").toLowerCase())??null}async mergeRequestForBranch(e,A,t=!1){let r=await this.get({path:`/projects/${encodeURIComponent(e)}/merge_requests`,operation:"GitLabWorktreeMergeRequests",source:"WORKTREES",query:{state:"opened",source_branch:A,order_by:"updated_at",sort:"desc",per_page:1},force:t,allowStaleOnError:!t});return r.data[0]?D(r.data[0]):null}async availableProjects(e,A=1,t=50){let r=Math.max(1,Math.min(100,t)),n=await this.get({path:"/projects",operation:"GitLabAvailableProjects",source:"GITLAB_SETTINGS",query:{membership:!0,simple:!0,order_by:"path",sort:"asc",search:e?.trim()||void 0,page:A,per_page:r}}),a=await (0,i.getPrismaClient)(),o=new Set((await a.gitLabProject.findMany({select:{id:!0}})).map(e=>e.id));return{items:n.data.map(e=>({id:String(e.id),name:e.name,pathWithNamespace:e.path_with_namespace,webUrl:e.web_url,defaultBranch:e.default_branch??null,visibility:e.visibility,alreadyManaged:o.has(String(e.id))})),total:w(n.headers.get("x-total"))??n.data.length,page:A,perPage:r,nextPage:m(n.headers.get("x-next-page"))}}async addProject(e){let A=(await this.get({path:`/projects/${encodeURIComponent(e)}`,operation:"GitLabProject",source:"GITLAB_SETTINGS",force:!0})).data,t=await (0,i.getPrismaClient)();return await t.gitLabProject.upsert({where:{id:String(A.id)},create:{id:String(A.id),name:A.name,pathWithNamespace:A.path_with_namespace,webUrl:A.web_url,defaultBranch:A.default_branch??null,visibility:A.visibility},update:{name:A.name,pathWithNamespace:A.path_with_namespace,webUrl:A.web_url,defaultBranch:A.default_branch??null,visibility:A.visibility,enabled:!0}}),this.projects()}async webhookSecrets(){let e=await this.credentials.getJson(a.CREDENTIALS.gitlabWebhookSigningSecrets);return!e||"object"!=typeof e||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(e=>"string"==typeof e[1]))}signingToken(){return`whsec_${(0,t.randomBytes)(32).toString("base64")}`}normalizeWebhookUrl(e){let A=new URL(e.trim());if("https:"!==A.protocol||A.username||A.password||A.search||A.hash)throw Error("GitLab webhook URL must be a public HTTPS URL without credentials, query, or fragment");return A.toString()}async configureProjectWebhook(e,A){await this.credentials.assertWritable();let t=this.normalizeWebhookUrl(A),r=await this.webhookSecrets(),n=r[e]??this.signingToken(),o=await (0,i.getPrismaClient)(),s=await o.gitLabProject.findUnique({where:{id:e}});if(!s)throw Error("The GitLab project is not managed by AIDE");let l=s.webhookId,d=!1,u=null;try{let A={url:t,name:"AIDE",description:"AIDE merge request and pipeline events",signing_token:n,...c};if(l)await this.mutate({method:"PUT",path:`/projects/${encodeURIComponent(e)}/hooks/${encodeURIComponent(l)}`,operation:"GitLabUpdateProjectWebhook",source:"WEBHOOK_MANAGEMENT",body:A,invalidateProjectId:e});else{let t=await this.mutate({method:"POST",path:`/projects/${encodeURIComponent(e)}/hooks`,operation:"GitLabCreateProjectWebhook",source:"WEBHOOK_MANAGEMENT",body:A,invalidateProjectId:e});l=String(t.id)}}catch(e){if(e instanceof h&&[401,403,404].includes(e.statusCode??0))d=!0,l=null,u="Automatic setup requires the Maintainer or Owner role. Configure this project webhook manually.";else throw e}return await this.credentials.setJson(a.CREDENTIALS.gitlabWebhookSigningSecrets,{...r,[e]:n},async A=>{await A.gitLabProject.update({where:{id:e},data:{webhookId:l,webhookState:d?"MANUAL_REQUIRED":"CONFIGURED",webhookError:u,webhookConfiguredAt:d?null:new Date}})}),{project:S(await o.gitLabProject.findUniqueOrThrow({where:{id:e}})),callbackUrl:t,signingToken:d?n:null,manualConfigurationRequired:d}}async removeProjectWebhook(e){let A=await (0,i.getPrismaClient)(),t=await A.gitLabProject.findUnique({where:{id:e}});if(!t)throw Error("The GitLab project is not managed by AIDE");t.webhookId&&await this.mutate({method:"DELETE",path:`/projects/${encodeURIComponent(e)}/hooks/${encodeURIComponent(t.webhookId)}`,operation:"GitLabDeleteProjectWebhook",source:"WEBHOOK_MANAGEMENT",invalidateProjectId:e});let r=await this.webhookSecrets();return delete r[e],await this.credentials.setJson(a.CREDENTIALS.gitlabWebhookSigningSecrets,r,async A=>{await A.gitLabProject.update({where:{id:e},data:{webhookId:null,webhookState:"NOT_CONFIGURED",webhookError:null,webhookConfiguredAt:null}})}),S(await A.gitLabProject.findUniqueOrThrow({where:{id:e}}))}async removeProject(e,A=!1){let t=await (0,i.getPrismaClient)(),r=await t.gitLabProject.findUnique({where:{id:e}});if(!r)return this.projects();if(r.webhookId)try{await this.removeProjectWebhook(e)}catch(e){if(!A)throw e}let n=await this.webhookSecrets();return delete n[e],await this.credentials.setJson(a.CREDENTIALS.gitlabWebhookSigningSecrets,n,async A=>{await A.gitLabProject.delete({where:{id:e}})}),await this.invalidateCache(e),this.projects()}async webhooksEnabled(){let e=await (0,i.getPrismaClient)();return await e.gitLabProject.count({where:{webhookState:{in:["CONFIGURED","MANUAL_REQUIRED"]}}})>0}async mergeRequests(e){let A=Math.max(1,e.page??1),t=Math.max(1,Math.min(100,e.perPage??25));if("PROJECT"===e.scope&&!e.projectId)throw Error("A project is required for project-scoped merge requests");let r=e.projectId?`/projects/${encodeURIComponent(e.projectId)}/merge_requests`:"/merge_requests",i="MINE"===e.scope?"created_by_me":"REVIEW_REQUESTED"===e.scope?"reviews_for_me":"all",n=await this.get({path:r,operation:"GitLabMergeRequests",source:"MERGE_REQUESTS_PAGE",query:{scope:i,state:e.state&&"ALL"!==e.state?e.state.toLowerCase():"all",order_by:"updated_at",sort:"desc",page:A,per_page:t}});return{items:n.data.map(D),total:w(n.headers.get("x-total"))??n.data.length,page:A,perPage:t,nextPage:m(n.headers.get("x-next-page"))}}async mergeRequest(e,A){let t=`/projects/${encodeURIComponent(e)}/merge_requests/${A}`,[r,i,n,a]=await Promise.all([this.get({path:t,operation:"GitLabMergeRequest",source:"MERGE_REQUEST_DETAILS",query:{include_rebase_in_progress:!0}}),this.get({path:`${t}/commits`,operation:"GitLabMergeRequestCommits",source:"MERGE_REQUEST_DETAILS",query:{per_page:100}}),this.get({path:`${t}/discussions`,operation:"GitLabMergeRequestDiscussions",source:"MERGE_REQUEST_DETAILS",query:{per_page:100}}),this.get({path:`${t}/pipelines`,operation:"GitLabMergeRequestPipelines",source:"MERGE_REQUEST_DETAILS",query:{per_page:100}})]);return{...D(r.data),changesCount:r.data.changes_count??null,commitsCount:i.data.length,discussions:n.data.map(b),pipelines:a.data.map(B)}}async createMergeRequest(e){return D(await this.mutate({method:"POST",path:`/projects/${encodeURIComponent(e.projectId)}/merge_requests`,operation:"GitLabCreateMergeRequest",source:"MERGE_REQUESTS_PAGE",body:{source_branch:e.sourceBranch,target_branch:e.targetBranch,title:e.title,description:e.description??void 0,reviewer_ids:e.reviewerIds?.map(Number),labels:e.labels?.join(","),remove_source_branch:e.removeSourceBranch??void 0,squash:e.squash??void 0},invalidateProjectId:e.projectId}))}async updateMergeRequest(e){return D(await this.mutate({method:"PUT",path:`/projects/${encodeURIComponent(e.projectId)}/merge_requests/${e.iid}`,operation:"GitLabUpdateMergeRequest",source:"MERGE_REQUEST_DETAILS",body:{title:e.title??void 0,description:e.description??void 0,state_event:e.stateEvent?.toLowerCase(),reviewer_ids:e.reviewerIds?.map(Number),labels:e.labels?.join(",")},invalidateProjectId:e.projectId}))}async submitReview(e){let A="APPROVE"===e.outcome?"approve":"REQUEST_CHANGES"===e.outcome?"requested_changes":"reviewed";return await this.mutate({method:"POST",path:`/projects/${encodeURIComponent(e.projectId)}/merge_requests/${e.iid}/notes`,operation:"GitLabSubmitReview",source:"MERGE_REQUEST_DETAILS",body:{body:[e.body?.trim(),`/submit_review ${A}`].filter(Boolean).join("\n\n")},invalidateProjectId:e.projectId}),!0}async replyToDiscussion(e){return await this.mutate({method:"POST",path:`/projects/${encodeURIComponent(e.projectId)}/merge_requests/${e.iid}/discussions/${encodeURIComponent(e.discussionId)}/notes`,operation:"GitLabReplyToDiscussion",source:"COMMENTS_PAGE",body:{body:e.body},invalidateProjectId:e.projectId}),b((await this.get({path:`/projects/${encodeURIComponent(e.projectId)}/merge_requests/${e.iid}/discussions/${encodeURIComponent(e.discussionId)}`,operation:"GitLabDiscussion",source:"COMMENTS_PAGE",force:!0})).data)}async setDiscussionResolved(e){return b(await this.mutate({method:"PUT",path:`/projects/${encodeURIComponent(e.projectId)}/merge_requests/${e.iid}/discussions/${encodeURIComponent(e.discussionId)}`,operation:"GitLabResolveDiscussion",source:"COMMENTS_PAGE",body:{resolved:e.resolved},invalidateProjectId:e.projectId}))}async mergeMergeRequest(e){return D(await this.mutate({method:"PUT",path:`/projects/${encodeURIComponent(e.projectId)}/merge_requests/${e.iid}/merge`,operation:"GitLabMergeMergeRequest",source:"MERGE_REQUEST_DETAILS",body:{squash:e.squash??void 0,should_remove_source_branch:e.removeSourceBranch??void 0,auto_merge:e.autoMerge??void 0,sha:e.sha??void 0},invalidateProjectId:e.projectId}))}async pipelineMergeRequests(e,A){try{return(await this.get({path:`/projects/${encodeURIComponent(e)}/repository/commits/${encodeURIComponent(A)}/merge_requests`,operation:"GitLabPipelineMergeRequests",source:"PIPELINES_PAGE",query:{per_page:100}})).data.map(e=>({projectId:String(e.project_id),iid:e.iid,title:e.title,webUrl:e.web_url,sourceBranch:e.source_branch}))}catch{return[]}}async pipelineWorktrees(e,A){let t=new Map,n=[...new Set(A.filter(Boolean))];if(!n.length)return t;let a=await (0,i.getPrismaClient)(),o=await a.gitLabProject.findUnique({where:{id:e},select:{webUrl:!0}});if(!o)return t;let s=(0,r.normalizeGitOrigin)(o.webUrl).canonicalOrigin,l=await a.codebaseRepository.findUnique({where:{canonicalOrigin:s},select:{id:!0}});if(!l)return t;for(let e of(await a.worktree.findMany({where:{missingAt:null,branch:{in:n},codebase:{repositoryId:l.id}},orderBy:{updatedAt:"desc"},select:{id:!0,branch:!0,highlightColor:!0}})))!e.branch||t.has(e.branch)||t.set(e.branch,{id:e.id,highlightColor:e.highlightColor});return t}async enrichPipelines(e,A){if(!A.length)return A;let t=new Map(await (0,n.mapIntegrationRequests)([...new Set(A.map(e=>e.sha))],async A=>[A,await this.pipelineMergeRequests(e,A)])),r=A.map(e=>{var A;let r,i;return A=t.get(e.sha)??[],(i=(r=e.ref.match(/^refs\/merge-requests\/(\d+)\/(?:head|merge)$/))?A.find(e=>e.iid===Number(r[1])):A.find(A=>A.sourceBranch===e.ref))?i.sourceBranch:"merge_request_event"===e.source&&A[0]?A[0].sourceBranch:e.ref}),i=await this.pipelineWorktrees(e,r);return A.map((e,A)=>{let n=r[A]??e.ref,a=i.get(n);return{...e,branch:n,mergeRequests:t.get(e.sha)??[],worktreeId:a?.id??null,worktreeHighlightColor:a?.highlightColor??null}})}async observePipelines(e){if(!e.length)return;let A=await (0,i.getPrismaClient)();await A.$transaction(async A=>{for(let r of e){let e=await A.gitLabPipelineSnapshot.upsert({where:{projectId_headSha:{projectId:r.projectId,headSha:r.sha}},create:{id:(0,t.randomUUID)(),projectId:r.projectId,headSha:r.sha,status:r.status,lastObservedAt:new Date},update:{status:r.status,lastObservedAt:new Date}});await A.gitLabPipelineRecord.upsert({where:{snapshotId_pipelineId:{snapshotId:e.id,pipelineId:r.id}},create:{id:(0,t.randomUUID)(),snapshotId:e.id,pipelineId:r.id,ref:r.ref,status:r.status,webUrl:r.webUrl,source:r.source,gitlabUpdatedAt:r.updatedAt?new Date(r.updatedAt):null,lastObservedAt:new Date},update:{ref:r.ref,status:r.status,webUrl:r.webUrl,source:r.source,gitlabUpdatedAt:r.updatedAt?new Date(r.updatedAt):null,lastObservedAt:new Date}})}})}async pipelines(e,A=1,t=25){let r=Math.max(1,Math.min(100,t)),i=await this.get({path:`/projects/${encodeURIComponent(e)}/pipelines`,operation:"GitLabPipelines",source:"PIPELINES_PAGE",query:{page:A,per_page:r,order_by:"id",sort:"desc"}}),n=await this.enrichPipelines(e,i.data.map(B));return await this.observePipelines(n),{items:n,total:w(i.headers.get("x-total"))??i.data.length,page:A,perPage:r,nextPage:m(i.headers.get("x-next-page"))}}async pipelinesForCommit(e,A){let t=await this.get({path:`/projects/${encodeURIComponent(e)}/pipelines`,operation:"GitLabWorktreePipelines",source:"WORKTREES",query:{sha:A,per_page:100,order_by:"id",sort:"desc"},allowStaleOnError:!0}),r=await this.enrichPipelines(e,t.data.map(B));return await this.observePipelines(r),r}async pipeline(e,A){let t=B((await this.get({path:`/projects/${encodeURIComponent(e)}/pipelines/${encodeURIComponent(A)}`,operation:"GitLabPipeline",source:"PIPELINES_PAGE"})).data);return await this.observePipelines([t]),(await this.enrichPipelines(e,[t]))[0]??t}async pipelineJobs(e,A){let t=(await this.get({path:`/projects/${encodeURIComponent(e)}/pipelines/${encodeURIComponent(A)}/jobs`,operation:"GitLabPipelineJobs",source:"PIPELINES_PAGE",query:{include_retried:!0,per_page:100}})).data.map(Q),r=await (0,i.getPrismaClient)();return await r.gitLabPipelineRecord.updateMany({where:{pipelineId:A},data:{jobsJson:JSON.stringify(t),lastObservedAt:new Date}}),t}async createPipeline(e,A,t=[]){let r=B(await this.mutate({method:"POST",path:`/projects/${encodeURIComponent(e)}/pipeline`,operation:"GitLabCreatePipeline",source:"PIPELINES_PAGE",body:{ref:A,variables:t.map(e=>({...e,variable_type:"env_var"}))},invalidateProjectId:e}));return await this.observePipelines([r]),this.publishPipeline(r),r}async retryPipeline(e,A){let t=B(await this.mutate({method:"POST",path:`/projects/${encodeURIComponent(e)}/pipelines/${encodeURIComponent(A)}/retry`,operation:"GitLabRetryPipeline",source:"PIPELINES_PAGE",invalidateProjectId:e}));return await this.observePipelines([t]),this.publishPipeline(t),t}async cancelPipeline(e,A){let t=B(await this.mutate({method:"POST",path:`/projects/${encodeURIComponent(e)}/pipelines/${encodeURIComponent(A)}/cancel`,operation:"GitLabCancelPipeline",source:"PIPELINES_PAGE",invalidateProjectId:e}));return await this.observePipelines([t]),this.publishPipeline(t),t}async retryJob(e,A){return Q(await this.mutate({method:"POST",path:`/projects/${encodeURIComponent(e)}/jobs/${encodeURIComponent(A)}/retry`,operation:"GitLabRetryJob",source:"PIPELINES_PAGE",invalidateProjectId:e}))}async cachedEntries(e=50,A=0){let t=await (0,i.getPrismaClient)(),[r,n]=await Promise.all([t.gitLabRestCacheEntry.findMany({orderBy:{fetchedAt:"desc"},take:e,skip:A}),t.gitLabRestCacheEntry.count()]),a=Date.now();return{items:await Promise.all(r.map(async e=>({id:e.id,operation:e.operation,endpoint:e.endpoint,fetchedAt:e.fetchedAt.toISOString(),stale:a-e.fetchedAt.getTime()>=await this.ttl(e.operation)*1e3}))),total:n,limit:e,offset:A}}async cacheMetrics(){let e=await (0,i.getPrismaClient)(),[A,t]=await Promise.all([e.gitLabRestCacheEntry.count(),e.gitLabApiCallLog.findMany({select:{source:!0,servedStale:!0,durationMs:!0}})]),r=t.reduce((e,A)=>e+A.durationMs,0);return{entries:A,calls:t.length,liveCalls:t.filter(({source:e})=>"LIVE"===e).length,cacheHits:t.filter(({source:e})=>"CACHE"===e).length,errors:t.filter(({source:e})=>"ERROR"===e).length,staleFallbacks:t.filter(({servedStale:e})=>e).length,averageDurationMs:t.length?r/t.length:0}}async cachedEntry(e){let A=await (0,i.getPrismaClient)(),t=await A.gitLabRestCacheEntry.findUnique({where:{id:e}});return t?{id:t.id,operation:t.operation,endpoint:t.endpoint,fetchedAt:t.fetchedAt.toISOString(),stale:Date.now()-t.fetchedAt.getTime()>=await this.ttl(t.operation)*1e3,request:g(t.requestJson),response:g(t.responseJson)}:null}async clearCache(){return await this.invalidateCache(),!0}async deleteCachedEntry(e){this.invalidatePendingGets();let A=await (0,i.getPrismaClient)();return(await A.gitLabRestCacheEntry.deleteMany({where:{id:e}})).count>0}async updateCacheTtl(e){let A=60*e;if(!Number.isInteger(e)||A<1||A>86400)throw Error("GitLab cache TTL must be from 1 second to 24 hours");let t=await (0,i.getPrismaClient)();return await t.gitLabSettings.upsert({where:{id:d},create:{id:d,cacheTtlSeconds:A},update:{cacheTtlSeconds:A}}),this.getSettings()}async apiCalls(e=50,A=0){let t=await (0,i.getPrismaClient)(),[r,n]=await Promise.all([t.gitLabApiCallLog.findMany({orderBy:{createdAt:"desc"},take:e,skip:A}),t.gitLabApiCallLog.count()]);return{items:r.map(e=>({...e,source:e.source,rateLimitResetAt:e.rateLimitResetAt?.toISOString()??null,createdAt:e.createdAt.toISOString()})),total:n,limit:e,offset:A}}async webhookDeliveries(e=50,A=0){let t=await (0,i.getPrismaClient)(),[r,n]=await Promise.all([t.gitLabWebhookDelivery.findMany({orderBy:{receivedAt:"desc"},take:e,skip:A}),t.gitLabWebhookDelivery.count()]);return{items:r.map(e=>({id:e.id,webhookId:e.webhookId,eventType:e.eventType,projectId:e.projectId,objectKind:e.objectKind,action:e.action,outcome:e.outcome,error:e.error,receivedAt:e.receivedAt.toISOString(),processedAt:e.processedAt?.toISOString()??null})),total:n,limit:e,offset:A}}async rateLimitSnapshots(){let e=await (0,i.getPrismaClient)();return(await e.gitLabRateLimitSnapshot.findMany({orderBy:{observedAt:"desc"}})).map(e=>({...e,resetAt:e.resetAt?.toISOString()??null,observedAt:e.observedAt.toISOString(),createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}))}async cacheTtlOverrides(){let e=await (0,i.getPrismaClient)();return(await e.gitLabRestCacheTtlOverride.findMany({orderBy:{operation:"asc"}})).map(e=>({...e,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}))}async saveCacheTtlOverride(e,A){let t=e.trim();if(!t)throw Error("GitLab cache operation is required");if(!Number.isInteger(A)||A<1||A>86400)throw Error("GitLab cache TTL must be from 1 second to 24 hours");let r=await (0,i.getPrismaClient)();return await r.gitLabRestCacheTtlOverride.upsert({where:{operation:t},create:{operation:t,ttlSeconds:A},update:{ttlSeconds:A}}),this.cacheTtlOverrides()}async deleteCacheTtlOverride(e){let A=await (0,i.getPrismaClient)();return await A.gitLabRestCacheTtlOverride.deleteMany({where:{operation:e}}),this.cacheTtlOverrides()}async autoRetryRules(e){let A=await (0,i.getPrismaClient)();return(await A.gitLabAutoRetryRule.findMany({where:e?{projectId:e}:void 0,include:{executions:{orderBy:{createdAt:"desc"}}},orderBy:{updatedAt:"desc"}})).map(e=>({...e,lastAttemptAt:e.lastAttemptAt?.toISOString()??null,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString(),executions:e.executions.map(e=>({...e,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}))}))}async saveAutoRetryRule(e){if(!Number.isInteger(e.maxAttempts)||e.maxAttempts<1||e.maxAttempts>100)throw Error("GitLab auto-retry attempts must be from 1 to 100");let A=await (await (0,i.getPrismaClient)()).gitLabProject.findUnique({where:{id:e.projectId}});if(!A?.enabled)throw Error("A managed GitLab project is required");let r=await (0,i.getPrismaClient)(),n=e.id?null:await r.gitLabAutoRetryRule.findFirst({where:{projectId:e.projectId,pipelineId:e.pipelineId??null},select:{id:!0}}),a=e.id??n?.id??(0,t.randomUUID)();return await r.gitLabAutoRetryRule.upsert({where:{id:a},create:{id:a,projectId:e.projectId,pipelineId:e.pipelineId??null,enabled:e.enabled??!0,maxAttempts:e.maxAttempts},update:{projectId:e.projectId,pipelineId:e.pipelineId??null,enabled:e.enabled??!0,maxAttempts:e.maxAttempts}}),queueMicrotask(()=>void this.reconcileAutoRetries()),(await this.autoRetryRules()).find(e=>e.id===a)}async deleteAutoRetryRule(e){let A=await (0,i.getPrismaClient)();return(await A.gitLabAutoRetryRule.deleteMany({where:{id:e}})).count>0}async autoRetryFailedPipeline(e,A){let r=await (0,i.getPrismaClient)();for(let i of(await r.gitLabAutoRetryRule.findMany({where:{projectId:e,enabled:!0,OR:[{pipelineId:null},{pipelineId:A}]}}))){let n,a=await r.gitLabAutoRetryExecution.count({where:{ruleId:i.id,pipelineId:A}});if(a>=i.maxAttempts)continue;let o=a+1;try{n=await r.gitLabAutoRetryExecution.create({data:{id:(0,t.randomUUID)(),ruleId:i.id,pipelineId:A,attempt:o,status:"RUNNING"}})}catch{continue}try{await this.retryPipeline(e,A),await r.$transaction([r.gitLabAutoRetryExecution.update({where:{id:n.id},data:{status:"RETRIED"}}),r.gitLabAutoRetryRule.update({where:{id:i.id},data:{attempts:{increment:1},lastAttemptAt:new Date,lastError:null}})])}catch(A){let e=I(A);await r.$transaction([r.gitLabAutoRetryExecution.update({where:{id:n.id},data:{status:"FAILED",lastError:e}}),r.gitLabAutoRetryRule.update({where:{id:i.id},data:{lastAttemptAt:new Date,lastError:e}})])}}}async reconcileAutoRetries(){let e=await (0,i.getPrismaClient)(),A=await e.gitLabAutoRetryRule.findMany({where:{enabled:!0},select:{projectId:!0},distinct:["projectId"]});for(let{projectId:e}of A)for(let A of(await this.pipelines(e,1,100)).items)["FAILED","CANCELED"].includes(A.status)&&await this.autoRetryFailedPipeline(e,A.id);return A.length}async recordWebhookWorkflowEvents(e){if(!this.workflowEvents)return;let A=A=>{let t=e.payload[A];return t&&"object"==typeof t&&!Array.isArray(t)?t:{}},t=A("project"),r=A("object_attributes"),i=A("user"),n=String(e.payload.object_kind??"").toLowerCase(),a={repo:{provider:"GITLAB",gitlabProjectId:e.projectId,name:t.name??null,pathWithNamespace:t.path_with_namespace??null,webUrl:t.web_url??null},actor:{id:i.id??null,username:i.username??null,name:i.name??null}};if("merge_request"===n)a.pr={provider:"GITLAB",id:r.id??null,iid:r.iid??null,number:r.iid??null,title:r.title??null,description:r.description??null,state:r.state??null,action:r.action??null,isDraft:r.draft??!1,headRefName:r.source_branch??null,headRefOid:r.last_commit&&"object"==typeof r.last_commit?r.last_commit.id??null:null,targetBranch:r.target_branch??null,url:r.url??null,labels:e.payload.labels??r.labels??[]};else if("pipeline"===n)a.pipeline={id:r.id??null,status:r.status??null,ref:r.ref??null,sha:r.sha??null,source:r.source??null};else if("build"===n)a.job={id:e.payload.build_id??null,name:e.payload.build_name??null,stage:e.payload.build_stage??null,status:e.payload.build_status??null},a.pipeline={id:A("pipeline").id??null};else if("note"===n){let e=A("merge_request");a.pr={provider:"GITLAB",id:e.id??null,iid:e.iid??null,number:e.iid??null,title:e.title??null,state:e.state??null,headRefName:e.source_branch??null,targetBranch:e.target_branch??null,url:e.url??null},a.comment={id:r.id??null,body:r.note??null,url:r.url??null,author:{id:i.id??null,username:i.username??null,name:i.name??null}}}else"push"===n&&(a.push={ref:e.payload.ref??null,before:e.payload.before??null,after:e.payload.after??null,commits:e.payload.commits??[]});let o=function(e){let A=String(e.object_kind??"").toLowerCase(),t=G(e.object_attributes),r=G(e.changes),i=String(t.action??"").toLowerCase(),n=String(t.status??"").toLowerCase(),a=[];if("merge_request"===A){var o;let e="update"===i&&T(r,"draft")&&!1===(Array.isArray(o=r.draft)?o[1]:G(o).current);(["open","reopen"].includes(i)||e)&&a.push("GITLAB_MR_STATE"),["close","merge"].includes(i)&&a.push("GITLAB_MR_CLOSED"),"update"===i&&"string"==typeof t.oldrev&&t.oldrev.trim()&&a.push("GITLAB_MR_SYNCHRONIZED"),("approved"===i||"approval"===i)&&a.push("GITLAB_REVIEW_APPROVED"),"update"===i&&T(r,"labels")&&a.push("GITLAB_MR_LABEL")}else if("note"===A){if(!Object.keys(G(e.merge_request)).length)return[];a.push("GITLAB_REVIEW_COMMENT","GITLAB_NOTE_COMMAND");let A=String(t.note??"");A.includes("/submit_review requested_changes")&&a.push("GITLAB_REVIEW_CHANGES_REQUESTED"),A.includes("/submit_review approve")&&a.push("GITLAB_REVIEW_APPROVED")}else if("pipeline"===A)a.push("GITLAB_PIPELINE_STATUS_CHANGED"),["success","failed","canceled","skipped"].includes(n)&&a.push("GITLAB_PIPELINE_RESULT"),"failed"===n&&a.push("GITLAB_PIPELINE_FAILED"),"success"===n&&a.push("GITLAB_PIPELINE_SUCCEEDED");else if("build"===A)a.push("GITLAB_JOB_STATUS_CHANGED");else if("push"===A){let A=String(G(e.project).default_branch??""),t=String(e.ref??"");A&&t===`refs/heads/${A}`&&a.push("GITLAB_PUSH_DEFAULT")}return[...new Set(a)]}(e.payload);await Promise.all([...new Set(o)].map(A=>this.workflowEvents.record({kind:A,subjectKey:`${e.projectId}:${String(r.iid??r.id??e.messageId)}`,dedupeKey:`gitlab:${e.messageId}:${A}`,payload:{sessionData:a,providerEvent:e.payload}})))}async recordWebhookNotification(e){if(!this.notifications)return;let A=e.payload.object_attributes&&"object"==typeof e.payload.object_attributes?e.payload.object_attributes:{},t=String(e.payload.object_kind??"").toLowerCase(),r=null,n="/gitlab/merge-requests",a="GitLab update",o="GitLab reported an update.",s="GITLAB_MERGE_REQUEST",l=`${e.projectId}:${String(A.iid??A.id??e.messageId)}`;if("pipeline"===t){let t=String(A.status??"").toLowerCase();if("success"===t&&(r="GITLAB_PIPELINE_SUCCEEDED"),"failed"===t&&(r="GITLAB_PIPELINE_FAILED"),!r)return;let i=String(A.id??"");n=`/gitlab/pipelines?project=${encodeURIComponent(e.projectId)}&pipeline=${encodeURIComponent(i)}`,a="success"===t?"GitLab pipeline succeeded":"GitLab pipeline failed",o=`${String(A.ref??"Pipeline")} \xb7 #${i}`,s="GITLAB_PIPELINE",l=`${e.projectId}:${i}`}else if("merge_request"===t){let t=await (await (0,i.getPrismaClient)()).gitLabSettings.findUnique({where:{id:d},select:{currentUserId:!0,currentUsername:!0}});if(!function(e,A){var t;let r,i,n;if("merge_request"!==String(e.object_kind??"").toLowerCase()||!A.id&&!A.username)return!1;let a=String(G(e.object_attributes).action??"").toLowerCase(),o=e=>null!=A.id&&String(e.id??"")===A.id||null!=A.username&&String(e.username??"").toLowerCase()===A.username.toLowerCase();if(["open","reopen"].includes(a))return!!Array.isArray(e.reviewers)&&e.reviewers.map(G).some(o);if("update"!==a)return!1;let s=G(e.changes);if(!T(s,"reviewers"))return!1;let l=(r=G(t=s.reviewers),i=Array.isArray(t)?t:[r.previous,r.current],{previous:(n=e=>Array.isArray(e)?e.map(G).filter(e=>Object.keys(e).length):[])(i[0]),current:n(i[1])}),d=l.current.find(o);return!!d&&(!0===d.re_requested||!l.previous.some(o))}(e.payload,{id:t?.currentUserId??null,username:t?.currentUsername??null}))return;r="GITLAB_REVIEW_REQUESTED";let s=String(A.iid??"");n=`/gitlab/merge-requests/${encodeURIComponent(e.projectId)}/${encodeURIComponent(s)}`,a="GitLab review requested",o=String(A.title??`Merge request !${s}`)}if(!r)return;let u=await (0,i.getPrismaClient)(),c=await u.$transaction(A=>this.notifications.recordInTransaction(A,{dedupeKey:`gitlab:${e.messageId}:${r}`,typeKey:r,title:a,body:o,href:n,resourceKind:s,resourceId:l}));this.notifications.created(c)}async handleWebhook(e){let r,n=e.headers.get("webhook-id"),a=e.headers.get("webhook-timestamp"),o=e.headers.get("webhook-signature"),s=e.headers.get("x-gitlab-event")??"Unknown Hook";if(!n||!a||!o)throw Error("Missing GitLab Standard Webhook signature headers");let l=Number(a);if(!Number.isFinite(l)||Math.abs(Date.now()/1e3-l)>300)throw Error("GitLab webhook timestamp is outside the replay window");let d=g(e.rawBody);if(!d||"object"!=typeof d)throw Error("Invalid GitLab webhook JSON");let u=(r=d.project)&&"object"==typeof r&&"id"in r?String(r.id):"number"==typeof d.project_id?String(d.project_id):null;if(!u)throw Error("GitLab webhook payload does not identify a project");let c=(await this.webhookSecrets())[u];if(!c?.startsWith("whsec_"))throw Error("No signing token is configured for this GitLab project");!function(e){let A=Number(e.timestamp),r=e.now??Date.now();if(!Number.isFinite(A)||Math.abs(r/1e3-A)>300)throw Error("GitLab webhook timestamp is outside the replay window");if(!e.signingToken.startsWith("whsec_"))throw Error("Invalid GitLab webhook signing token");let i=Buffer.from(e.signingToken.slice(6),"base64"),n=(0,t.createHmac)("sha256",i).update(`${e.webhookId}.${e.timestamp}.${e.rawBody}`).digest();if(!e.signature.split(/\s+/).flatMap(e=>{let[A,t]=e.split(",",2);if("v1"!==A||!t)return[];try{return[Buffer.from(t,"base64")]}catch{return[]}}).some(e=>e.length===n.length&&(0,t.timingSafeEqual)(e,n)))throw Error("Invalid GitLab webhook signature")}({rawBody:e.rawBody,webhookId:n,timestamp:a,signature:o,signingToken:c});let h=await (0,i.getPrismaClient)(),p=d.object_attributes,C=p&&"object"==typeof p&&"action"in p?String(p.action):null,f={eventType:s,projectId:u,objectKind:"string"==typeof d.object_kind?d.object_kind:null,action:C,outcome:"RECEIVED",error:null,payloadJson:e.rawBody.slice(0,1e6),receivedAt:new Date(1e3*l),processedAt:null};try{await h.gitLabWebhookDelivery.create({data:{id:(0,t.randomUUID)(),webhookId:n,...f}})}catch(e){if(!("object"==typeof e&&null!==e&&"code"in e&&"P2002"===e.code))throw e;if(0===(await h.gitLabWebhookDelivery.updateMany({where:{webhookId:n,outcome:{notIn:["PROCESSED","IGNORED"]}},data:f})).count)return{duplicate:!0}}let w=async(e,A=null)=>{await h.gitLabWebhookDelivery.update({where:{webhookId:n},data:{outcome:e,error:A,processedAt:new Date}})};try{if(this.invalidatePendingGets(),await h.$transaction([h.gitLabProject.updateMany({where:{id:u},data:{webhookLastReceivedAt:new Date,webhookError:null}}),h.gitLabRestCacheEntry.deleteMany({where:{endpoint:{contains:`/projects/${encodeURIComponent(u)}/`}}})]),(0,A.publishIntegrationConfiguration)("gitlab"),await this.recordWebhookWorkflowEvents({messageId:n,eventType:s,projectId:u,payload:d}),await this.recordWebhookNotification({messageId:n,projectId:u,payload:d}),"pipeline"===String(d.object_kind??"").toLowerCase()&&["failed","canceled"].includes(String(d.object_attributes&&"object"==typeof d.object_attributes&&"status"in d.object_attributes?d.object_attributes.status:"").toLowerCase())){let e=d.object_attributes;null!=e.id&&await this.autoRetryFailedPipeline(u,String(e.id))}if("pipeline"===String(d.object_kind??"").toLowerCase()){let e=d.object_attributes;if(null!=e.id)try{this.publishPipeline(await this.pipeline(u,String(e.id)))}catch{}}return await w("PROCESSED"),{duplicate:!1}}catch(e){throw await w("ERROR",I(e,c)),e}}}])},375240,e=>{"use strict";e.i(611377),e.s([])},785730,e=>{"use strict";e.i(592299);var A=e.i(747461),t=e.i(972425),r=e.i(863568);let i={"exact-primary":"EXACT_PRIMARY","prefixed-primary":"PREFIXED_PRIMARY","exact-restore":"EXACT_RESTORE","prefixed-restore":"PREFIXED_RESTORE"};function n(e,A){return A?e.split(A).join("[REDACTED]"):e}function a(e){return{id:e.id,key:e.key,version:e.version,scope:e.scope,repoId:e.repoId,updatedAt:e.updatedAt,locationId:e.locationId}}e.s(["CacheServerService",0,class{credentials;constructor(e=new r.CredentialService){this.credentials=e}async storedSettings(){return(0,A.readConnectionSettings)(this.credentials,t.CREDENTIALS.cacheServerSettings,A.cacheServerConnectionSettings)}async getSettings(){let[e,A]=await Promise.all([this.storedSettings(),this.credentials.isConfigured(t.CREDENTIALS.cacheServerApiKey)]);return{configured:!!(e&&A),baseUrl:e?.value.baseUrl??null,apiKeyConfigured:A,headers:(e?.value.headers??[]).map(({name:e})=>({name:e,valueConfigured:!0})),updatedAt:(e?.updatedAt??new Date(0)).toISOString()}}async saveSettings(e){let A=function(e){let A,t=e.trim().replace(/\/+$/,"");if(!t)throw Error("A cache server base URL is required");try{A=new URL(t)}catch{throw Error("The cache server base URL is not a valid URL")}if("http:"!==A.protocol&&"https:"!==A.protocol)throw Error("The cache server base URL must use http or https");return t}(e.baseUrl),r=await this.credentials.isConfigured(t.CREDENTIALS.cacheServerApiKey),i=e.apiKey?.trim()||(r?await this.credentials.getText(t.CREDENTIALS.cacheServerApiKey):null);if(!i)throw Error("A cache server API key is required");let n=await this.storedSettings(),a=n?.value.headers??[],o={baseUrl:A,headers:function(e,A){if(!e)return[];let t=new Map(A.map(e=>[e.name.toLowerCase(),e.value])),r=new Set,i=[];for(let A of e){let e=A.name.trim();if(!e)continue;let n=e.toLowerCase();if(r.has(n))continue;r.add(n);let a=A.value||t.get(n);if(!a)throw Error(`A value is required for the ${e} header`);i.push({name:e,value:a})}return i}(e.headers,a)},s=[...e.apiKey?.trim()||!r?[{descriptor:t.CREDENTIALS.cacheServerApiKey,value:Buffer.from(i,"utf8")}]:[],...n&&JSON.stringify(o)===JSON.stringify(n.value)?[]:[{descriptor:t.CREDENTIALS.cacheServerSettings,value:(0,t.encodeJsonCredential)(o)}]];return s.length&&await this.credentials.setMany(s),this.getSettings()}async clearSettings(){return await this.credentials.deleteMany([t.CREDENTIALS.cacheServerApiKey,t.CREDENTIALS.cacheServerSettings]),this.getSettings()}async testConnection(){var e;if(!("object"==typeof(e=await this.request("GET","/cache-entries",{query:{itemsPerPage:1,page:1}}))&&null!==e&&"number"==typeof e.total&&Number.isInteger(e.total)&&e.total>=0&&Array.isArray(e.items)))throw Error("Cache server returned an invalid cache entry response");return this.getSettings()}async listCacheEntries(e){let A=await this.request("GET","/cache-entries",{query:{key:e.key?.trim()||void 0,version:e.version?.trim()||void 0,scope:e.scope?.trim()||void 0,repoId:e.repoId?.trim()||void 0,itemsPerPage:e.itemsPerPage??20,page:e.page??1}});return{total:A?.total??0,items:(A?.items??[]).map(a)}}async getCacheEntry(e){let A=await this.request("GET",`/cache-entries/${encodeURIComponent(e)}`,{allowNotFound:!0});return A?a(A):null}async getCacheEntryDetail(e){let A=await this.getCacheEntry(e);if(!A)return null;let t=A.locationId?await this.getStorageLocation(A.locationId):null;return{entry:A,location:t}}async getStorageLocation(e){let A=await this.request("GET",`/storage-locations/${encodeURIComponent(e)}`,{allowNotFound:!0});return A?{id:A.id,folderName:A.folderName,partCount:A.partCount,mergeStartedAt:A.mergeStartedAt??null,mergedAt:A.mergedAt??null,partsDeletedAt:A.partsDeletedAt??null,lastDownloadedAt:A.lastDownloadedAt??null,sizeBytes:A.sizeBytes??null}:null}async matchCacheEntry(e){let A=(e.restoreKeys??[]).map(e=>e.trim()).filter(Boolean),t=e.scopes.map(e=>e.trim()).filter(Boolean),r=await this.request("GET","/cache-entries/match",{query:{primaryKey:e.primaryKey,restoreKeys:A.length>0?A:void 0,scopes:t,repoId:e.repoId,version:e.version}});if(!r)return null;let n=i[r.type];if(!n)throw Error("Cache server returned an unknown match type");return{match:a(r.match),type:n}}async deleteCacheEntry(e){return await this.request("DELETE",`/cache-entries/${encodeURIComponent(e)}`,{allowNotFound:!0}),!0}async deleteCacheEntriesByIds(e){for(let A of e)await this.deleteCacheEntry(A);return!0}async deleteCacheEntries(e){let A=e.repoId?.trim();if(A){let t=new Set,r=1,i=0;do{let n=await this.listCacheEntries({...e,repoId:A,itemsPerPage:100,page:r});for(let e of(i=n.total,n.items))e.repoId===A&&t.add(e.id);r+=1}while((r-1)*100<i)return this.deleteCacheEntriesByIds([...t])}let t={};return e.key?.trim()&&(t.key=e.key.trim()),e.version?.trim()&&(t.version=e.version.trim()),e.scope?.trim()&&(t.scope=e.scope.trim()),await this.request("DELETE","/cache-entries",{body:t}),!0}async deleteStorageLocation(e){return await this.request("DELETE",`/storage-locations/${encodeURIComponent(e)}`,{allowNotFound:!0}),!0}async requireConfig(){let e=await this.storedSettings();if(!e)throw Error("The cache server is not configured");let A=await this.credentials.getText(t.CREDENTIALS.cacheServerApiKey);if(!A)throw Error("The cache server is not configured");return{baseUrl:e.value.baseUrl,apiKey:A,headers:e.value.headers}}buildUrl(e,A,t){let r=new URL(`${e}${A}`);if(t){for(let[e,A]of Object.entries(t))if(null!=A)if(Array.isArray(A))for(let t of A)r.searchParams.append(e,t);else r.searchParams.append(e,String(A))}return r.toString()}async request(e,A,t={}){let r,i,a=await this.requireConfig(),o=this.buildUrl(a.baseUrl,A,t.query),s={accept:"application/json"};for(let e of a.headers)s[e.name]=e.value;s["x-api-key"]=a.apiKey,void 0!==t.body&&(s["content-type"]="application/json");try{r=await fetch(o,{method:e,headers:s,body:void 0!==t.body?JSON.stringify(t.body):void 0,cache:"no-store"})}catch(e){throw Error(n(e instanceof Error?e.message:String(e),a.apiKey))}if(t.allowNotFound&&404===r.status)return null;let l=await r.text();if(l)try{i=JSON.parse(l)}catch{if(!r.ok)throw Error(`Cache server returned HTTP ${r.status}`);i=void 0}if(!r.ok)throw Error(n(i&&"object"==typeof i&&"message"in i&&"string"==typeof i.message?i.message:`Cache server returned HTTP ${r.status}`,a.apiKey));return i??null}}])},224354,e=>{"use strict";e.i(785730),e.s([])},76389,(e,A,t)=>{var r,i;i=r||(r={}),function(A){var t="object"==typeof globalThis?globalThis:e.g,r=n(i);function n(e,A){return function(t,r){Object.defineProperty(e,t,{configurable:!0,writable:!0,value:r}),A&&A(t,r)}}void 0!==t.Reflect&&(r=n(t.Reflect,r)),A(r,t),void 0===t.Reflect&&(t.Reflect=i)}(function(e,A){var t,r=Object.prototype.hasOwnProperty,i="function"==typeof Symbol,n=i&&void 0!==Symbol.toPrimitive?Symbol.toPrimitive:"@@toPrimitive",a=i&&void 0!==Symbol.iterator?Symbol.iterator:"@@iterator",o="function"==typeof Object.create,s=({__proto__:[]})instanceof Array,l=!o&&!s,d={create:o?function(){return U(Object.create(null))}:s?function(){return U({__proto__:null})}:function(){return U({})},has:l?function(e,A){return r.call(e,A)}:function(e,A){return A in e},get:l?function(e,A){return r.call(e,A)?e[A]:void 0}:function(e,A){return e[A]}},u=Object.getPrototypeOf(Function),c="function"==typeof Map&&"function"==typeof Map.prototype.entries?Map:function(){var e={},A=[],t=function(){function e(e,A,t){this._index=0,this._keys=e,this._values=A,this._selector=t}return e.prototype["@@iterator"]=function(){return this},e.prototype[a]=function(){return this},e.prototype.next=function(){var e=this._index;if(e>=0&&e<this._keys.length){var t=this._selector(this._keys[e],this._values[e]);return e+1>=this._keys.length?(this._index=-1,this._keys=A,this._values=A):this._index++,{value:t,done:!1}}return{value:void 0,done:!0}},e.prototype.throw=function(e){throw this._index>=0&&(this._index=-1,this._keys=A,this._values=A),e},e.prototype.return=function(e){return this._index>=0&&(this._index=-1,this._keys=A,this._values=A),{value:e,done:!0}},e}();function r(){this._keys=[],this._values=[],this._cacheKey=e,this._cacheIndex=-2}return Object.defineProperty(r.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),r.prototype.has=function(e){return this._find(e,!1)>=0},r.prototype.get=function(e){var A=this._find(e,!1);return A>=0?this._values[A]:void 0},r.prototype.set=function(e,A){var t=this._find(e,!0);return this._values[t]=A,this},r.prototype.delete=function(A){var t=this._find(A,!1);if(t>=0){for(var r=this._keys.length,i=t+1;i<r;i++)this._keys[i-1]=this._keys[i],this._values[i-1]=this._values[i];return this._keys.length--,this._values.length--,v(A,this._cacheKey)&&(this._cacheKey=e,this._cacheIndex=-2),!0}return!1},r.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=e,this._cacheIndex=-2},r.prototype.keys=function(){return new t(this._keys,this._values,i)},r.prototype.values=function(){return new t(this._keys,this._values,n)},r.prototype.entries=function(){return new t(this._keys,this._values,o)},r.prototype["@@iterator"]=function(){return this.entries()},r.prototype[a]=function(){return this.entries()},r.prototype._find=function(e,A){if(!v(this._cacheKey,e)){this._cacheIndex=-1;for(var t=0;t<this._keys.length;t++)if(v(this._keys[t],e)){this._cacheIndex=t;break}}return this._cacheIndex<0&&A&&(this._cacheIndex=this._keys.length,this._keys.push(e),this._values.push(void 0)),this._cacheIndex},r;function i(e,A){return e}function n(e,A){return A}function o(e,A){return[e,A]}}(),h="function"==typeof Set&&"function"==typeof Set.prototype.entries?Set:function(){function e(){this._map=new c}return Object.defineProperty(e.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),e.prototype.has=function(e){return this._map.has(e)},e.prototype.add=function(e){return this._map.set(e,e),this},e.prototype.delete=function(e){return this._map.delete(e)},e.prototype.clear=function(){this._map.clear()},e.prototype.keys=function(){return this._map.keys()},e.prototype.values=function(){return this._map.keys()},e.prototype.entries=function(){return this._map.entries()},e.prototype["@@iterator"]=function(){return this.keys()},e.prototype[a]=function(){return this.keys()},e}(),g="function"==typeof WeakMap?WeakMap:function(){var e=d.create(),A=i();function t(){this._key=i()}return t.prototype.has=function(e){var A=n(e,!1);return void 0!==A&&d.has(A,this._key)},t.prototype.get=function(e){var A=n(e,!1);return void 0!==A?d.get(A,this._key):void 0},t.prototype.set=function(e,A){return n(e,!0)[this._key]=A,this},t.prototype.delete=function(e){var A=n(e,!1);return void 0!==A&&delete A[this._key]},t.prototype.clear=function(){this._key=i()},t;function i(){var A;do A="@@WeakMap@@"+function(){var e=function(){if("function"==typeof Uint8Array){var e=new Uint8Array(16);return"u">typeof crypto?crypto.getRandomValues(e):"u">typeof msCrypto?msCrypto.getRandomValues(e):a(e,16),e}return a(Array(16),16)}();e[6]=79&e[6]|64,e[8]=191&e[8]|128;for(var A="",t=0;t<16;++t){var r=e[t];(4===t||6===t||8===t)&&(A+="-"),r<16&&(A+="0"),A+=r.toString(16).toLowerCase()}return A}();while(d.has(e,A))return e[A]=!0,A}function n(e,t){if(!r.call(e,A)){if(!t)return;Object.defineProperty(e,A,{value:d.create()})}return e[A]}function a(e,A){for(var t=0;t<A;++t)e[t]=255*Math.random()|0;return e}}(),p=i?Symbol.for("@reflect-metadata:registry"):void 0,C=(!B(p)&&D(A.Reflect)&&Object.isExtensible(A.Reflect)&&(t=A.Reflect[p]),B(t)&&(t=function(){B(p)||void 0===A.Reflect||p in A.Reflect||"function"!=typeof A.Reflect.defineMetadata||(t=(e=A.Reflect).defineMetadata,r=e.hasOwnMetadata,i=e.getOwnMetadata,n=e.getOwnMetadataKeys,a=e.deleteMetadata,o=new g,s={isProviderFor:function(e,A){var t=o.get(e);return!!(!B(t)&&t.has(A))||!!n(e,A).length&&(B(t)&&(t=new h,o.set(e,t)),t.add(A),!0)},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:r,OrdinaryGetOwnMetadata:i,OrdinaryOwnMetadataKeys:n,OrdinaryDeleteMetadata:a});var e,t,r,i,n,a,o,s,l,d,u,C=new g,f={registerProvider:function(e){if(!Object.isExtensible(f))throw Error("Cannot add provider to a frozen registry.");switch(!0){case s===e:break;case B(l):l=e;break;case l===e:break;case B(d):d=e;break;case d===e:break;default:void 0===u&&(u=new h),u.add(e)}},getProvider:I,setProvider:function(e,A,t){if(!function(e){if(B(e))throw TypeError();return l===e||d===e||!B(u)&&u.has(e)}(t))throw Error("Metadata provider not registered.");var r=I(e,A);if(r!==t){if(!B(r))return!1;var i=C.get(e);B(i)&&(i=new c,C.set(e,i)),i.set(A,t)}return!0}};return f;function I(e,A){var t,r=C.get(e);return B(r)||(t=r.get(A)),B(t)&&(t=function(e,A){if(!B(l)){if(l.isProviderFor(e,A))return l;if(!B(d)){if(d.isProviderFor(e,A))return l;if(!B(u))for(var t=T(u);;){var r=M(t);if(!r)return;var i=r.value;if(i.isProviderFor(e,A))return N(t),i}}}if(!B(s)&&s.isProviderFor(e,A))return s}(e,A),B(t)||(B(r)&&(r=new c,C.set(e,r)),r.set(A,t))),t}}()),!B(p)&&D(A.Reflect)&&Object.isExtensible(A.Reflect)&&Object.defineProperty(A.Reflect,p,{enumerable:!1,configurable:!1,writable:!1,value:t}),t),f=function(e){var A=new g,t={isProviderFor:function(e,t){var r=A.get(e);return!B(r)&&r.has(t)},OrdinaryDefineOwnMetadata:function(e,A,t,i){r(t,i,!0).set(e,A)},OrdinaryHasOwnMetadata:function(e,A,t){var i=r(A,t,!1);return!B(i)&&!!i.has(e)},OrdinaryGetOwnMetadata:function(e,A,t){var i=r(A,t,!1);if(!B(i))return i.get(e)},OrdinaryOwnMetadataKeys:function(e,A){var t=[],i=r(e,A,!1);if(B(i))return t;for(var n=T(i.keys()),a=0;;){var o=M(n);if(!o)return t.length=a,t;var s=o.value;try{t[a]=s}catch(e){try{N(n)}finally{throw e}}a++}},OrdinaryDeleteMetadata:function(e,t,i){var n=r(t,i,!1);if(B(n)||!n.delete(e))return!1;if(0===n.size){var a=A.get(t);B(a)||(a.delete(i),0===a.size&&A.delete(a))}return!0}};return C.registerProvider(t),t;function r(r,i,n){var a=A.get(r),o=!1;if(B(a)){if(!n)return;a=new c,A.set(r,a),o=!0}var s=a.get(i);if(B(s)){if(!n)return;if(s=new c,a.set(i,s),!e.setProvider(r,i,t))throw a.delete(i),o&&A.delete(r),Error("Wrong provider for target.")}return s}}(C);function I(e,A,t){var r=H(A,t,!1);return!B(r)&&!!r.OrdinaryHasOwnMetadata(e,A,t)}function w(e,A,t){var r=H(A,t,!1);if(!B(r))return r.OrdinaryGetOwnMetadata(e,A,t)}function m(e,A,t,r){H(t,r,!0).OrdinaryDefineOwnMetadata(e,A,t,r)}function E(e,A){var t=H(e,A,!1);return t?t.OrdinaryOwnMetadataKeys(e,A):[]}function y(e){if(null===e)return 1;switch(typeof e){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return null===e?1:6;default:return 6}}function B(e){return void 0===e}function Q(e){return null===e}function D(e){return"object"==typeof e?null!==e:"function"==typeof e}e("decorate",function(e,A,t,r){if(B(t)){if(!S(e)||!R(A))throw TypeError();for(var i=e,n=A,a=i.length-1;a>=0;--a){var o=(0,i[a])(n);if(!B(o)&&!Q(o)){if(!R(o))throw TypeError();n=o}}return n}if(!S(e)||!D(A)||!D(r)&&!B(r)&&!Q(r))throw TypeError();return Q(r)&&(r=void 0),function(e,A,t,r){for(var i=e.length-1;i>=0;--i){var n=(0,e[i])(A,t,r);if(!B(n)&&!Q(n)){if(!D(n))throw TypeError();r=n}}return r}(e,A,t=b(t),r)}),e("metadata",function(e,A){return function(t,r){if(!D(t)||!B(r)&&!function(e){switch(y(e)){case 3:case 4:return!0;default:return!1}}(r))throw TypeError();m(e,A,t,r)}}),e("defineMetadata",function(e,A,t,r){if(!D(t))throw TypeError();return B(r)||(r=b(r)),m(e,A,t,r)}),e("hasMetadata",function(e,A,t){if(!D(A))throw TypeError();return B(t)||(t=b(t)),function e(A,t,r){if(I(A,t,r))return!0;var i=O(t);return!Q(i)&&e(A,i,r)}(e,A,t)}),e("hasOwnMetadata",function(e,A,t){if(!D(A))throw TypeError();return B(t)||(t=b(t)),I(e,A,t)}),e("getMetadata",function(e,A,t){if(!D(A))throw TypeError();return B(t)||(t=b(t)),function e(A,t,r){if(I(A,t,r))return w(A,t,r);var i=O(t);if(!Q(i))return e(A,i,r)}(e,A,t)}),e("getOwnMetadata",function(e,A,t){if(!D(A))throw TypeError();return B(t)||(t=b(t)),w(e,A,t)}),e("getMetadataKeys",function(e,A){if(!D(e))throw TypeError();return B(A)||(A=b(A)),function e(A,t){var r=E(A,t),i=O(A);if(null===i)return r;var n=e(i,t);if(n.length<=0)return r;if(r.length<=0)return n;for(var a=new h,o=[],s=0;s<r.length;s++){var l=r[s],d=a.has(l);d||(a.add(l),o.push(l))}for(var u=0;u<n.length;u++){var l=n[u],d=a.has(l);d||(a.add(l),o.push(l))}return o}(e,A)}),e("getOwnMetadataKeys",function(e,A){if(!D(e))throw TypeError();return B(A)||(A=b(A)),E(e,A)}),e("deleteMetadata",function(e,A,t){if(!D(A)||(B(t)||(t=b(t)),!D(A)))throw TypeError();B(t)||(t=b(t));var r=H(A,t,!1);return!B(r)&&r.OrdinaryDeleteMetadata(e,A,t)});function b(e){var A=function(e){switch(y(e)){case 0:case 1:case 2:case 3:case 4:case 5:return e}var A="string",t=G(e,n);if(void 0!==t){var r=t.call(e,A);if(D(r))throw TypeError();return r}return function(e,A){if("string"===A){var t=e.toString;if(k(t)){var r=t.call(e);if(!D(r))return r}var i=e.valueOf;if(k(i)){var r=i.call(e);if(!D(r))return r}}else{var i=e.valueOf;if(k(i)){var r=i.call(e);if(!D(r))return r}var n=e.toString;if(k(n)){var r=n.call(e);if(!D(r))return r}}throw TypeError()}(e,A)}(e);return"symbol"==typeof A?A:""+A}function S(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:"[object Array]"===Object.prototype.toString.call(e)}function k(e){return"function"==typeof e}function R(e){return"function"==typeof e}function v(e,A){return e===A||e!=e&&A!=A}function G(e,A){var t=e[A];if(null!=t){if(!k(t))throw TypeError();return t}}function T(e){var A=G(e,a);if(!k(A))throw TypeError();var t=A.call(e);if(!D(t))throw TypeError();return t}function M(e){var A=e.next();return!A.done&&A}function N(e){var A=e.return;A&&A.call(e)}function O(e){var A=Object.getPrototypeOf(e);if("function"!=typeof e||e===u||A!==u)return A;var t=e.prototype,r=t&&Object.getPrototypeOf(t);if(null==r||r===Object.prototype)return A;var i=r.constructor;return"function"!=typeof i||i===e?A:i}function H(e,A,t){var r=C.getProvider(e,A);if(!B(r))return r;if(t){if(C.setProvider(e,A,f))return f;throw Error("Illegal state.")}}function U(e){return e.__=void 0,delete e.__,e}})},709932,456622,e=>{"use strict";var A=e.i(898912),t=e.i(969068);e.i(592299);var r=e.i(747461),i=e.i(972425),n=e.i(863568);class a extends Error{status;errors;constructor(e,A,t){super(e),this.status=A,this.errors=t,this.name="AppleDeveloperRequestError"}}async function o(e=new n.CredentialService){let A=await e.getJson(i.CREDENTIALS.appStoreConnectSettings);if(!A)throw Error("App Store Connect API credentials are not configured");let t=(0,r.appStoreConnectConnectionSettings)(A),a=await e.getText(i.CREDENTIALS.appStoreConnectPrivateKey);if(!a)throw Error("App Store Connect API credentials are not configured");return{issuerId:t.issuerId,keyId:t.keyId,privateKey:a}}e.s(["AppleDeveloperClient",0,class{credentials;fetcher;constructor(e,A=fetch){this.credentials=e,this.fetcher=A}async token(){let e;try{e=await (0,A.importPKCS8)(this.credentials.privateKey,"ES256")}catch{throw Error("The App Store Connect key must be an ES256 PKCS#8 private key")}return new t.SignJWT({}).setProtectedHeader({alg:"ES256",kid:this.credentials.keyId,typ:"JWT"}).setIssuer(this.credentials.issuerId).setAudience("appstoreconnect-v1").setIssuedAt().setExpirationTime("15m").sign(e)}async request(e,A={}){let t,r=await this.token(),i=e.startsWith("http")?e:`https://api.appstoreconnect.apple.com${e}`;try{t=await this.fetcher(i,{...A,signal:A.signal??AbortSignal.timeout(2e4),headers:{accept:"application/json",authorization:`Bearer ${r}`,...A.body?{"content-type":"application/json"}:{},...A.headers}})}catch(e){if(e instanceof Error&&("TimeoutError"===e.name||"AbortError"===e.name))throw Error("Apple Developer API timed out; retry the operation");throw Error("Could not connect to the Apple Developer API")}if(204===t.status)return;let n=await t.json().catch(()=>({}));if(!t.ok){let e=n.errors?.map(e=>e.detail||e.title||e.code).filter(Boolean).join("; ");throw new a(401===t.status||403===t.status?"Apple rejected the API key or it lacks Certificates, Identifiers & Profiles permission":e||`Apple Developer API returned HTTP ${t.status}`,t.status,n.errors??[])}return n}async list(e){let A=[],t=e;for(;t;){let e=await this.request(t);A.push(...e.data),t=e.links?.next??null}return A}listProfiles(){return this.list("/v1/profiles?limit=200&include=bundleId,certificates,devices")}listCertificates(){return this.list("/v1/certificates?limit=200")}listBundleIds(){return this.list("/v1/bundleIds?limit=200")}listDevices(){return this.list("/v1/devices?limit=200")}async createProfile(e){let A={bundleId:{data:{type:"bundleIds",id:e.bundleIdId}},certificates:{data:e.certificateIds.map(e=>({type:"certificates",id:e}))}};return e.deviceIds?.length&&(A.devices={data:e.deviceIds.map(e=>({type:"devices",id:e}))}),this.request("/v1/profiles",{method:"POST",body:JSON.stringify({data:{type:"profiles",attributes:{name:e.name,profileType:e.profileType},relationships:A}})})}deleteProfile(e){return this.request(`/v1/profiles/${encodeURIComponent(e)}`,{method:"DELETE"})}revokeCertificate(e){return this.request(`/v1/certificates/${encodeURIComponent(e)}`,{method:"DELETE"})}},"AppleDeveloperRequestError",0,a,"storedAppleDeveloperCredentials",0,o],456622),e.s([],709932)},587483,663084,e=>{"use strict";e.i(76389);var A,t,r,i,n,a,o,s,l,d,u,c,h,g,p,C,f,I,w,m,E,y,B,Q,D,b,S,k,R,v,G,T,M,N,O,H,U,_,x,L,P,q,K,J,F,j,z,Y,Z,V,W,$,X,ee,eA,et,er,ei,en,ea,eo,es,el,ed,eu,ec,eh,eg,ep,eC,ef,eI,ew,em,eE,ey,eB,eQ,eD,eb,eS,ek,eR,ev,eG,eT,eM,eN,eO,eH,eU,e_,ex,eL,eP,eq,eK,eJ,eF,ej,ez,eY,eZ=e.i(666680);class eV{static isArrayBuffer(e){return"[object ArrayBuffer]"===Object.prototype.toString.call(e)}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,A){if(e.constructor===A)return e;if(this.isArrayBuffer(e))return new A(e);if(this.isArrayBufferView(e))return new A(e.buffer,e.byteOffset,e.byteLength);throw TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,A){let t=eV.toUint8Array(e),r=eV.toUint8Array(A);if(t.length!==r.byteLength)return!1;for(let e=0;e<t.length;e++)if(t[e]!==r[e])return!1;return!0}static concat(...e){let A;A=!Array.isArray(e[0])||e[1]instanceof Function?Array.isArray(e[0])&&e[1]instanceof Function?e[0]:e[e.length-1]instanceof Function?e.slice(0,e.length-1):e:e[0];let t=0;for(let e of A)t+=e.byteLength;let r=new Uint8Array(t),i=0;for(let e of A){let A=this.toUint8Array(e);r.set(A,i),i+=A.length}return e[e.length-1]instanceof Function?this.toView(r,e[e.length-1]):r.buffer}}let eW="string",e$=/^[0-9a-f\s]+$/i,eX=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,e0=/^[a-zA-Z0-9-_]+$/;class e1{static fromString(e){let A=unescape(encodeURIComponent(e)),t=new Uint8Array(A.length);for(let e=0;e<A.length;e++)t[e]=A.charCodeAt(e);return t.buffer}static toString(e){let A=eV.toUint8Array(e),t="";for(let e=0;e<A.length;e++)t+=String.fromCharCode(A[e]);return decodeURIComponent(escape(t))}}class e8{static toString(e,A=!1){let t=eV.toArrayBuffer(e),r=new DataView(t),i="";for(let e=0;e<t.byteLength;e+=2)i+=String.fromCharCode(r.getUint16(e,A));return i}static fromString(e,A=!1){let t=new ArrayBuffer(2*e.length),r=new DataView(t);for(let t=0;t<e.length;t++)r.setUint16(2*t,e.charCodeAt(t),A);return t}}class e4{static isHex(e){return typeof e===eW&&e$.test(e)}static isBase64(e){return typeof e===eW&&eX.test(e)}static isBase64Url(e){return typeof e===eW&&e0.test(e)}static ToString(e,A="utf8"){let t=eV.toUint8Array(e);switch(A.toLowerCase()){case"utf8":return this.ToUtf8String(t);case"binary":return this.ToBinary(t);case"hex":return this.ToHex(t);case"base64":return this.ToBase64(t);case"base64url":return this.ToBase64Url(t);case"utf16le":return e8.toString(t,!0);case"utf16":case"utf16be":return e8.toString(t);default:throw Error(`Unknown type of encoding '${A}'`)}}static FromString(e,A="utf8"){if(!e)return new ArrayBuffer(0);switch(A.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return e8.fromString(e,!0);case"utf16":case"utf16be":return e8.fromString(e);default:throw Error(`Unknown type of encoding '${A}'`)}}static ToBase64(e){let A=eV.toUint8Array(e);return"u">typeof btoa?btoa(this.ToString(A,"binary")):Buffer.from(A).toString("base64")}static FromBase64(e){let A=this.formatString(e);if(!A)return new ArrayBuffer(0);if(!e4.isBase64(A))throw TypeError("Argument 'base64Text' is not Base64 encoded");return"u">typeof atob?this.FromBinary(atob(A)):new Uint8Array(Buffer.from(A,"base64")).buffer}static FromBase64Url(e){let A=this.formatString(e);if(!A)return new ArrayBuffer(0);if(!e4.isBase64Url(A))throw TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(A.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,A=e4.DEFAULT_UTF8_ENCODING){switch(A){case"ascii":return this.FromBinary(e);case"utf8":return e1.fromString(e);case"utf16":case"utf16be":return e8.fromString(e);case"utf16le":case"usc2":return e8.fromString(e,!0);default:throw Error(`Unknown type of encoding '${A}'`)}}static ToUtf8String(e,A=e4.DEFAULT_UTF8_ENCODING){switch(A){case"ascii":return this.ToBinary(e);case"utf8":return e1.toString(e);case"utf16":case"utf16be":return e8.toString(e);case"utf16le":case"usc2":return e8.toString(e,!0);default:throw Error(`Unknown type of encoding '${A}'`)}}static FromBinary(e){let A=e.length,t=new Uint8Array(A);for(let r=0;r<A;r++)t[r]=e.charCodeAt(r);return t.buffer}static ToBinary(e){let A=eV.toUint8Array(e),t="";for(let e=0;e<A.length;e++)t+=String.fromCharCode(A[e]);return t}static ToHex(e){let A=eV.toUint8Array(e),t="",r=A.length;for(let e=0;e<r;e++){let r=A[e];r<16&&(t+="0"),t+=r.toString(16)}return t}static FromHex(e){let A=this.formatString(e);if(!A)return new ArrayBuffer(0);if(!e4.isHex(A))throw TypeError("Argument 'hexString' is not HEX encoded");A.length%2&&(A=`0${A}`);let t=new Uint8Array(A.length/2);for(let e=0;e<A.length;e+=2){let r=A.slice(e,e+2);t[e/2]=parseInt(r,16)}return t.buffer}static ToUtf16String(e,A=!1){return e8.toString(e,A)}static FromUtf16String(e,A=!1){return e8.fromString(e,A)}static Base64Padding(e){let A=4-e.length%4;if(A<4)for(let t=0;t<A;t++)e+="=";return e}static formatString(e){return(null==e?void 0:e.replace(/[\n\r\t ]/g,""))||""}}function e2(e,A,t){var r;return e instanceof Object==!1?t:null!=(r=e[A])?r:t}function e6(e,A=0,t=e.byteLength-A,r=!1){let i="";for(let n of new Uint8Array(e,A,t)){let e=n.toString(16).toUpperCase();1===e.length&&(i+="0"),i+=e,r&&(i+=" ")}return i.trim()}function e3(e,A){let t=0;if(1===e.length)return e[0];for(let r=e.length-1;r>=0;r--)t+=e[e.length-1-r]*Math.pow(2,A*r);return t}function e5(e,A,t=-1){let r=e,i=0,n=Math.pow(2,A);for(let a=1;a<8;a++){if(e<n){let e;if(t<0)e=new ArrayBuffer(a),i=a;else{if(t<a)return new ArrayBuffer(0);e=new ArrayBuffer(t),i=t}let n=new Uint8Array(e);for(let e=a-1;e>=0;e--){let t=Math.pow(2,e*A);n[i-e-1]=Math.floor(r/t),r-=n[i-e-1]*t}return e}n*=Math.pow(2,A)}return new ArrayBuffer(0)}function e9(...e){let A=0,t=0;for(let t of e)A+=t.byteLength;let r=new ArrayBuffer(A),i=new Uint8Array(r);for(let A of e)i.set(new Uint8Array(A),t),t+=A.byteLength;return r}function e7(...e){let A=0,t=0;for(let t of e)A+=t.length;let r=new Uint8Array(new ArrayBuffer(A));for(let A of e)r.set(A,t),t+=A.length;return r}function Ae(){let e=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let A=255===e[0]&&128&e[1],t=0===e[0]&&(128&e[1])==0;(A||t)&&this.warnings.push("Needlessly long format")}let A=new Uint8Array(new ArrayBuffer(this.valueHex.byteLength));for(let e=0;e<this.valueHex.byteLength;e++)A[e]=0;A[0]=128&e[0];let t=e3(A,8),r=new Uint8Array(new ArrayBuffer(this.valueHex.byteLength));for(let A=0;A<this.valueHex.byteLength;A++)r[A]=e[A];return r[0]&=127,e3(r,8)-t}function AA(e,A){if(e.byteLength!==A.byteLength)return!1;let t=new Uint8Array(e),r=new Uint8Array(A);for(let e=0;e<t.length;e++)if(t[e]!==r[e])return!1;return!0}function At(e,A){let t=e.toString(10);if(A<t.length)return"";let r=A-t.length,i=Array.from({length:r});for(let e=0;e<r;e++)i[e]="0";return i.join("").concat(t)}e4.DEFAULT_UTF8_ENCODING="utf8";let Ar="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Ai="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=";function An(e,A=!1,t=!1,r=!1){let i=0,n=0,a=0,o="",s=A?Ai:Ar;if(r){let A=0;for(let t=0;t<e.length;t++)if(0!==e.charCodeAt(t)){A=t;break}e=e.slice(A)}for(;i<e.length;){let A=e.charCodeAt(i++);i>=e.length&&(n=1);let r=e.charCodeAt(i++);i>=e.length&&(a=1);let l=e.charCodeAt(i++),d=A>>2,u=(3&A)<<4|r>>4,c=(15&r)<<2|l>>6,h=63&l;1===n?c=h=64:1===a&&(h=64),t?64===c?o+=`${s.charAt(d)}${s.charAt(u)}`:64===h?o+=`${s.charAt(d)}${s.charAt(u)}${s.charAt(c)}`:o+=`${s.charAt(d)}${s.charAt(u)}${s.charAt(c)}${s.charAt(h)}`:o+=`${s.charAt(d)}${s.charAt(u)}${s.charAt(c)}${s.charAt(h)}`}return o}function Aa(e,A=!1,t=!1){let r=A?Ai:Ar;function i(e){for(let A=0;A<64;A++)if(r.charAt(A)===e)return A;return 64}function n(e){return 64===e?0:e}let a=0,o="";for(;a<e.length;){let A=i(e.charAt(a++)),t=a>=e.length?0:i(e.charAt(a++)),r=a>=e.length?0:i(e.charAt(a++)),s=a>=e.length?0:i(e.charAt(a++)),l=n(A)<<2|n(t)>>4,d=(15&n(t))<<4|n(r)>>2,u=(3&n(r))<<6|n(s);o+=String.fromCharCode(l),64!==r&&(o+=String.fromCharCode(d)),64!==s&&(o+=String.fromCharCode(u))}if(t){let e=o.length,A=-1;for(let t=e-1;t>=0;t--)if(0!==o.charCodeAt(t)){A=t;break}o=-1!==A?o.slice(0,A+1):""}return o}function Ao(e){let A="";for(let t of new Uint8Array(e))A+=String.fromCharCode(t);return A}function As(e){let A=e.length,t=new ArrayBuffer(A),r=new Uint8Array(t);for(let t=0;t<A;t++)r[t]=e.charCodeAt(t);return t}let Al=Math.log(2);function Ad(e,A){for(let t of A)delete e[t]}function Au(){if("u"<typeof BigInt)throw Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Ac(e){let A=0,t=0;for(let t=0;t<e.length;t++)A+=e[t].byteLength;let r=new Uint8Array(A);for(let A=0;A<e.length;A++){let i=e[A];r.set(new Uint8Array(i),t),t+=i.byteLength}return r.buffer}function Ah(e,A,t,r){return A instanceof Uint8Array?A.byteLength?t<0?(e.error="Wrong parameter: inputOffset less than zero",!1):r<0?(e.error="Wrong parameter: inputLength less than zero",!1):!(A.byteLength-t-r<0)||(e.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):(e.error="Wrong parameter: inputBuffer has zero length",!1):(e.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}class Ag{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Ac(this.items)}}let Ap=[new Uint8Array([1])],AC="0123456789",Af="name",AI="valueHexView",Aw=new ArrayBuffer(0),Am=new Uint8Array(0),AE="EndOfContent",Ay="OCTET STRING",AB="BIT STRING";function AQ(e){var A;return(A=class extends e{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(e){this.valueHexView=new Uint8Array(e)}constructor(...e){var A;super(...e);const t=e[0]||{};this.isHexOnly=null!=(A=t.isHexOnly)&&A,this.valueHexView=t.valueHex?eV.toUint8Array(t.valueHex):Am}fromBER(e,A,t,r){let i=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!Ah(this,i,A,t))return -1;let n=A+t;return(this.valueHexView=i.subarray(A,n),this.valueHexView.length)?(this.blockLength=t,n):(this.warnings.push("Zero buffer length"),A)}toBER(e=!1){return this.isHexOnly?e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",Aw)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:e4.ToHex(this.valueHexView)}}}).NAME="hexBlock",A}class AD{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:A="",warnings:t=[],valueBeforeDecode:r=Am}={}){this.blockLength=e,this.error=A,this.warnings=t,this.valueBeforeDecodeView=eV.toUint8Array(r)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:e4.ToHex(this.valueBeforeDecodeView)}}}AD.NAME="baseBlock";class Ab extends AD{fromBER(e,A,t,r){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,A){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}}Ab.NAME="valueBlock";class AS extends AQ(AD){constructor({idBlock:e={}}={}){var A,t,r,i;super(),e?(this.isHexOnly=null!=(A=e.isHexOnly)&&A,this.valueHexView=e.valueHex?eV.toUint8Array(e.valueHex):Am,this.tagClass=null!=(t=e.tagClass)?t:-1,this.tagNumber=null!=(r=e.tagNumber)?r:-1,this.isConstructed=null!=(i=e.isConstructed)&&i):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let A=0;switch(this.tagClass){case 1:A|=0;break;case 2:A|=64;break;case 3:A|=128;break;case 4:A|=192;break;default:return this.error="Unknown tag class",Aw}if(this.isConstructed&&(A|=32),this.tagNumber<31&&!this.isHexOnly){let t=new Uint8Array(1);if(!e){let e=this.tagNumber;e&=31,A|=e,t[0]=A}return t.buffer}if(!this.isHexOnly){let t=e5(this.tagNumber,7),r=new Uint8Array(t),i=t.byteLength,n=new Uint8Array(i+1);if(n[0]=31|A,!e){for(let e=0;e<i-1;e++)n[e+1]=128|r[e];n[i]=r[i-1]}return n.buffer}let t=new Uint8Array(this.valueHexView.byteLength+1);if(t[0]=31|A,!e){let e=this.valueHexView;for(let A=0;A<e.length-1;A++)t[A+1]=128|e[A];t[this.valueHexView.byteLength]=e[e.length-1]}return t.buffer}fromBER(e,A,t){let r=eV.toUint8Array(e);if(!Ah(this,r,A,t))return -1;let i=r.subarray(A,A+t);if(0===i.length)return this.error="Zero buffer length",-1;switch(192&i[0]){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(32&i[0])==32,this.isHexOnly=!1;let n=31&i[0];if(31!==n)this.tagNumber=n,this.blockLength=1;else{let e=0;for(;;){let A=e+1;if(A>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(e++,(128&i[A])==0)break}this.blockLength=e+1;let A=this.valueHexView=new Uint8Array(e);for(let t=0;t<e;t++)A[t]=127&i[t+1];this.blockLength<=9?this.tagNumber=e3(A,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(1===this.tagClass&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return A+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}}AS.NAME="identificationBlock";class Ak extends AD{constructor({lenBlock:e={}}={}){var A,t,r;super(),this.isIndefiniteForm=null!=(A=e.isIndefiniteForm)&&A,this.longFormUsed=null!=(t=e.longFormUsed)&&t,this.length=null!=(r=e.length)?r:0}fromBER(e,A,t){let r=eV.toUint8Array(e);if(!Ah(this,r,A,t))return -1;let i=r.subarray(A,A+t);if(0===i.length)return this.error="Zero buffer length",-1;if(255===i[0])return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=128===i[0],this.isIndefiniteForm)return this.blockLength=1,A+this.blockLength;if(this.longFormUsed=!!(128&i[0]),!1===this.longFormUsed)return this.length=i[0],this.blockLength=1,A+this.blockLength;let n=127&i[0];if(n>8)return this.error="Too big integer",-1;if(n+1>i.length)return this.error="End of input reached before message was fully decoded",-1;let a=A+1,o=r.subarray(a,a+n);return 0===o[n-1]&&this.warnings.push("Needlessly long encoded length"),this.length=e3(o,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=n+1,A+this.blockLength}toBER(e=!1){let A,t;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return A=new ArrayBuffer(1),!1===e&&((t=new Uint8Array(A))[0]=128),A;if(this.longFormUsed){let r=e5(this.length,8);if(r.byteLength>127)return this.error="Too big length",Aw;if(A=new ArrayBuffer(r.byteLength+1),e)return A;let i=new Uint8Array(r);(t=new Uint8Array(A))[0]=128|r.byteLength;for(let e=0;e<r.byteLength;e++)t[e+1]=i[e];return A}return A=new ArrayBuffer(1),!1===e&&((t=new Uint8Array(A))[0]=this.length),A}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}}Ak.NAME="lengthBlock";let AR={};class Av extends AD{constructor({name:e="",optional:A=!1,primitiveSchema:t,...r}={},i){super(r),this.name=e,this.optional=A,t&&(this.primitiveSchema=t),this.idBlock=new AS(r),this.lenBlock=new Ak(r),this.valueBlock=i?new i(r):new Ab(r)}fromBER(e,A,t,r){let i=this.valueBlock.fromBER(e,A,this.lenBlock.isIndefiniteForm?t:this.lenBlock.length,r);return -1===i?this.error=this.valueBlock.error:(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength)),i}toBER(e,A){let t=A||new Ag;A||function e(A){var t;if(A instanceof AR.Constructed)for(let t of A.valueBlock.value)e(t)&&(A.lenBlock.isIndefiniteForm=!0);return!!(null==(t=A.lenBlock)?void 0:t.isIndefiniteForm)}(this);let r=this.idBlock.toBER(e);if(t.write(r),this.lenBlock.isIndefiniteForm)t.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,t),t.write(new ArrayBuffer(2));else{let A=this.valueBlock.toBER(e);this.lenBlock.length=A.byteLength;let r=this.lenBlock.toBER(e);t.write(r),t.write(A)}return A?Aw:t.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return"ascii"===e?this.onAsciiEncoding():e4.ToHex(this.toBER())}onAsciiEncoding(){let e=this.constructor.NAME,A=e4.ToHex(this.valueBlock.valueBeforeDecodeView);return`${e} : ${A}`}isEqual(e){return this===e||e instanceof this.constructor&&AA(this.toBER(),e.toBER())}}Av.NAME="BaseBlock";class AG extends Av{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e="",...A}={},t){super(A,t),e&&this.fromString(e)}fromBER(e,A,t){let r=this.valueBlock.fromBER(e,A,this.lenBlock.isIndefiniteForm?t:this.lenBlock.length);return -1===r?this.error=this.valueBlock.error:(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength)),r}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}}AG.NAME="BaseStringBlock";class AT extends AQ(Ab){constructor({isHexOnly:e=!0,...A}={}){super(A),this.isHexOnly=e}}AT.NAME="PrimitiveValueBlock";class AM extends Av{constructor(e={}){super(e,AT),this.idBlock.isConstructed=!1}}function AN(e={}){var A,t,r;return{depth:0,maxDepth:null!=(A=e.maxDepth)?A:100,nodesCount:0,maxNodes:null!=(t=e.maxNodes)?t:1e4,maxContentLength:null!=(r=e.maxContentLength)?r:0x1000000}}function AO(e,A,t,r){let i=r.depth+1;if(i>r.maxDepth){let e;return(e=new Av({},Ab)).error="Maximum ASN.1 nesting depth exceeded",{offset:-1,result:e}}r.depth=i;try{return AH(e,A,t,r)}finally{r.depth-=1}}function AH(e,A=0,t=e.length,r=AN()){let i=A,n=new Av({},Ab),a=new AD;if(!Ah(a,e,A,t))return n.error=a.error,{offset:-1,result:n};if(!e.subarray(A,A+t).length)return n.error="Zero buffer length",{offset:-1,result:n};let o=function(e){if(e.nodesCount+=1,e.nodesCount>e.maxNodes)return"Maximum ASN.1 node count exceeded"}(r);if(o)return n.error=o,{offset:-1,result:n};let s=n.idBlock.fromBER(e,A,t);if(n.idBlock.warnings.length&&n.warnings.concat(n.idBlock.warnings),-1===s)return n.error=n.idBlock.error,{offset:-1,result:n};if(A=s,t-=n.idBlock.blockLength,s=n.lenBlock.fromBER(e,A,t),n.lenBlock.warnings.length&&n.warnings.concat(n.lenBlock.warnings),-1===s)return n.error=n.lenBlock.error,{offset:-1,result:n};A=s,t-=n.lenBlock.blockLength;let l=n.lenBlock.isIndefiniteForm?t:n.lenBlock.length,d=function(e,A){if(e>A.maxContentLength)return"Maximum ASN.1 content length exceeded"}(l,r);if(d)return n.error=d,{offset:-1,result:n};if(!n.idBlock.isConstructed&&n.lenBlock.isIndefiniteForm)return n.error="Indefinite length form used for primitive encoding form",{offset:-1,result:n};let u=Av;if(1===n.idBlock.tagClass){if(n.idBlock.tagNumber>=37&&!1===n.idBlock.isHexOnly)return n.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:n};switch(n.idBlock.tagNumber){case 0:if(n.idBlock.isConstructed&&n.lenBlock.length>0)return n.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:n};u=AR.EndOfContent;break;case 1:u=AR.Boolean;break;case 2:u=AR.Integer;break;case 3:u=AR.BitString;break;case 4:u=AR.OctetString;break;case 5:u=AR.Null;break;case 6:u=AR.ObjectIdentifier;break;case 10:u=AR.Enumerated;break;case 12:u=AR.Utf8String;break;case 13:u=AR.RelativeObjectIdentifier;break;case 14:u=AR.TIME;break;case 15:return n.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:n};case 16:u=AR.Sequence;break;case 17:u=AR.Set;break;case 18:u=AR.NumericString;break;case 19:u=AR.PrintableString;break;case 20:u=AR.TeletexString;break;case 21:u=AR.VideotexString;break;case 22:u=AR.IA5String;break;case 23:u=AR.UTCTime;break;case 24:u=AR.GeneralizedTime;break;case 25:u=AR.GraphicString;break;case 26:u=AR.VisibleString;break;case 27:u=AR.GeneralString;break;case 28:u=AR.UniversalString;break;case 29:u=AR.CharacterString;break;case 30:u=AR.BmpString;break;case 31:u=AR.DATE;break;case 32:u=AR.TimeOfDay;break;case 33:u=AR.DateTime;break;case 34:u=AR.Duration;break;default:{let e=n.idBlock.isConstructed?new AR.Constructed:new AR.Primitive;e.idBlock=n.idBlock,e.lenBlock=n.lenBlock,e.warnings=n.warnings,n=e}}}else u=n.idBlock.isConstructed?AR.Constructed:AR.Primitive;return s=(n=function(e,A){if(e instanceof A)return e;let t=new A;return t.idBlock=e.idBlock,t.lenBlock=e.lenBlock,t.warnings=e.warnings,t.valueBeforeDecodeView=e.valueBeforeDecodeView,t}(n,u)).fromBER(e,A,l,r),n.valueBeforeDecodeView=e.subarray(i,i+n.blockLength),{offset:s,result:n}}function AU(e,A={}){if(!e.byteLength){let e=new Av({},Ab);return e.error="Input buffer has zero length",{offset:-1,result:e}}return AH(eV.toUint8Array(e).slice(),0,e.byteLength,AN(A))}AR.Primitive=AM,AM.NAME="PRIMITIVE";class A_ extends Ab{constructor({value:e=[],isIndefiniteForm:A=!1,...t}={}){super(t),this.value=e,this.isIndefiniteForm=A}fromBER(e,A,t,r){var i,n;let a=eV.toUint8Array(e),o=null!=r?r:AN();if(!Ah(this,a,A,t))return -1;if(this.valueBeforeDecodeView=a.subarray(A,A+t),0===this.valueBeforeDecodeView.length)return this.warnings.push("Zero buffer length"),A;let s=A;for(;i=this.isIndefiniteForm,n=t,(i?1:n)>0;){let e=AO(a,s,t,o);if(-1===e.offset)return this.error=e.result.error,this.warnings.concat(e.result.warnings),-1;if(s=e.offset,this.blockLength+=e.result.blockLength,t-=e.result.blockLength,this.value.push(e.result),this.isIndefiniteForm&&e.result.constructor.NAME===AE)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===AE?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,A){let t=A||new Ag;for(let A=0;A<this.value.length;A++)this.value[A].toBER(e,t);return A?Aw:t.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let A of this.value)e.value.push(A.toJSON());return e}}A_.NAME="ConstructedValueBlock";class Ax extends Av{constructor(e={}){super(e,A_),this.idBlock.isConstructed=!0}fromBER(e,A,t,r){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let i=this.valueBlock.fromBER(e,A,this.lenBlock.isIndefiniteForm?t:this.lenBlock.length,r);return -1===i?this.error=this.valueBlock.error:(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength)),i}onAsciiEncoding(){let e=[];for(let A of this.valueBlock.value)e.push(A.toString("ascii").split("\n").map(e=>` ${e}`).join("\n"));let A=3===this.idBlock.tagClass?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${A} :
996
+ `)}}(A={...A,secret:r,baseURL:u?A.baseURL:c?new URL(c).origin:"",basePath:A.basePath||"/api/auth",plugins:s.concat(l)},d);let w=A.advanced?.ipAddress?.trustedProxies;if(w&&w.length>0){let e=w.filter(e=>null===Q(e));e.length>0&&d.warn(`Ignoring invalid \`advanced.ipAddress.trustedProxies\` entries: ${e.join(", ")}. Each entry must be an IP address or CIDR range.`)}let m=(0,An.getCookies)(A),E=(0,eT.getAuthTables)(A),y=(await Promise.all(Object.entries(A.socialProviders||{}).map(async([e,A])=>{let t="function"==typeof A?await A():A;if(null==t||!1===t.enabled)return null;t.clientId||d.warn(`Social provider ${e} is missing clientId or clientSecret`);let r=iD[e](t);return r.disableImplicitSignUp=t.disableImplicitSignUp,r}))).filter(e=>null!==e),B=({model:e,size:t})=>{if("function"==typeof A.advanced?.generateId)return A.advanced.generateId({model:e,size:t});let r=A?.advanced?.database?.generateId;return"function"==typeof r?r({model:e,size:t}):"uuid"===r?crypto.randomUUID():"serial"!==r&&!1!==r&&(0,N.generateId)(t)},{publish:D}=await nO(A,{adapter:e.id,database:"function"==typeof A.database?"adapter":t(A.database)}),b=new Set(A.plugins.map(e=>e.id)),S=await AM(A),k=await AU(A),v={appName:A.appName||"Better Auth",baseURL:c||"",version:(0,nc.getBetterAuthVersion)(),socialProviders:y,options:A,oauthConfig:{storeStateStrategy:A.account?.storeStateStrategy||(o?"database":"cookie"),skipStateCookieCheck:!!A.account?.skipStateCookieCheck},tables:E,trustedOrigins:S,trustedProviders:k,isTrustedOrigin(e,A){return this.trustedOrigins.some(t=>e5(e,t,A))},sessionConfig:{updateAge:A.session?.updateAge!==void 0?A.session.updateAge:86400,expiresIn:A.session?.expiresIn||604800,freshAge:A.session?.freshAge===void 0?86400:A.session.freshAge,cookieRefreshCache:(n=A.session?.cookieCache?.refreshCache,a=A.session?.cookieCache?.maxAge||300,o&&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:{...A.rateLimit,enabled:A.rateLimit?.enabled??p.isProduction,window:A.rateLimit?.window||10,max:A.rateLimit?.max||100,storage:A.rateLimit?.storage||(A.secondaryStorage?"secondary-storage":"memory")},authCookies:m,logger:d,generateId:B,session:null,secondaryStorage:A.secondaryStorage,password:{hash:A.emailAndPassword?.password?.hash||At,verify:A.emailAndPassword?.password?.verify||Ai,config:{minPasswordLength:A.emailAndPassword?.minPasswordLength||8,maxPasswordLength:A.emailAndPassword?.maxPasswordLength||128},checkPassword:AL},setNewSession(e){this.newSession=e},newSession:null,adapter:e,internalAdapter:Ay(e,{options:A,logger:d,hooks:A.databaseHooks?[{source:"user",hooks:A.databaseHooks}]:[],generateId:B}),createAuthCookie:(0,An.createCookieGetter)(A),async runMigrations(){throw new R.BetterAuthError("runMigrations will be set by the specific init implementation")},publishTelemetry:D,skipCSRFCheck:!!A.advanced?.disableCSRFCheck,skipOriginCheck:A.advanced?.disableOriginCheck!==void 0?A.advanced.disableOriginCheck:!!(0,p.isTest)(),runInBackground:A.advanced?.backgroundTasks?.handler??(e=>{e.catch(()=>{})}),async runInBackgroundOrAwait(e){try{A.advanced?.backgroundTasks?.handler?e instanceof Promise&&A.advanced.backgroundTasks.handler(e.catch(e=>{d.error("Failed to run background task:",e)})):await e}catch(e){d.error("Failed to run background task:",e)}},getPlugin:e=>A.plugins.find(A=>A.id===e)??null,hasPlugin:e=>b.has(e)},G=AT(v);return(0,e7.isPromise)(G)&&await G,v}let nU=async e=>{let A=await eO(e),t=await nH(A,e,e=>(0,eU.getKyselyDatabaseType)(e)||"unknown");return t.runMigrations=async function(){if(!e.database||"updateMany"in e.database)throw new R.BetterAuthError("Database is not provided or it's an adapter. Migrations are only supported with a database instance.");let{runMigrations:A}=await e0(e);await A()},t};var n_=e.i(779198),nx=e.i(595544);let nL=()=>n??=e.A(162916).catch(e=>{throw n=void 0,e}),nP=(0,_.createAccessControl)({user:["create","list","set-role","ban","impersonate","impersonate-admins","delete","set-password","set-email","get","update"],session:["list","revoke","delete"]}),nq={admin:nP.newRole({user:["create","list","set-role","ban","impersonate","delete","set-password","set-email","get","update"],session:["list","revoke","delete"]}),user:nP.newRole({user:[],session:[]})},nK=(0,c.defineErrorCodes)({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",PASSWORD_CANNOT_BE_UPDATED_VIA_UPDATE_USER:"Password cannot be updated through update-user. Use the set-user-password endpoint instead"}),nJ=async e=>{let A=e.context.returned;return A?A instanceof Response?200!==A.status?null:await A.clone().json():(0,AP.isAPIError)(A)?null:A:null},nF=e=>{if(e.userId&&e.options?.adminUserIds?.includes(e.userId))return!0;if(!e.permissions)return!1;let A=(e.role||e.options?.defaultRole||"user").split(","),t=e.options?.roles||nq;for(let r of A)if(t[r]?.authorize(e.permissions)?.success)return!0;return!1};var nj=e.i(752067);let nz=(0,g.createAuthMiddleware)(async e=>{let A=await (0,v.getAuthoritativeSessionFromCtx)(e);if(!A)throw R.APIError.fromStatus("UNAUTHORIZED");return{session:A}});function nY(e){return Array.isArray(e)?e.join(","):e}let nZ=C.object({userId:H.coerce.string().meta({description:"The user id"}),role:C.union([C.string().meta({description:"The role to set. `admin` or `user` by default"}),C.array(C.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]`"})}),nV=C.object({id:C.string().meta({description:"The id of the User"})}),nW=C.object({email:C.string().meta({description:"The email of the user"}),password:C.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:C.string().meta({description:"The name of the user"}),role:C.union([C.string().meta({description:"The role of the user"}),C.array(C.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:C.record(C.string(),C.any()).optional().meta({description:"Extra fields for the user. Including custom additional fields."})}),n$=C.object({userId:H.coerce.string().meta({description:"The user id"}),data:C.record(C.any(),C.any()).meta({description:"The user data to update"})}),nX=C.object({searchValue:C.string().optional().meta({description:'The value to search for. Eg: "some name"'}),searchField:C.enum(["email","name"]).meta({description:'The field to search in, defaults to email. Can be `email` or `name`. Eg: "name"'}).optional(),searchOperator:C.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:C.string().meta({description:"The number of users to return"}).or(C.number()).optional(),offset:C.string().meta({description:"The offset to start from"}).or(C.number()).optional(),sortBy:C.string().meta({description:"The field to sort by"}).optional(),sortDirection:C.enum(["asc","desc"]).meta({description:"The direction to sort by"}).optional(),filterField:C.string().meta({description:"The field to filter by"}).optional(),filterValue:C.string().meta({description:"The value to filter by"}).or(C.number()).or(C.boolean()).or(C.array(C.string())).or(C.array(C.number())).optional(),filterOperator:C.enum(nj.whereOperators).meta({description:"The operator to use for the filter"}).optional()}),n0=C.object({userId:H.coerce.string().meta({description:"The user id"})}),n1=C.object({userId:H.coerce.string().meta({description:"The user id"})}),n8=C.object({userId:H.coerce.string().meta({description:"The user id"}),banReason:C.string().meta({description:"The reason for the ban"}).optional(),banExpiresIn:C.number().meta({description:"The number of seconds until the ban expires"}).optional()}),n4=C.object({userId:H.coerce.string().meta({description:"The user id"})}),n2=C.object({sessionToken:C.string().meta({description:"The session token"})}),n6=C.object({userId:H.coerce.string().meta({description:"The user id"})}),n3=C.object({userId:H.coerce.string().meta({description:"The user id"})}),n5=C.object({newPassword:C.string().nonempty("newPassword cannot be empty").meta({description:"The new password"}),userId:H.coerce.string().nonempty("userId cannot be empty").meta({description:"The user id"})}),n9=C.object({userId:H.coerce.string().optional().meta({description:'The user id. Eg: "user-id"'}),role:C.string().optional().meta({description:'The role to check permission for. Eg: "admin"'})}).and(C.xor([C.object({permission:C.record(C.string(),C.array(C.string()))}),C.object({permissions:C.record(C.string(),C.array(C.string()))})])),n7={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 ae=e.i(259968),aA=e.i(976394);function at(e){try{return decodeURIComponent(e)}catch{return e}}let ar=(0,c.defineErrorCodes)({INVALID_OAUTH_CONFIGURATION:"Invalid OAuth configuration",TOKEN_URL_NOT_FOUND:"Invalid OAuth configuration. Token URL not found."});async function ai(e,A){let t=await rJ(e,{method:"GET",headers:A});if(t.error||!t.data)return null;if(t.data.issuer)try{new URL(t.data.issuer)}catch{return null}return t.data}async function an(e,A){if(e.idToken)try{let A=ic(e.idToken);if(A?.sub&&A?.email)return{id:A.sub,emailVerified:A.email_verified,image:A.picture,...A}}catch{}if(!A)return null;let t=await rJ(A,{method:"GET",headers:{Authorization:`Bearer ${e.accessToken}`}});return t.error||!t.data?null:{...t.data,email:t.data.email,emailVerified:t.data.email_verified??!1,image:t.data.picture,name:t.data.name}}let aa=async e=>{let A=await (0,k.createHash)("SHA-256").digest(new TextEncoder().encode(e));return S.base64Url.encode(new Uint8Array(A),{padding:!1})},ao=C.object({token:C.string().meta({description:'The token to verify. Eg: "some-token"'})});var as=e.i(270133),al=e.i(135475),ad=e.i(768843);function au(e,A){return e[A]?.trim()||void 0}function ac(e,A){let t=au(e,A);if(!t)throw Error(`${A} is required for AUTH_MODE.`);return t}function ah(e=process.env){let A=function(e){let A=au(e,"AUTH_MODE")??"password";if("password"!==A&&"oidc"!==A&&"both"!==A)throw Error('AUTH_MODE must be "password", "oidc", or "both".');return A}(e),t=(0,as.resolveAppOrigins)(e);return{secret:(0,ad.getAppSecrets)(e).authSecret,origins:t,baseURL:t.canonical,trustProxyHeaders:function(e){let A=au(e,"TRUST_PROXY_HEADERS")?.toLowerCase();if(!A||"false"===A||"0"===A)return!1;if("true"===A||"1"===A)return!0;throw Error("TRUST_PROXY_HEADERS must be true, false, 1, or 0.")}(e),mode:A,provider:function(e,A){if("password"===A)return null;let t=au(e,"AUTH_OAUTH_DISCOVERY_URL"),r=au(e,"AUTH_OAUTH_AUTHORIZATION_URL"),i=au(e,"AUTH_OAUTH_TOKEN_URL"),n=au(e,"AUTH_OAUTH_USER_INFO_URL"),a=au(e,"AUTH_OAUTH_ISSUER"),o=!!(r||i||n),s=r&&i&&n;if(t&&o)throw Error("OIDC configuration must use either discovery or explicit endpoints, not both.");if(!t&&!s)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(o&&!s)throw Error("Explicit OAuth configuration must include authorization, token, and user-info URLs.");if(s&&!a)throw Error("AUTH_OAUTH_ISSUER is required with explicit OAuth endpoints.");let l=ac(e,"AUTH_OAUTH_SCOPES").split(",").map(e=>e.trim()).filter(Boolean);if(0===l.length)throw Error("AUTH_OAUTH_SCOPES must contain at least one scope.");return{providerId:ac(e,"AUTH_OAUTH_PROVIDER_ID"),displayName:ac(e,"AUTH_OAUTH_PROVIDER_NAME"),clientId:ac(e,"AUTH_OAUTH_CLIENT_ID"),clientSecret:ac(e,"AUTH_OAUTH_CLIENT_SECRET"),scopes:l,requireIssuerValidation:function(e){let A=au(e,"AUTH_OAUTH_REQUIRE_ISSUER_VALIDATION")?.toLowerCase();if(!A||"false"===A||"0"===A)return!1;if("true"===A||"1"===A)return!0;throw Error("AUTH_OAUTH_REQUIRE_ISSUER_VALIDATION must be true, false, 1, or 0.")}(e),discoveryUrl:t,issuer:a,authorizationUrl:r,tokenUrl:i,userInfoUrl:n}}(e,A)}}function ag(e){return"password"===e||"both"===e}function ap(e){return"oidc"===e||"both"===e}e.s(["getAuthRuntimeConfig",0,ah,"oauthAuthenticationEnabled",0,ap,"passwordAuthenticationEnabled",0,ag],658978);var aC=e.i(812057);let af=RegExp(String.raw`((?:"?(?:authorization|password|accessToken|refreshToken|idToken|sessionToken|clientSecret|secret|privateKey)"?)\s*:\s*)(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^,\n}\]]+)`,"gi");function aI(e){return e.replace(af,'$1"[REDACTED]"')}function aw(e,A,...t){let r=[`${new Date().toISOString()} ${e.toUpperCase()} [Better Auth]: ${A}`,...t.map(e=>"string"==typeof e?e:(0,aC.inspect)(e,{depth:6,breakLength:120}))].map(aI);"error"===e?console.error(...r):"warn"===e?console.warn(...r):console.log(...r)}function am(e){return"string"==typeof e&&e.length>0?e:void 0}async function aE(e,A){try{return await fetch(e,{headers:{Accept:"application/vnd.github+json",Authorization:`Bearer ${A}`,"User-Agent":"AI-Development-Environment"}})}catch{return null}}async function ay(e,A){let t,r=await aE(e,A);if(!r?.ok)return null;let i=await r.json(),n=am(i.email),a=await aE(((t=new URL(e)).pathname=`${t.pathname.replace(/\/$/,"")}/emails`,t.toString()),A),o=a?.ok?await a.json():[],s=Array.isArray(o)?o:[],l=s.find(e=>!0===e.primary)??s[0],d=n??am(l?.email),u=s.find(e=>am(e.email)===d);return{...i,email:d,emailVerified:u?.verified===!0,image:am(i.avatar_url),name:am(i.name)??am(i.login)??""}}let aB="default";async function aQ(){let e=await (0,al.getPrismaClient)();return await e.authSettings.findUnique({where:{id:aB}})??await e.authSettings.upsert({where:{id:aB},create:{id:aB},update:{}})}async function aD({allowWhenRegistrationClosed:e=!1}={}){let A=await (0,al.getPrismaClient)(),t=await aQ();if(t.bootstrapCompleted){if(!t.registrationEnabled&&!e)throw new R.APIError("FORBIDDEN",{message:"Account registration is disabled."});return}if(await A.user.count()>0){if(await A.authSettings.update({where:{id:aB},data:{bootstrapCompleted:!0,registrationEnabled:!1,bootstrapClaimId:null,bootstrapClaimedAt:null}}),e)return;throw new R.APIError("FORBIDDEN",{message:"Account registration is disabled."})}let r=new Date(Date.now()-18e4),i=(0,Ae.randomUUID)();if(1!==(await A.authSettings.updateMany({where:{id:aB,bootstrapCompleted:!1,OR:[{bootstrapClaimedAt:null},{bootstrapClaimedAt:{lt:r}}]},data:{bootstrapClaimId:i,bootstrapClaimedAt:new Date}})).count)throw new R.APIError("CONFLICT",{message:"The initial account is already being created. Try again shortly."})}async function ab(){let e=await (0,al.getPrismaClient)();await e.authSettings.updateMany({where:{id:aB,bootstrapCompleted:!1},data:{bootstrapCompleted:!0,registrationEnabled:!1,bootstrapClaimId:null,bootstrapClaimedAt:null}})}let aS={user:{create:{before:async(e,A)=>(await aD({allowWhenRegistrationClosed:A?.path?.includes("/admin/create-user")??!1}),{data:{...e,role:"user",banned:!1,banReason:null,banExpires:null}}),after:async()=>{await ab()}},update:{before:async e=>({data:{...e,role:"user",banned:!1,banReason:null,banExpires:null}})},delete:{before:async()=>{throw new R.APIError("BAD_REQUEST",{message:"Accounts must be deleted through the management API."})}}}};e.s(["authDatabaseHooks",0,aS],525796);let ak={user:["create","list","set-password","set-email","get","update"],session:["list","revoke","delete"]},aR=(0,_.createAccessControl)(ak),av=aR.newRole(ak),aG=null;function aT(){return aG||(aG=(0,al.getPrismaClient)().then(e=>(function(e,A=ah()){var t;let r,i,n,a,o,s=A.provider,l=s?.providerId.toLowerCase()==="github"?s.userInfoUrl:void 0,d=ap(A.mode)&&s?(e=>{let A=new Set,t=new Set;for(let r of e.config){let e=r.providerId;A.has(e)&&t.add(e),A.add(e)}return t.size>0&&console.warn(`Duplicate provider IDs found: ${Array.from(t).join(", ")}`),{id:"generic-oauth",version:nx.PACKAGE_VERSION,init:async A=>{let t=[];for(let r of e.config){let e,i,n=r.authorizationUrl,a=r.tokenUrl,o=r.userInfoUrl,s=r.endSessionEndpoint,l=!1;if(r.discoveryUrl){let t=await ai(r.discoveryUrl,r.discoveryHeaders).catch(e=>(A.logger.error(`Discovery fetch failed for "${r.providerId}": ${e}`),null));if(t){if(!t.issuer&&!r.accountIssuer)throw Error(`Provider "${r.providerId}": discovery did not return an issuer. Configure accountIssuer explicitly to establish a stable account namespace.`);n??=t.authorization_endpoint,a??=t.token_endpoint,o??=t.userinfo_endpoint,s??=t.end_session_endpoint,e=t.issuer;let A=t.id_token_signing_alg_values_supported;if(l=Array.isArray(A)&&A.length>0,t.jwks_uri&&t.issuer){let e;try{e=new URL(t.jwks_uri,r.discoveryUrl)}catch{throw Error(`Provider "${r.providerId}": invalid jwks_uri "${t.jwks_uri}" in discovery document.`)}i={jwks:io(e),issuer:t.issuer,audience:r.clientId,algorithms:l?A:void 0}}}else if(r.accountIssuer)n&&a||A.logger.error(`Provider "${r.providerId}": discovery returned no data and no explicit endpoints configured. OAuth sign-in will fail for this provider.`);else throw Error(`Provider "${r.providerId}": discovery returned no valid data. Provider initialization stopped to keep its account issuer stable.`)}if(r.requireIdTokenVerification&&!i)throw Error(`Provider "${r.providerId}": requires verified ID tokens, but discovery did not provide a usable issuer and jwks_uri.`);let d=r.tokenEndpointAuth;if(r.clientSecret&&(d?.method==="private_key_jwt"||d?.method==="none"))throw Error(`Provider "${r.providerId}": tokenEndpointAuth.method "${d?.method}" cannot be combined with clientSecret`);if(!r.clientSecret&&(d?.method==="client_secret_basic"||d?.method==="client_secret_post"))throw Error(`Provider "${r.providerId}": tokenEndpointAuth.method "${d?.method}" requires clientSecret`);if(!r.clientSecret&&!d&&"basic"===r.authentication)throw Error(`Provider "${r.providerId}": authentication "basic" requires clientSecret`);let u=r.accountSubject,c=r.accountIssuer,h={id:r.providerId,name:r.name??r.providerId,issuer:e,accountSubject:({tokens:e,profile:A})=>u?u({tokens:e,profile:A}):l?A.sub??"":A.id??"",accountIssuer:"function"==typeof c?({tokens:e,profile:A})=>c({tokens:e,profile:A}):c??e,idToken:i,requiresIdTokenNonce:void 0!==i&&!0!==r.disableIdTokenNonceBinding,allowIdpInitiated:r.allowIdpInitiated,async createEndSessionURL(e){let t;if(r.disableProviderLogout||!s)return null;try{t=new URL(s)}catch{return null}e.idToken&&t.searchParams.set("id_token_hint",e.idToken);let i=e.postLogoutRedirectURI??r.postLogoutRedirectURI,n=i?new URL(i,A.baseURL).toString():void 0;return n?(t.searchParams.set("post_logout_redirect_uri",n),t.searchParams.set("client_id",r.clientId),e.state&&t.searchParams.set("state",e.state)):e.idToken||t.searchParams.set("client_id",r.clientId),t},createAuthorizationURL(e){if(!n)throw R.APIError.from("BAD_REQUEST",ar.INVALID_OAUTH_CONFIGURATION);return rC({id:r.providerId,options:{clientId:r.clientId,clientSecret:r.clientSecret,redirectURI:r.redirectURI},authorizationEndpoint:n,state:e.state,codeVerifier:r.pkce??!0?e.codeVerifier:void 0,scopes:(()=>{let A=[...e.scopes??[],...r.scopes??[]];return l&&!A.includes("openid")&&A.unshift("openid"),A})(),redirectURI:e.redirectURI,prompt:r.prompt,accessType:r.accessType,responseType:r.responseType,responseMode:r.responseMode,nonce:e.idTokenNonce,additionalParams:{...r.authorizationUrlParams??{},...e.additionalParams??{}},loginHint:e.loginHint})},async validateAuthorizationCode(e){if(r.getToken)return ru(await r.getToken(e),r.accessTokenExpiresIn);if(!a)throw R.APIError.from("BAD_REQUEST",ar.TOKEN_URL_NOT_FOUND);return ru(await il({headers:r.authorizationHeaders,code:e.code,codeVerifier:r.pkce??!0?e.codeVerifier:void 0,redirectURI:e.redirectURI,options:{clientId:r.clientId,clientSecret:r.clientSecret,redirectURI:r.redirectURI},tokenEndpoint:a,authentication:r.authentication,tokenEndpointAuth:d,additionalParams:r.tokenUrlParams}),r.accessTokenExpiresIn)},async getUserInfo(e){let{expectedIdTokenNonce:t,...i}=e;if(i.idToken&&h.idToken&&!await ry(h,i.idToken,t))return A.logger.error(`Provider "${r.providerId}": id_token failed verification against the discovery JWKS or expected nonce`),null;let n=r.getUserInfo?await r.getUserInfo(i):await an(i,o);if(!n)return null;let a=r.mapProfileToUser?await r.mapProfileToUser(n):{},s={email:n.email,emailVerified:n.emailVerified,image:n.image,name:n.name,...a};return{user:{...s,image:s.image??void 0},data:n}},async refreshAccessToken(e,A){if(!a)throw R.APIError.from("BAD_REQUEST",ar.TOKEN_URL_NOT_FOUND);let t="function"==typeof r.refreshTokenParams?await r.refreshTokenParams(A):r.refreshTokenParams;return ru(await r6({refreshToken:e,options:{clientId:r.clientId,clientSecret:r.clientSecret},authentication:r.authentication,tokenEndpointAuth:d,tokenEndpoint:a,extraParams:t}),r.accessTokenExpiresIn)},disableImplicitSignUp:r.disableImplicitSignUp,disableSignUp:r.disableSignUp,options:{disableSignUp:r.disableSignUp,overrideUserInfoOnSignIn:r.overrideUserInfo,requireEmailVerification:r.requireEmailVerification}};t.push(h)}let r=new Set(A.socialProviders.map(e=>e.id));for(let e of t)r.has(e.id)&&A.logger.warn(`Generic OAuth provider "${e.id}" shadows a built-in social provider with the same ID`);return{context:{socialProviders:t.concat(A.socialProviders)}}},options:e,$ERROR_CODES:ar}})({config:[{providerId:s.providerId,clientId:s.clientId,clientSecret:s.clientSecret,scopes:s.scopes,discoveryUrl:s.discoveryUrl,accountIssuer:`local:oauth:${s.providerId}`,authorizationUrl:s.authorizationUrl,tokenUrl:s.tokenUrl,userInfoUrl:s.userInfoUrl,getUserInfo:l?async e=>e.accessToken?ay(l,e.accessToken):null:void 0,pkce:!0,requireIdTokenVerification:s.requireIssuerValidation,disableImplicitSignUp:!1}]}):null;return((e,A)=>{let t=A(e),{api:r}=nu(t,e),i=e.plugins?.reduce((e,A)=>A.$ERROR_CODES?{...e,...A.$ERROR_CODES}:e,{}),n=async A=>{let r,i=await t,n=i.options.basePath||"/api/auth";if((0,e1.isDynamicBaseURLConfig)(e.baseURL))r=await AO(i,A,AN(i.options));else{r=Object.create(Object.getPrototypeOf(i),Object.getOwnPropertyDescriptors(i));let e=i.options;if(!i.options.baseURL){let t=(0,e1.getBaseURL)(void 0,n,A,void 0,i.options.advanced?.trustedProxyHeaders);if(!t)throw new R.BetterAuthError("Could not get base URL from request. Please provide a valid base URL.");r.baseURL=t,r.options={...i.options,baseURL:(0,e1.getOrigin)(t)||void 0},e=r.options}r.trustedOrigins=await AM(e,A),r.trustedProviders=await AU(e,A)}let{handler:a}=((e,A)=>{let{api:t,middlewares:r}=nu(e,A),i=new URL(e.baseURL).pathname;return(0,nd.createRouter)(t,{routerContext:e,openapi:{disabled:!0},basePath:i,routerMiddleware:[{path:"/**",middleware:AY},...r],allowedMediaTypes:["application/json"],skipTrailingSlashes:A.advanced?.skipTrailingSlashes??!1,async onRequest(A){let t=e.options.disabledPaths||[],r=Aq(A.url,i);if(t.includes(r))return new Response("Not Found",{status:404});let n=A,a=await A4(n,e);if(a)return a;for(let A of e.options.plugins||[])if(A.onRequest){let t=await (0,AI.withSpan)(`onRequest ${A.id}`,{[AC]:"onRequest",[Af]:`plugin:${A.id}`},()=>A.onRequest(n,e));if(t&&"response"in t)return t.response;t&&"request"in t&&(n=t.request)}return n},async onResponse(A,t){for(let t of e.options.plugins||[])if(t.onResponse){let r=await (0,AI.withSpan)(`onResponse ${t.id}`,{[AC]:"onResponse",[Af]:`plugin:${t.id}`,[Ag.ATTR_HTTP_RESPONSE_STATUS_CODE]:A.status},()=>t.onResponse(A,e));if(r)return r.response}return A},onError(t){if((0,AP.isAPIError)(t)&&"FOUND"===t.status)return;if(A.onAPIError?.throw)throw t;if(A.onAPIError?.onError)return void A.onAPIError.onError(t,e);let r=A.logger?.level,i="error"===r||"warn"===r||"debug"===r?eM.logger:void 0;if(A.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 e.logger?.error(t.message);(0,AP.isAPIError)(t)?("INTERNAL_SERVER_ERROR"===t.status&&e.logger.error(t.status,t),i?.error(t.message)):e.logger?.error(t&&"object"==typeof t&&"name"in t?t.name:"",t)}}})})(r,e);return(0,Ac.runWithAdapter)(r.adapter,()=>a(A))};return{handler:n,fetch:n,api:r,options:e,$context:t,$ERROR_CODES:{...i,...A_.BASE_ERROR_CODES}}})({appName:"AI Development Environment",baseURL:(0,as.betterAuthBaseURL)(A.origins),trustedOrigins:e=>{if(!e)return[];let t=(0,as.originFromRequest)(e,A.trustProxyHeaders);return t&&(0,as.isTrustedOrigin)(A.origins,t)?[t]:[]},secret:A.secret,logger:{log:aw},advanced:{trustedProxyHeaders:A.trustProxyHeaders},database:(t={provider:"sqlite"},r=null,i=(e,A=!1)=>({getFieldName:r,getModelName:i,getFieldAttributes:n,getDefaultModelName:a,schema:o})=>{let s=(e,A,t)=>{if(!e&&!t)return;let n={};if(e)for(let t of e)n[r({model:A,field:t})]=!0;if(t){if(!e){let e=o[a(A)]?.fields||{};for(let t of(e.id={type:"string"},Object.keys(e)))n[r({model:A,field:t})]=!0}for(let[e,r]of Object.entries(t)){let t=l(A,i(e),o);"one-to-one"===r.relation?n[t]=!0:n[t]={take:r.limit}}}return n},l=(e,A,r)=>{try{let n=a(e),o=a(A),s=i(A).toLowerCase(),l=Object.entries(r[o]?.fields||{}).filter(([e,A])=>A.references&&a(A.references.model)===n);if(l.length>0){let[e,A]=l[0];return A?.unique===!0||!0===t.usePlural?s:`${s}s`}if((l=Object.entries(r[n]?.fields||{}).filter(([e,A])=>A.references&&a(A.references.model)===o)).length>0)return s}catch{}return`${i(A).toLowerCase()}s`};function d(e){switch(e){case"starts_with":return"startsWith";case"ends_with":return"endsWith";case"ne":return"not";case"not_in":return"notIn";default:return e}}let u=({action:e,model:A,where:i})=>{if(!i||!i.length)return{};let a=e=>{let i=r({model:A,field:e.field}),a=(e.mode??"sensitive")==="insensitive"&&("string"==typeof e.value||Array.isArray(e.value)&&e.value.every(e=>"string"==typeof e)),o="postgresql"===t.provider||"mongodb"===t.provider,s=a&&o?"insensitive":void 0,l=s?{mode:s}:{};if("ne"===e.operator&&null===e.value)return n({model:A,field:e.field})?.required!==!0?{[i]:{not:null}}:{};if(("in"===e.operator||"not_in"===e.operator)&&Array.isArray(e.value)){let A=e.value.filter(e=>null!=e);if(0===A.length)if("in"===e.operator)return{AND:[{[i]:{equals:"__never__"}},{[i]:{not:"__never__"}}]};else return{};return{[i]:{[d(e.operator)]:A,...l}}}return"eq"!==e.operator&&e.operator?"ne"===e.operator?{[i]:{not:{equals:e.value},...l}}:{[i]:{[d(e.operator)]:e.value,...l}}:{[i]:{equals:e.value,...l}}};if("update"===e){let e=i.filter(e=>"AND"===e.connector||!e.connector),t=i.filter(e=>"OR"===e.connector),n=e.filter(e=>"eq"===e.operator||!e.operator),o=e.filter(e=>"eq"!==e.operator&&void 0!==e.operator).map(e=>a(e)),s=t.map(e=>a(e)),l={};for(let e of n)l[r({model:A,field:e.field})]=e.value;return o.length>0&&(l.AND=o),s.length>0&&(l.OR=s),l}if("delete"===e){let e=i.find(e=>"id"===e.field);if(e){let t=r({model:A,field:"id"}),n=i.filter(e=>"id"!==e.field);if(0===n.length)return{[t]:e.value};let o=n.filter(e=>"AND"===e.connector||!e.connector),s=n.filter(e=>"OR"===e.connector),l=o.map(e=>a(e)),d=s.map(e=>a(e)),u={[t]:e.value};return l.length>0&&(u.AND=l),d.length>0&&(u.OR=d),u}}if(1===i.length){let e=i[0];if(!e)return;return a(e)}let o=i.filter(e=>"AND"===e.connector||!e.connector),s=i.filter(e=>"OR"===e.connector),l=o.map(e=>a(e)),u=s.map(e=>a(e));return{...l.length?{AND:l}:{},...u.length?{OR:u}:{}}};return{async create({model:A,data:t,select:r}){if(!e[A])throw new R.BetterAuthError(`Model ${A} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);return await e[A].create({data:t,select:s(r,A)})},async findOne({model:A,where:t,select:r,join:n}){let a=u({model:A,where:t,action:"findOne"});if(!e[A])throw new R.BetterAuthError(`Model ${A} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let d=new Map;for(let e of Object.keys(n??{})){let t=l(A,e,o);d.set(t,i(e))}let c=s(r,A,n),h=await e[A].findFirst({where:a,select:c});if(n&&h)for(let[e,A]of d.entries())e!==A&&e in h&&(h[A]=h[e],delete h[e]);return h},async findMany({model:A,where:t,limit:n,select:a,offset:d,sortBy:c,join:h}){let g=u({model:A,where:t,action:"findMany"});if(!e[A])throw new R.BetterAuthError(`Model ${A} 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[e,t]of Object.entries(h)){let t=l(A,e,o);p.set(t,i(e))}let C=s(a,A,h),f=await e[A].findMany({where:g,take:n||100,skip:d||0,...c?.field?{orderBy:{[r({model:A,field:c.field})]:"desc"===c.direction?"desc":"asc"}}:{},select:C});if(h&&Array.isArray(f))for(let e of f)for(let[A,t]of p.entries())A!==t&&A in e&&(e[t]=e[A],delete e[A]);return f},async count({model:A,where:t}){let r=u({model:A,where:t,action:"count"});if(!e[A])throw new R.BetterAuthError(`Model ${A} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);return await e[A].count({where:r})},async update({model:A,where:r,update:i}){if(!e[A])throw new R.BetterAuthError(`Model ${A} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);if(!(r?.length&&r.some(e=>{if("OR"===e.connector||e.operator&&"eq"!==e.operator)return!1;if("insensitive"===e.mode){let A="postgresql"===t.provider||"mongodb"===t.provider,r="string"==typeof e.value||Array.isArray(e.value)&&e.value.every(e=>"string"==typeof e);if(A&&r)return!1}return"id"===e.field||n({model:A,field:e.field})?.unique===!0}))){let t=u({model:A,where:r,action:"updateMany"});return(await e[A].updateMany({where:t,data:i}))?.count?await e[A].findFirst({where:t}):null}let a=u({model:A,where:r,action:"update"});try{return await e[A].update({where:a,data:i})}catch(e){if(eG(e))return null;throw e}},async updateMany({model:A,where:t,update:r}){if(!e[A])throw new R.BetterAuthError(`Model ${A} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let i=u({model:A,where:t,action:"updateMany"}),n=await e[A].updateMany({where:i,data:r});return n?n.count:0},async delete({model:A,where:t}){if(!e[A])throw new R.BetterAuthError(`Model ${A} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);if(!t?.some(e=>"id"===e.field)){let r=u({model:A,where:t,action:"deleteMany"});await e[A].deleteMany({where:r});return}let r=u({model:A,where:t,action:"delete"});try{await e[A].delete({where:r})}catch(e){if(eG(e))return;throw e}},async deleteMany({model:A,where:t}){let r=u({model:A,where:t,action:"deleteMany"}),i=await e[A].deleteMany({where:r});return i?i.count:0},async consumeOne({model:t,where:r}){if(!e[t])throw new R.BetterAuthError(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);if(r?.some(e=>"id"===e.field)){let A=u({model:t,where:r,action:"delete"});try{return await e[t].delete({where:A})??null}catch(e){if(eG(e))return null;throw e}}let i=u({model:t,where:r,action:"findOne"}),n=async e=>{let A=await e[t].findFirst({where:i});if(!A)return null;try{return(await e[t].deleteMany({where:u({model:t,where:[...r??[],{field:"id",value:A.id,operator:"eq",connector:"AND",mode:"sensitive"}],action:"deleteMany"})}))?.count>0?A:null}catch(e){if(eG(e))return null;throw e}};return A||"function"!=typeof e.$transaction?n(e):e.$transaction(n)},async incrementOne({model:t,where:r,increment:i,set:n}){if(!e[t])throw new R.BetterAuthError(`Model ${t} does not exist in the database. If you haven't generated the Prisma client, you need to run 'npx prisma generate'`);let a={...n??{}};for(let[e,A]of Object.entries(i))a[e]={increment:A};if(r?.some(e=>"id"===e.field)){let A=u({model:t,where:r,action:"update"});try{return await e[t].update({where:A,data:a})??null}catch(e){if(eG(e))return null;throw e}}let o=u({model:t,where:r,action:"findOne"}),s=async e=>{let A=await e[t].findFirst({where:o});if(!A)return null;try{return await e[t].update({where:u({model:t,where:[...r,{field:"id",value:A.id,operator:"eq",connector:"AND",mode:"sensitive"}],action:"update"}),data:a})??null}catch(e){if(eG(e))return null;throw e}};return A||"function"!=typeof e.$transaction?s(e):e.$transaction(s)},options:t}},n=null,n={config:{adapterId:"prisma",adapterName:"Prisma Adapter",usePlural:t.usePlural??!1,debugLogs:t.debugLogs??!1,supportsUUIDs:"postgresql"===t.provider,supportsArrays:"postgresql"===t.provider||"mongodb"===t.provider,transaction:!!t.transaction&&(A=>e.$transaction(e=>A((0,ev.createAdapterFactory)({config:{...n.config,transaction:!1},adapter:i(e,!0)})(r))))},adapter:i(e)},a=(0,ev.createAdapterFactory)(n),e=>(r=e,a(e))),emailAndPassword:{enabled:ag(A.mode),requireEmailVerification:!1},account:{accountLinking:{enabled:!0,disableImplicitLinking:!0,allowDifferentEmails:!1}},databaseHooks:aS,plugins:[function(){let e=(e=>{let A={...e||{},defaultRole:e?.defaultRole??"user",adminRoles:e?.adminRoles??["admin"],bannedUserMessage:e?.bannedUserMessage??"You have been banned from this application. Please contact support if you believe this is an error."};if(e?.adminRoles){let A=(Array.isArray(e.adminRoles)?e.adminRoles:[...e.adminRoles.split(",")]).filter(A=>!Object.keys(e?.roles||nq).map(e=>e.toLowerCase()).includes(A.toLowerCase()));if(A.length>0)throw new R.BetterAuthError(`Invalid admin roles: ${A.join(", ")}. Admin roles must be defined in the 'roles' configuration.`)}return{id:"admin",version:nx.PACKAGE_VERSION,init:()=>({options:{databaseHooks:{user:{create:{before:async A=>({data:{role:e?.defaultRole??"user",...A}})}},session:{create:{async before(e,t){if(!t)return;let r=await t.context.internalAdapter.findUserById(e.userId);if(r?.banned){if(r.banExpires&&new Date(r.banExpires).getTime()<Date.now())return void await t.context.internalAdapter.updateUser(e.userId,{banned:!1,banReason:null,banExpires:null});throw R.APIError.from("FORBIDDEN",{message:A.bannedUserMessage,code:"BANNED_USER"})}}}}}}}),hooks:{after:[{matcher:e=>"/list-sessions"===e.path,handler:(0,g.createAuthMiddleware)(async e=>{let A=await nJ(e);if(!A)return;let t=A.filter(e=>!e.impersonatedBy);return e.json(t)})}]},endpoints:{setRole:(0,g.createAuthEndpoint)("/admin/set-role",{method:"POST",body:nZ,requireHeaders:!0,use:[nz],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 e=>{if(!nF({userId:e.context.session.user.id,role:e.context.session.user.role,options:A,permissions:{user:["set-role"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE);let t=A.roles;if(t){for(let A of Array.isArray(e.body.role)?e.body.role:[e.body.role])if(!t[A])throw R.APIError.from("BAD_REQUEST",nK.YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE)}if(!await e.context.internalAdapter.findUserById(e.body.userId))throw R.APIError.from("NOT_FOUND",A_.BASE_ERROR_CODES.USER_NOT_FOUND);let r=await e.context.internalAdapter.updateUser(e.body.userId,{role:nY(e.body.role)});return e.json({user:(0,M.parseUserOutput)(e.context.options,r)})}),getUser:(0,g.createAuthEndpoint)("/admin/get-user",{method:"GET",query:nV,use:[nz],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 e=>{let{id:t}=e.query;if(!nF({userId:e.context.session.user.id,role:e.context.session.user.role,options:A,permissions:{user:["get"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_GET_USER);let r=await e.context.internalAdapter.findUserById(t);if(!r)throw R.APIError.from("NOT_FOUND",A_.BASE_ERROR_CODES.USER_NOT_FOUND);return(0,M.parseUserOutput)(e.context.options,r)}),createUser:(0,g.createAuthEndpoint)("/admin/create-user",{method:"POST",body:nW,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 e=>{let t=await (0,v.getAuthoritativeSessionFromCtx)(e);if(!t&&(e.request||e.headers))throw e.error("UNAUTHORIZED");if(t&&!nF({userId:t.user.id,role:t.user.role,options:A,permissions:{user:["create"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_CREATE_USERS);let{role:r,...i}=e.body.data??{},n=e.body.role??r;if(void 0!==n){if(t&&!nF({userId:t.user.id,role:t.user.role,options:A,permissions:{user:["set-role"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE);for(let e of Array.isArray(n)?n:[n]){if("string"!=typeof e)throw R.APIError.from("BAD_REQUEST",nK.INVALID_ROLE_TYPE);if(A.roles&&!A.roles[e])throw R.APIError.from("BAD_REQUEST",nK.YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE)}}if(t&&["banned","banReason","banExpires"].some(e=>Object.prototype.hasOwnProperty.call(i,e))&&!nF({userId:t.user.id,role:t.user.role,options:A,permissions:{user:["ban"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_BAN_USERS);let a=e.body.email.toLowerCase();if(!C.email().safeParse(a).success)throw R.APIError.from("BAD_REQUEST",A_.BASE_ERROR_CODES.INVALID_EMAIL);if(await e.context.internalAdapter.findUserByEmail(a))throw R.APIError.from("BAD_REQUEST",nK.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL);let o=await e.context.internalAdapter.createUser({...i,email:a,name:e.body.name,role:void 0!==n?nY(n):A?.defaultRole??"user"},{method:"admin"});if(!o)throw R.APIError.from("INTERNAL_SERVER_ERROR",nK.FAILED_TO_CREATE_USER);if(e.body.password){let A=await e.context.password.hash(e.body.password);await e.context.internalAdapter.linkAccount({providerId:"credential",issuer:Am("credential"),accountId:o.id,password:A,userId:o.id})}return e.json({user:(0,M.parseUserOutput)(e.context.options,o)})}),adminUpdateUser:(0,g.createAuthEndpoint)("/admin/update-user",{method:"POST",body:n$,use:[nz],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 e=>{if(!nF({userId:e.context.session.user.id,role:e.context.session.user.role,options:A,permissions:{user:["update"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_UPDATE_USERS);if(0===Object.keys(e.body.data).length)throw R.APIError.from("BAD_REQUEST",nK.NO_DATA_TO_UPDATE);let t=e.body.data,r=e=>Object.prototype.hasOwnProperty.call(t,e);if(r("password"))throw R.APIError.from("BAD_REQUEST",nK.PASSWORD_CANNOT_BE_UPDATED_VIA_UPDATE_USER);if(Object.prototype.hasOwnProperty.call(e.body.data,"role")){if(!nF({userId:e.context.session.user.id,role:e.context.session.user.role,options:A,permissions:{user:["set-role"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_CHANGE_USERS_ROLE);let t=e.body.data.role,r=Array.isArray(t)?t:[t];for(let e of r){if("string"!=typeof e)throw R.APIError.from("BAD_REQUEST",nK.INVALID_ROLE_TYPE);if(A.roles&&!A.roles[e])throw R.APIError.from("BAD_REQUEST",nK.YOU_ARE_NOT_ALLOWED_TO_SET_NON_EXISTENT_VALUE)}e.body.data.role=nY(r)}if(["banned","banReason","banExpires"].some(r)){if(!nF({userId:e.context.session.user.id,role:e.context.session.user.role,options:A,permissions:{user:["ban"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_BAN_USERS);if(!0===t.banned&&e.body.userId===e.context.session.user.id)throw R.APIError.from("BAD_REQUEST",nK.YOU_CANNOT_BAN_YOURSELF)}if(r("email")||r("emailVerified")){if(!nF({userId:e.context.session.user.id,role:e.context.session.user.role,options:A,permissions:{user:["set-email"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_SET_USERS_EMAIL);if(r("email")){let A=String(t.email).toLowerCase();if(!C.email().safeParse(A).success)throw R.APIError.from("BAD_REQUEST",A_.BASE_ERROR_CODES.INVALID_EMAIL);let r=await e.context.internalAdapter.findUserByEmail(A);if(r&&r.user.id!==e.body.userId)throw R.APIError.from("BAD_REQUEST",nK.USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL);t.email=A}}if(!await e.context.internalAdapter.findUserById(e.body.userId))throw R.APIError.from("NOT_FOUND",A_.BASE_ERROR_CODES.USER_NOT_FOUND);let i=await e.context.internalAdapter.updateUser(e.body.userId,e.body.data);return!0===t.banned&&await e.context.internalAdapter.deleteUserSessions(e.body.userId),e.json((0,M.parseUserOutput)(e.context.options,i))}),listUsers:(0,g.createAuthEndpoint)("/admin/list-users",{method:"GET",use:[nz],query:nX,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 e=>{let t=e.context.session;if(!nF({userId:e.context.session.user.id,role:t.user.role,options:A,permissions:{user:["list"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_LIST_USERS);let r=[];e.query?.searchValue&&r.push({field:e.query.searchField||"email",operator:e.query.searchOperator||"contains",value:e.query.searchValue}),e.query?.filterValue!==void 0&&r.push({field:e.query.filterField||"email",operator:e.query.filterOperator||"eq",value:e.query.filterValue});try{let A=await e.context.internalAdapter.listUsers(Number(e.query?.limit)||void 0,Number(e.query?.offset)||void 0,e.query?.sortBy?{field:e.query.sortBy,direction:e.query.sortDirection||"asc"}:void 0,r.length?r:void 0),t=await e.context.internalAdapter.countTotalUsers(r.length?r:void 0);return e.json({users:A.map(A=>(0,M.parseUserOutput)(e.context.options,A)),total:t,limit:Number(e.query?.limit)||void 0,offset:Number(e.query?.offset)||void 0})}catch{return e.json({users:[],total:0})}}),listUserSessions:(0,g.createAuthEndpoint)("/admin/list-user-sessions",{method:"POST",use:[nz],body:n0,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 e=>{let t=e.context.session;if(!nF({userId:e.context.session.user.id,role:t.user.role,options:A,permissions:{session:["list"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_LIST_USERS_SESSIONS);let r=await e.context.internalAdapter.listSessions(e.body.userId);return e.json({sessions:r.map(A=>(0,M.parseSessionOutput)(e.context.options,A))})}),unbanUser:(0,g.createAuthEndpoint)("/admin/unban-user",{method:"POST",body:n1,use:[nz],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 e=>{let t=e.context.session;if(!nF({userId:e.context.session.user.id,role:t.user.role,options:A,permissions:{user:["ban"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_BAN_USERS);if(!await e.context.internalAdapter.findUserById(e.body.userId))throw R.APIError.from("NOT_FOUND",A_.BASE_ERROR_CODES.USER_NOT_FOUND);let r=await e.context.internalAdapter.updateUser(e.body.userId,{banned:!1,banExpires:null,banReason:null,updatedAt:new Date});return e.json({user:(0,M.parseUserOutput)(e.context.options,r)})}),banUser:(0,g.createAuthEndpoint)("/admin/ban-user",{method:"POST",body:n8,use:[nz],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 e=>{let t=e.context.session;if(!nF({userId:e.context.session.user.id,role:t.user.role,options:A,permissions:{user:["ban"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_BAN_USERS);if(!await e.context.internalAdapter.findUserById(e.body.userId))throw R.APIError.from("NOT_FOUND",A_.BASE_ERROR_CODES.USER_NOT_FOUND);if(e.body.userId===e.context.session.user.id)throw R.APIError.from("BAD_REQUEST",nK.YOU_CANNOT_BAN_YOURSELF);let r=await e.context.internalAdapter.updateUser(e.body.userId,{banned:!0,banReason:e.body.banReason||A?.defaultBanReason||"No reason",banExpires:e.body.banExpiresIn?(0,Aa.getDate)(e.body.banExpiresIn,"sec"):A?.defaultBanExpiresIn?(0,Aa.getDate)(A.defaultBanExpiresIn,"sec"):null,updatedAt:new Date});return await e.context.internalAdapter.deleteUserSessions(e.body.userId),e.json({user:(0,M.parseUserOutput)(e.context.options,r)})}),impersonateUser:(0,g.createAuthEndpoint)("/admin/impersonate-user",{method:"POST",body:n4,use:[nz],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 e=>{if(!nF({userId:e.context.session.user.id,role:e.context.session.user.role,options:A,permissions:{user:["impersonate"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_IMPERSONATE_USERS);let t=await e.context.internalAdapter.findUserById(e.body.userId);if(!t)throw R.APIError.from("NOT_FOUND",A_.BASE_ERROR_CODES.USER_NOT_FOUND);let r=(Array.isArray(A.adminRoles)?A.adminRoles:A.adminRoles?.split(",")||[]).map(e=>e.trim());if(((t.role||A.defaultRole||"user").split(",").some(e=>r.includes(e))||A.adminUserIds?.includes(t.id))&&!(!0===A.allowImpersonatingAdmins||nF({userId:e.context.session.user.id,role:e.context.session.user.role,options:A,permissions:{user:["impersonate-admins"]}})))throw R.APIError.from("FORBIDDEN",nK.YOU_CANNOT_IMPERSONATE_ADMINS);let i=await e.context.internalAdapter.createSession(t.id,!0,{impersonatedBy:e.context.session.user.id,expiresAt:A?.impersonationSessionDuration?(0,Aa.getDate)(A.impersonationSessionDuration,"sec"):(0,Aa.getDate)(3600,"sec")},!0);if(!i)throw R.APIError.from("INTERNAL_SERVER_ERROR",nK.FAILED_TO_CREATE_USER);let n=e.context.authCookies;(0,An.deleteSessionCookie)(e);let a=await e.getSignedCookie(e.context.authCookies.dontRememberToken.name,e.context.secret),o=e.context.createAuthCookie("admin_session");return await e.setSignedCookie(o.name,`${e.context.session.session.token}:${a||""}`,e.context.secret,n.sessionToken.attributes),await (0,An.setSessionCookie)(e,{session:i,user:t},!0),e.json({session:i,user:(0,M.parseUserOutput)(e.context.options,t)})}),stopImpersonating:(0,g.createAuthEndpoint)("/admin/stop-impersonating",{method:"POST",requireHeaders:!0},async e=>{let A=await (0,v.getSessionFromCtx)(e);if(!A)throw R.APIError.fromStatus("UNAUTHORIZED");if(!A.session.impersonatedBy)throw R.APIError.fromStatus("BAD_REQUEST",{message:"You are not impersonating anyone"});let t=await e.context.internalAdapter.findUserById(A.session.impersonatedBy);if(!t)throw R.APIError.fromStatus("INTERNAL_SERVER_ERROR",{message:"Failed to find user"});let r=e.context.createAuthCookie("admin_session"),i=await e.getSignedCookie(r.name,e.context.secret);if(!i)throw R.APIError.fromStatus("INTERNAL_SERVER_ERROR",{message:"Failed to find admin session"});let[n,a]=i?.split(":"),o=await e.context.internalAdapter.findSession(n);if(!o||o.session.userId!==t.id)throw R.APIError.fromStatus("INTERNAL_SERVER_ERROR",{message:"Failed to find admin session"});return await e.context.internalAdapter.deleteSession(A.session.token),await (0,An.setSessionCookie)(e,o,!!a),(0,An.expireCookie)(e,r),e.json({session:(0,M.parseSessionOutput)(e.context.options,o.session),user:(0,M.parseUserOutput)(e.context.options,o.user)})}),revokeUserSession:(0,g.createAuthEndpoint)("/admin/revoke-user-session",{method:"POST",body:n2,use:[nz],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 e=>{let t=e.context.session;if(!nF({userId:e.context.session.user.id,role:t.user.role,options:A,permissions:{session:["revoke"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS);return await e.context.internalAdapter.deleteSession(e.body.sessionToken),e.json({success:!0})}),revokeUserSessions:(0,g.createAuthEndpoint)("/admin/revoke-user-sessions",{method:"POST",body:n6,use:[nz],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 e=>{let t=e.context.session;if(!nF({userId:e.context.session.user.id,role:t.user.role,options:A,permissions:{session:["revoke"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_REVOKE_USERS_SESSIONS);return await e.context.internalAdapter.deleteUserSessions(e.body.userId),e.json({success:!0})}),removeUser:(0,g.createAuthEndpoint)("/admin/remove-user",{method:"POST",body:n3,use:[nz],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 e=>{let t=e.context.session;if(!nF({userId:e.context.session.user.id,role:t.user.role,options:A,permissions:{user:["delete"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_DELETE_USERS);if(e.body.userId===e.context.session.user.id)throw R.APIError.from("BAD_REQUEST",nK.YOU_CANNOT_REMOVE_YOURSELF);if(!await e.context.internalAdapter.findUserById(e.body.userId))throw R.APIError.from("NOT_FOUND",A_.BASE_ERROR_CODES.USER_NOT_FOUND);return await e.context.internalAdapter.deleteUserSessions(e.body.userId),await e.context.internalAdapter.deleteUser(e.body.userId),e.json({success:!0})}),setUserPassword:(0,g.createAuthEndpoint)("/admin/set-user-password",{method:"POST",body:n5,use:[nz],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 e=>{if(!nF({userId:e.context.session.user.id,role:e.context.session.user.role,options:A,permissions:{user:["set-password"]}}))throw R.APIError.from("FORBIDDEN",nK.YOU_ARE_NOT_ALLOWED_TO_SET_USERS_PASSWORD);let{newPassword:t,userId:r}=e.body,i=e.context.password.config.minPasswordLength;if(t.length<i)throw e.context.logger.warn("Password is too short"),R.APIError.from("BAD_REQUEST",A_.BASE_ERROR_CODES.PASSWORD_TOO_SHORT);let n=e.context.password.config.maxPasswordLength;if(t.length>n)throw e.context.logger.warn("Password is too long"),R.APIError.from("BAD_REQUEST",A_.BASE_ERROR_CODES.PASSWORD_TOO_LONG);let a=await e.context.internalAdapter.findUserById(r);if(!a)throw R.APIError.from("NOT_FOUND",A_.BASE_ERROR_CODES.USER_NOT_FOUND);let o=await e.context.password.hash(t);return await e.context.internalAdapter.findCredentialAccount(r)?await e.context.internalAdapter.updatePassword(r,o):await e.context.internalAdapter.createAccount({userId:r,providerId:"credential",issuer:Am("credential"),accountId:a.id,password:o}),e.json({status:!0})}),userHasPermission:(0,g.createAuthEndpoint)("/admin/has-permission",{method:"POST",body:n9,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 e=>{if(!e.body?.permissions)throw new R.APIError("BAD_REQUEST",{message:"invalid permission check. no permission(s) were passed."});let t=await (0,v.getAuthoritativeSessionFromCtx)(e);if(!t&&(e.request||e.headers))throw new R.APIError("UNAUTHORIZED");if(!t&&!e.body.userId&&!e.body.role)throw new R.APIError("BAD_REQUEST",{message:"user id or role is required"});let r=t?.user||(e.body.role?{id:e.body.userId||"",role:e.body.role}:null)||(e.body.userId?await e.context.internalAdapter.findUserById(e.body.userId):null);if(!r)throw new R.APIError("BAD_REQUEST",{message:"user not found"});let i=nF({userId:r.id,role:r.role,options:A,permissions:e.body.permissions});return e.json({error:null,success:i})})},$ERROR_CODES:nK,schema:(0,M.mergeSchema)(n7,A.schema),options:e}})({ac:aR,roles:{user:av},defaultRole:"user",adminRoles:["user"]}),{setRole:A,banUser:t,unbanUser:r,impersonateUser:i,stopImpersonating:n,removeUser:a,...o}=e.endpoints;return{...e,endpoints:o}}(),function(e){if(Array.isArray(e)&&e.length>0){if(!e.every(e=>e.configId))throw new R.BetterAuthError("configId is required for each API key configuration in the api-key plugin.");let A=e.map(e=>e.configId);if(new Set(A).size!==A.length)throw new R.BetterAuthError("configId must be unique for each API key configuration in the api-key plugin.")}let A=(void 0)??{schema:Array.isArray(e)?void 0:e?.schema},t=[...(Array.isArray(e)?e:[e]).map(e=>({...e,apiKeyHeaders:e?.apiKeyHeaders??"x-api-key",defaultKeyLength:e?.defaultKeyLength||64,maximumPrefixLength:e?.maximumPrefixLength??32,minimumPrefixLength:e?.minimumPrefixLength??1,maximumNameLength:e?.maximumNameLength??32,minimumNameLength:e?.minimumNameLength??1,enableMetadata:e?.enableMetadata??!1,disableKeyHashing:e?.disableKeyHashing??!1,requireName:e?.requireName??!1,storage:e?.storage??"database",rateLimit:{enabled:e?.rateLimit?.enabled===void 0||e?.rateLimit?.enabled,timeWindow:e?.rateLimit?.timeWindow??864e5,maxRequests:e?.rateLimit?.maxRequests??10},keyExpiration:{defaultExpiresIn:e?.keyExpiration?.defaultExpiresIn??null,disableCustomExpiresTime:e?.keyExpiration?.disableCustomExpiresTime??!1,maxExpiresIn:e?.keyExpiration?.maxExpiresIn??365,minExpiresIn:e?.keyExpiration?.minExpiresIn??1},startingCharactersConfig:{shouldStore:e?.startingCharactersConfig?.shouldStore??!0,charactersLength:e?.startingCharactersConfig?.charactersLength??6},enableSessionForAPIKeys:e?.enableSessionForAPIKeys??!1,fallbackToDatabase:e?.fallbackToDatabase??!1,customStorage:e?.customStorage,deferUpdates:e?.deferUpdates??!1}))],r=(0,M.mergeSchema)((({defaultRateLimitMax:e,defaultTimeWindow:A})=>({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:A},rateLimitMax:{type:"number",required:!1,input:!1,defaultValue:e},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:e=>JSON.stringify(e),output:e=>e?(0,x.parseJSON)(e):null}}}}}))({defaultRateLimitMax:(1===t.length?t[0]?.rateLimit.maxRequests:void 0)??10,defaultTimeWindow:(1===t.length?t[0]?.rateLimit.timeWindow:void 0)??864e5}),A.schema);function i(e){for(let A of t){if(!A.enableSessionForAPIKeys)continue;let t=function(e,A){if(A.customAPIKeyGetter)return A.customAPIKeyGetter(e);if(Array.isArray(A.apiKeyHeaders)){for(let t of A.apiKeyHeaders){let A=e.headers?.get(t);if(A)return A}return null}return e.headers?.get(A.apiKeyHeaders)??null}(e,A);if(t)return{key:t,config:A}}return null}let n=function({defaultKeyGenerator:e,configurations:A,schema:t}){return{createApiKey:function({defaultKeyGenerator:e,configurations:A,schema:t,deleteAllExpiredApiKeys:r}){return(0,g.createAuthEndpoint)("/api-key/create",{method:"POST",body:eu,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:o,expiresIn:s,prefix:l,remaining:d,metadata:u,refillAmount:c,refillInterval:g,permissions:p,rateLimitMax:C,rateLimitTimeWindow:f,rateLimitEnabled:I}=t.body,w=eB(t.context,A,a),m=w.customKeyGenerator||e,E=await (0,v.getSessionFromCtx)(t,{disableCookieCache:!0}),y=t.request||t.headers;if(y&&(void 0!==c||void 0!==g||void 0!==C||void 0!==f||void 0!==I||void 0!==p||null!==d))throw R.APIError.from("BAD_REQUEST",h.SERVER_ONLY_PROPERTY);if(t.request&&void 0!==t.body.userId)throw R.APIError.from("UNAUTHORIZED",h.UNAUTHORIZED_SESSION);if("organization"===(w.references??"user")){let e=t.body.organizationId;if(!e){let e=h.ORGANIZATION_ID_REQUIRED;throw R.APIError.from("BAD_REQUEST",e)}let A=E?.user.id||t.body.userId;if(!A)throw R.APIError.from("UNAUTHORIZED",h.UNAUTHORIZED_SESSION);await es(t,A,e,"create"),i=e}else if(y){if(!E?.user.id){let e=h.UNAUTHORIZED_SESSION;throw R.APIError.from("UNAUTHORIZED",e)}i=E.user.id}else{let e=t.body.userId,A=E?.user.id;if(!A&&!e||E&&e&&A!==e){let e=h.UNAUTHORIZED_SESSION;throw R.APIError.from("UNAUTHORIZED",e)}i=A||e}if(u){if(!1===w.enableMetadata)throw R.APIError.from("BAD_REQUEST",h.METADATA_DISABLED);if("object"!=typeof u)throw R.APIError.from("BAD_REQUEST",h.INVALID_METADATA_TYPE)}if(c&&!g){let e=h.REFILL_AMOUNT_AND_INTERVAL_REQUIRED;throw R.APIError.from("BAD_REQUEST",e)}if(g&&!c){let e=h.REFILL_INTERVAL_AND_AMOUNT_REQUIRED;throw R.APIError.from("BAD_REQUEST",e)}if(s){if(!0===w.keyExpiration.disableCustomExpiresTime){let e=h.KEY_DISABLED_EXPIRATION;throw R.APIError.from("BAD_REQUEST",e)}let e=s/86400;if(w.keyExpiration.minExpiresIn>e){let e=h.EXPIRES_IN_IS_TOO_SMALL;throw R.APIError.from("BAD_REQUEST",e)}if(w.keyExpiration.maxExpiresIn<e){let e=h.EXPIRES_IN_IS_TOO_LARGE;throw R.APIError.from("BAD_REQUEST",e)}}if(l&&(l.length<w.minimumPrefixLength||l.length>w.maximumPrefixLength))throw R.APIError.from("BAD_REQUEST",h.INVALID_PREFIX_LENGTH);if(o){if(o.length<w.minimumNameLength||o.length>w.maximumNameLength)throw R.APIError.from("BAD_REQUEST",h.INVALID_NAME_LENGTH)}else if(w.requireName)throw R.APIError.from("BAD_REQUEST",h.NAME_REQUIRED);r(t.context);let B=await m({length:w.defaultKeyLength,prefix:l||w.defaultPrefix}),Q=w.disableKeyHashing?B:await ek(B),D=null;w.startingCharactersConfig.shouldStore&&(D=B.substring(0,w.startingCharactersConfig.charactersLength));let b=w.permissions?.defaultPermissions?"function"==typeof w.permissions.defaultPermissions?await w.permissions.defaultPermissions(i,t):w.permissions.defaultPermissions:void 0,S=p?JSON.stringify(p):b?JSON.stringify(b):void 0,k={configId:w.configId??"default",createdAt:new Date,updatedAt:new Date,name:o??null,prefix:l??w.defaultPrefix??null,start:D,key:Q,enabled:!0,expiresAt:s?ed(s,"sec"):w.keyExpiration.defaultExpiresIn?ed(w.keyExpiration.defaultExpiresIn,"sec"):null,referenceId:i,lastRefillAt:null,lastRequest:null,metadata:null,rateLimitMax:C??w.rateLimit.maxRequests??null,rateLimitTimeWindow:f??w.rateLimit.timeWindow??null,remaining:null===d?d:d??c??null,refillAmount:c??null,refillInterval:g??null,rateLimitEnabled:void 0===I?w.rateLimit.enabled??!0:I,requestCount:0,permissions:S};if(u&&(k.metadata=u),"secondary-storage"===w.storage&&w.fallbackToDatabase)n=await t.context.adapter.create({model:eR,data:k}),await ei(t,n,w);else if("secondary-storage"===w.storage){let e=t.context.generateId({model:"apikey"})||(0,N.generateId)();n={...k,id:e},await ei(t,n,w)}else n=await t.context.adapter.create({model:eR,data:k});return t.json({...n,key:B,metadata:u??null,permissions:n.permissions?(0,O.safeJSONParse)(n.permissions):null})})}({defaultKeyGenerator:e,configurations:A,schema:t,deleteAllExpiredApiKeys:eS}),verifyApiKey:function({configurations:e,schema:A,deleteAllExpiredApiKeys:t}){return g.createAuthEndpoint.serverOnly({method:"POST",body:ey},async r=>{let i,{configId:n,key:a}=r.body,o=eB(r.context,e,n);if(void 0!==n&&o.customAPIKeyValidator&&!await o.customAPIKeyValidator({ctx:r,key:a}))return r.json({valid:!1,error:{message:h.INVALID_API_KEY,code:"KEY_NOT_FOUND"},key:null});let s=null;try{let l=await ef({key:a,permissions:r.body.permissions,ctx:r,lookupOpts:o,configurations:e,schema:A,expectedConfigId:n,runCustomValidator:void 0===n});s=l.apiKey,(i=l.opts).deferUpdates&&r.context.runInBackground(t(r.context).catch(e=>{r.context.logger.error("Failed to delete expired API keys:",e)}))}catch(e){if(r.context.logger.error("Failed to validate API key:",e),e instanceof R.APIError||e instanceof R.APIError||e?.name==="APIError")return r.json({valid:!1,error:{...e.body,message:e.body?.message,code:e.body?.code},key:null});return r.json({valid:!1,error:{message:h.INVALID_API_KEY,code:"INVALID_API_KEY"},key:null})}let{key:l,...d}=s??{key:1,permissions:void 0},u=null;return s&&(u=await K(r,s,i)),d.permissions=d.permissions?(0,O.safeJSONParse)(d.permissions):null,r.json({valid:!0,error:null,key:null===s?null:{...d,metadata:u}})})}({configurations:A,schema:t,deleteAllExpiredApiKeys:eS}),getApiKey:function({configurations:e,schema:A,deleteAllExpiredApiKeys:t}){return(0,g.createAuthEndpoint)("/api-key/get",{method:"GET",query:eh,use:[v.sessionMiddleware],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 A=>{let{configId:r,id:i}=A.query,n=A.context.session,a=eB(A.context,e,r),o=null;if(!(o=await er(A,i,a))||!eD(o.configId,a.configId))throw R.APIError.from("NOT_FOUND",h.KEY_NOT_FOUND);let s=eB(A.context,e,o.configId);if((s.references??"user")==="organization")await es(A,n.user.id,o.referenceId,"read");else if(o.referenceId!==n.user.id)throw R.APIError.from("NOT_FOUND",h.KEY_NOT_FOUND);t(A.context);let l=await K(A,o,s),{key:d,...u}=o;return A.json({...u,metadata:l,permissions:u.permissions?(0,O.safeJSONParse)(u.permissions):null})})}({configurations:A,schema:t,deleteAllExpiredApiKeys:eS}),updateApiKey:function({configurations:e,schema:A,deleteAllExpiredApiKeys:t}){return(0,g.createAuthEndpoint)("/api-key/update",{method:"POST",body:ep,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 A=>{let{configId:r,keyId:i,expiresIn:n,enabled:a,metadata:o,refillAmount:s,refillInterval:l,remaining:d,name:u,permissions:c,rateLimitEnabled:g,rateLimitTimeWindow:p,rateLimitMax:C}=A.body,f=await (0,v.getSessionFromCtx)(A,{disableCookieCache:!0}),I=A.request||A.headers,w=I&&!f?null:f?.user||{id:A.body.userId};if(!w?.id||f&&A.body.userId&&f?.user.id!==A.body.userId)throw R.APIError.from("UNAUTHORIZED",h.UNAUTHORIZED_SESSION);if(I&&(void 0!==s||void 0!==l||void 0!==C||void 0!==p||void 0!==g||void 0!==d||void 0!==c))throw R.APIError.from("BAD_REQUEST",h.SERVER_ONLY_PROPERTY);let m=eB(A.context,e,r),E=null;if(!(E=await er(A,i,m))||!eD(E.configId,m.configId))throw R.APIError.from("NOT_FOUND",h.KEY_NOT_FOUND);let y=eB(A.context,e,E.configId);if((y.references??"user")==="organization")await es(A,w.id,E.referenceId,"update");else if(E.referenceId!==w.id)throw R.APIError.from("NOT_FOUND",h.KEY_NOT_FOUND);let B={};if(void 0!==u){if(u.length<y.minimumNameLength||u.length>y.maximumNameLength)throw R.APIError.from("BAD_REQUEST",h.INVALID_NAME_LENGTH);B.name=u}if(void 0!==a&&(B.enabled=a),void 0!==n){if(!0===y.keyExpiration.disableCustomExpiresTime)throw R.APIError.from("BAD_REQUEST",h.KEY_DISABLED_EXPIRATION);if(null!==n){let e=n/86400;if(e<y.keyExpiration.minExpiresIn)throw R.APIError.from("BAD_REQUEST",h.EXPIRES_IN_IS_TOO_SMALL);if(e>y.keyExpiration.maxExpiresIn)throw R.APIError.from("BAD_REQUEST",h.EXPIRES_IN_IS_TOO_LARGE)}B.expiresAt=n?ed(n,"sec"):null}if(void 0!==o&&!0===y.enableMetadata){if("object"!=typeof o)throw R.APIError.from("BAD_REQUEST",h.INVALID_METADATA_TYPE);B.metadata=o}if(void 0!==d&&(B.remaining=d),void 0!==s||void 0!==l){if(void 0!==s&&void 0===l)throw R.APIError.from("BAD_REQUEST",h.REFILL_AMOUNT_AND_INTERVAL_REQUIRED);if(void 0!==l&&void 0===s)throw R.APIError.from("BAD_REQUEST",h.REFILL_INTERVAL_AND_AMOUNT_REQUIRED);B.refillAmount=s,B.refillInterval=l}if(void 0!==g&&(B.rateLimitEnabled=g),void 0!==p&&(B.rateLimitTimeWindow=p),void 0!==C&&(B.rateLimitMax=C),void 0!==c&&(B.permissions=JSON.stringify(c)),0===Object.keys(B).length)throw R.APIError.from("BAD_REQUEST",h.NO_VALUES_TO_UPDATE);let Q=E;try{if("secondary-storage"===y.storage&&y.fallbackToDatabase){let e=await A.context.adapter.update({model:eR,where:[{field:"id",value:E.id}],update:B});e&&(await ei(A,e,y),Q=e)}else if("database"===y.storage){let e=await A.context.adapter.update({model:eR,where:[{field:"id",value:E.id}],update:B});e&&(Q=e)}else{let e={...E,...B,updatedAt:new Date};await ei(A,e,y),Q=e}}catch(e){throw R.APIError.fromStatus("INTERNAL_SERVER_ERROR",{message:e?.message})}t(A.context);let D=await K(A,Q,y),{key:b,...S}=Q;return A.json({...S,metadata:D,permissions:S.permissions?(0,O.safeJSONParse)(S.permissions):null})})}({configurations:A,schema:t,deleteAllExpiredApiKeys:eS}),deleteApiKey:function({configurations:e,schema:A,deleteAllExpiredApiKeys:t}){return(0,g.createAuthEndpoint)("/api-key/delete",{method:"POST",body:ec,use:[v.sessionMiddleware],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 A=>{let{configId:r,keyId:i}=A.body,n=A.context.session;if(!0===n.user.banned)throw R.APIError.from("UNAUTHORIZED",h.USER_BANNED);let a=eB(A.context,e,r),o=null;if(!(o=await er(A,i,a))||!eD(o.configId,a.configId))throw R.APIError.from("NOT_FOUND",h.KEY_NOT_FOUND);let s=eB(A.context,e,o.configId);if((s.references??"user")==="organization")await es(A,n.user.id,o.referenceId,"delete");else if(o.referenceId!==n.user.id)throw R.APIError.from("NOT_FOUND",h.KEY_NOT_FOUND);try{"secondary-storage"===s.storage&&s.fallbackToDatabase?(await en(A,o,s),await A.context.adapter.delete({model:eR,where:[{field:"id",value:o.id}]})):"database"===s.storage?await A.context.adapter.delete({model:eR,where:[{field:"id",value:o.id}]}):await en(A,o,s)}catch(e){throw R.APIError.fromStatus("INTERNAL_SERVER_ERROR",{message:e?.message})}return t(A.context),A.json({success:!0})})}({configurations:A,schema:t,deleteAllExpiredApiKeys:eS}),listApiKeys:function({configurations:e,schema:A,deleteAllExpiredApiKeys:t}){return(0,g.createAuthEndpoint)("/api-key/list",{method:"GET",use:[v.sessionMiddleware],query:eg,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 A=>{let r=A.context.session,i=A.query?.configId,n=A.query?.organizationId,a=A.query?.limit!=null?Number(A.query.limit):void 0,o=A.query?.offset!=null?Number(A.query.offset):void 0;n&&await es(A,r.user.id,n,"read");let s=n??r.user.id,l=n?"organization":"user",d=[];if(i){let{apiKeys:t}=await eo(A,s,eB(A.context,e,i),{limit:void 0,offset:void 0,sortBy:A.query?.sortBy,sortDirection:A.query?.sortDirection});d=t}else{let t=new Map;for(let A of e){let e="database"===A.storage?"database":A.customStorage?`custom:${A.configId??"default"}`:A.fallbackToDatabase?"secondary-storage-with-fallback":"secondary-storage";t.has(e)||t.set(e,A)}let r=await Promise.all([...t.values()].map(e=>eo(A,s,e,{limit:void 0,offset:void 0,sortBy:A.query?.sortBy,sortDirection:A.query?.sortDirection}))),i=new Set;for(let{apiKeys:e}of r)for(let A of e)i.has(A.id)||(i.add(A.id),d.push(A))}let u=d.filter(A=>(e.find(e=>eQ(A.configId)?eQ(e.configId):e.configId===A.configId)?.references??"user")===l&&A.referenceId===s);i&&(u=u.filter(e=>eD(e.configId,i)));let c=u.length,h=u;void 0!==o&&(h=h.slice(o)),void 0!==a&&(h=h.slice(0,a)),t(A.context);let g=h.map(e=>{let{key:A,...t}=e;return{...t,metadata:L(e.metadata),permissions:t.permissions?(0,O.safeJSONParse)(t.permissions):null}}),p=e.find(e=>"database"===e.storage||e.fallbackToDatabase);return p&&await A.context.runInBackgroundOrAwait(q(A,h,p)),A.json({apiKeys:g,total:c,limit:a,offset:o})})}({configurations:A,schema:t,deleteAllExpiredApiKeys:eS}),deleteAllExpiredApiKeys:function({deleteAllExpiredApiKeys:e}){return g.createAuthEndpoint.serverOnly({method:"POST"},async A=>{try{await e(A.context,!0)}catch(e){return A.context.logger.error("[API KEY PLUGIN] Failed to delete expired API keys:",e),A.json({success:!1,error:e})}return A.json({success:!0,error:null})})}({deleteAllExpiredApiKeys:eS})}}({defaultKeyGenerator:async e=>{let A=T(e.length,"a-z","A-Z");return`${e.prefix||""}${A}`},configurations:t,schema:r});return{id:"api-key",version:"1.7.2",$ERROR_CODES:h,hooks:{before:[{matcher:e=>!!i(e),handler:(0,g.createAuthMiddleware)(async e=>{let{key:A,config:n}=i(e);if("string"!=typeof A)throw R.APIError.from("BAD_REQUEST",h.INVALID_API_KEY_GETTER_RETURN_TYPE);if(A.length<n.defaultKeyLength||n.customAPIKeyValidator&&!await n.customAPIKeyValidator({ctx:e,key:A}))throw R.APIError.from("FORBIDDEN",h.INVALID_API_KEY);let{apiKey:a}=await ef({key:A,ctx:e,lookupOpts:n,configurations:t,schema:r,expectedConfigId:n.configId}),o=eS(e.context).catch(A=>{e.context.logger.error("Failed to delete expired API keys:",A)});if(n.deferUpdates&&e.context.runInBackground(o),(n.references??"user")!=="user"){let e=h.INVALID_REFERENCE_ID_FROM_API_KEY;throw R.APIError.from("UNAUTHORIZED",e)}let s=await e.context.internalAdapter.findUserById(a.referenceId);if(!s){let e=h.INVALID_REFERENCE_ID_FROM_API_KEY;throw R.APIError.from("UNAUTHORIZED",e)}let l={user:s,session:{id:a.id,token:A,userId:a.referenceId,userAgent:e.request?.headers.get("user-agent")??null,ipAddress:e.request?b(e.request,e.context.options):null,createdAt:new Date,updatedAt:new Date,expiresAt:a.expiresAt||ed(e.context.options.session?.expiresIn||604800,"ms")}};return(e.context.session=l,"/get-session"===e.path)?l:{context:e}})}]},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:nx.PACKAGE_VERSION,hooks:{before:[{matcher:e=>!!(e.request?.headers.get("authorization")||e.headers?.get("authorization")),handler:(0,g.createAuthMiddleware)(async e=>{let A,t=e.request?.headers.get("authorization")||e.headers?.get("Authorization");if(!t||"bearer "!==t.slice(0,7).toLowerCase())return;let r=t.slice(7).trim();if(!r)return;A=r.includes(".")?r.includes("%")?at(r):r:at((await (0,ae.serializeSignedCookie)("",r,e.context.secret)).replace("=",""));try{if(!await (0,aA.createHMAC)("SHA-256","base64urlnopad").verify(e.context.secret,A.split(".")[0],A.split(".")[1]))return}catch{return}let i=e.request?.headers||e.headers,n=new Headers({...Object.fromEntries(i?.entries())});return(0,n_.setRequestCookie)(n,e.context.authCookies.sessionToken.name,A),{context:{headers:n}}})}],after:[{matcher:e=>!0,handler:(0,g.createAuthMiddleware)(async e=>{let A=e.context.responseHeaders?.get("set-cookie");if(!A)return;let t=(0,n_.parseSetCookieHeader)(A),r=e.context.authCookies.sessionToken.name,i=t.get(r);if(!i||!i.value||0===i["max-age"])return;let n=i.value,a=new Set((e.context.responseHeaders?.get("access-control-expose-headers")||"").split(",").map(e=>e.trim()).filter(Boolean));a.add("set-auth-token"),e.setHeader("set-auth-token",n),e.setHeader("Access-Control-Expose-Headers",Array.from(a).join(", "))})}]},options:void 0},(e=>{let A={storeToken:"plain",...e};async function t(e,t){return"hashed"===A.storeToken?await aa(t):"object"==typeof A.storeToken&&"type"in A.storeToken&&"custom-hasher"===A.storeToken.type?await A.storeToken.hash(t):t}async function r(e,r){let i=A?.generateToken?await A.generateToken(r,e):T(32),n=new Date(Date.now()+(A?.expiresIn??3)*6e4),a=await t(e,i);return await e.context.internalAdapter.createVerificationValue({value:r.session.token,identifier:`one-time-token:${a}`,expiresAt:n}),i}return{id:"one-time-token",version:nx.PACKAGE_VERSION,endpoints:{generateOneTimeToken:(0,g.createAuthEndpoint)("/one-time-token/generate",{method:"GET",use:[v.sessionMiddleware]},async e=>{if(A?.disableClientRequest&&e.request)throw e.error("BAD_REQUEST",{message:"Client requests are disabled"});let t=e.context.session,i=await r(e,t);return e.json({token:i})}),verifyOneTimeToken:(0,g.createAuthEndpoint)("/one-time-token/verify",{method:"POST",body:ao},async e=>{let{token:r}=e.body,i=await t(e,r),n=await e.context.internalAdapter.consumeVerificationValue(`one-time-token:${i}`);if(!n)throw e.error("BAD_REQUEST",{message:"Invalid token"});let a=await e.context.internalAdapter.findSession(n.value);if(!a)throw e.error("BAD_REQUEST",{message:"Session not found"});if(A?.disableSetSessionCookie||await (0,An.setSessionCookie)(e,a),a.session.expiresAt<new Date)throw e.error("BAD_REQUEST",{message:"Session expired"});return e.json(a)})},hooks:{after:[{matcher:()=>!0,handler:(0,g.createAuthMiddleware)(async e=>{if(e.context.newSession){if(!A?.setOttHeaderOnNewSession)return;let t=new Set((e.context.responseHeaders?.get("access-control-expose-headers")||"").split(",").map(e=>e.trim()).filter(Boolean));t.add("set-ott");let i=await r(e,e.context.newSession);e.setHeader("set-ott",i),e.setHeader("Access-Control-Expose-Headers",Array.from(t).join(", "))}})}]},options:e}})({disableClientRequest:!0,expiresIn:1,storeToken:"hashed"}),...d?[d]:[],(o=!1,{id:"next-cookies",version:nx.PACKAGE_VERSION,hooks:{before:[{matcher:e=>"/get-session"===e.path,handler:(0,g.createAuthMiddleware)(async e=>{let A;if(o||(!function(e,A){let t=e.options.plugins||[];if(0===t.length)return;let r=t.findIndex(e=>e.id===A);-1===r||t.slice(r+1).some(e=>e.hooks&&Array.isArray(e.hooks.after)&&e.hooks.after.length>0)&&e.logger.warn(`[better-auth] Cookie integration plugin "${A}" 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.`)}(e.context,"next-cookies"),o=!0),"_flag"in e&&"router"===e._flag)return;try{let{headers:e}=await nL();A=await e()}catch{return}let t="1"===A.get("RSC"),r=!!A.get("next-action");t&&!r&&await (0,te.setShouldSkipSessionRefresh)(!0)})}],after:[{matcher:e=>!0,handler:(0,g.createAuthMiddleware)(async e=>{let A=e.context.responseHeaders;if((!("_flag"in e)||"router"!==e._flag)&&A instanceof Headers){let e,t=A?.get("set-cookie");if(!t)return;let r=(0,n_.parseSetCookieHeader)(t);try{let{cookies:A}=await nL();e=await A()}catch(e){if(e instanceof Error&&(e.message.startsWith("`cookies` was called outside a request scope.")||e.message.includes("Cannot find module")))return;throw e}r.forEach((A,t)=>{if(t)try{e.set(t,A.value,(0,n_.toCookieOptions)(A))}catch{}});return}})}]}})]},nU)})(e))),aG}e.s(["getAuth",0,aT],725307);class aM extends Error{status;constructor(e,A=401){super(e),this.status=A,this.name="PrincipalResolutionError"}}async function aN(e,A){let t=e.get("x-api-key")?.trim()||null,r=function(e){let A=e.get("authorization");if(!A)return null;if(!A.startsWith("Bearer "))throw new aM("Authorization must use the Bearer scheme.");let t=A.slice(7).trim();if(!t)throw new aM("The bearer credential is empty.");return t}(e),i=/(?:^|;\s*)(?:__Secure-)?better-auth\.session_token=/.test(e.get("cookie")??"");if(Number(!!t)+Number(!!r)+Number(i)>1)throw new aM("Provide exactly one application credential.",400);if(t){let e=await aT(),A=await e.api.verifyApiKey({body:{key:t}});if(!A.valid||!A.key)throw new aM("The API key is invalid or inactive.");return{kind:"apiKey",apiKeyId:A.key.id,userId:A.key.referenceId,name:A.key.name??null}}if(r?.startsWith("agent_")){if(!A)throw new aM("Agent credentials are not accepted by this endpoint.");let e=await A.authenticate(r);if(!e)throw new aM("The agent credential is invalid.");return{kind:"agent",agentId:e}}if(r||i){let A=await aT(),t=await A.api.getSession({headers:e});if(!t?.session||!t.user)throw new aM("The session is invalid or expired.");return{kind:"user",userId:t.user.id,email:t.user.email,sessionId:t.session.id}}return{kind:"anonymous"}}e.s(["resolveRequestPrincipal",0,aN],847435)},914710,e=>{"use strict";e.i(725307),e.i(658978),e.i(847435),e.i(525796),e.s([],914710)},737799,e=>{"use strict";e.i(666680),e.i(914710),e.s([])},476314,e=>{"use strict";var A,t=e.i(715224),r=e.i(822196);e.i(198171),e.i(448224);e.i(214928),t.Protocol,e.i(381575),Symbol.for("mcp.completable"),(A||(A={})).Completable="McpCompletable",e.i(749906),e.s([],476314)},423924,e=>e.a(async(A,t)=>{try{e.s([]),e.i(476314);var r=e.i(652085),i=A([r]);[r]=i.then?(await i)():i,t()}catch(e){t(e)}},!1),576565,e=>e.a(async(A,t)=>{try{e.s([]);var r=e.i(504400);e.i(737799),e.i(176985);var i=e.i(423924),n=e.i(652085),a=A([r,i,n]);[r,i,n]=a.then?(await a)():a,t()}catch(e){t(e)}},!1),374421,e=>{"use strict";var A=e.i(666680),t=e.i(380592),r=e.i(135475);let i="server:worktree-automations",n=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"]),a=new Set(["SUCCEEDED","FAILED","CANCELLED"]);function o(e){let[A,t,r]=e.split("/");if(!A||!t||r)throw Error("A GitHub repository must be in owner/name format");return{owner:A,name:t}}function s(e){return{worktreeId:e.worktreeId,state:e.state,conflictWorkflowId:e.conflictWorkflowId,conflictWorkflowChoice:e.conflictWorkflowChoice,lastError:e.lastError,pauseReason:e.pauseReason,lastSyncedAt:e.lastSyncedAt?.toISOString()??null,updatedAt:e.updatedAt.toISOString()}}function l(e){return{...e,mergeMethod:e.mergeMethod,updatedAt:e.updatedAt.toISOString()}}e.s(["WorktreeAutomationService",0,class{worktrees;github;jira;workflows;agentControl;polling;timer;running;rerunRequested;constructor(e,A,r,n,a,o){this.worktrees=e,this.github=A,this.jira=r,this.workflows=n,this.agentControl=a,this.polling=o,this.timer=null,this.running=!1,this.rerunRequested=!1,this.agentControl.registerCompletionObserver(async e=>{e.kind===t.WORKTREE_AUTO_SYNC_JOB_KIND&&this.changed()}),this.polling?.register({id:i,kind:"WORKTREE_AUTOMATION",runtime:"SERVER",enabled:!0,cadenceSeconds:60,details:{}})}startRuntime(){queueMicrotask(()=>void this.reconcile())}schedule(){this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>void this.reconcile(),6e4),this.timer.unref(),this.polling?.schedule(i,new Date(Date.now()+6e4))}changed(){if(this.running){this.rerunRequested=!0;return}this.timer&&clearTimeout(this.timer),this.timer=null,queueMicrotask(()=>void this.reconcile())}async stopAutoSyncWork(e){e?.activeJobId&&await this.agentControl.cancelJob(e.activeJobId).catch(()=>null),e?.workflowRunId&&await this.workflows.lifecycle(e.workflowRunId,"CANCEL").catch(()=>null)}async autoSync(e){let A=await (0,r.getPrismaClient)(),t=await A.worktreeAutoSync.findUnique({where:{worktreeId:e}});return t?s(t):null}async configureAutoSync(e){let A=await (0,r.getPrismaClient)(),t=await A.worktree.findFirst({where:{id:e.worktreeId,missingAt:null},select:{id:!0,branch:!0,codebaseId:!0,codebase:{select:{repositoryId:!0}}}});if(!t?.branch)throw Error("Auto Sync requires a branch");await this.stopAutoSyncWork(await A.worktreeAutoSync.findUnique({where:{worktreeId:t.id},select:{activeJobId:!0,workflowRunId:!0}}));let i=e.conflictWorkflowId?.trim()||null;if(i){let e=await A.workflow.findUnique({where:{id:i},select:{enabled:!0,archivedAt:!0,activeVersionId:!0,quickActionKind:!0,quickActionRepositories:{select:{repositoryId:!0}}}});if(!e?.enabled||e.archivedAt||!e.activeVersionId||"MERGE_CONFLICT"!==e.quickActionKind)throw Error("Select an enabled merge-conflict quick action workflow");if(e.quickActionRepositories.length>0&&!e.quickActionRepositories.some(({repositoryId:e})=>e===t.codebase.repositoryId))throw Error("The merge-conflict workflow is not available for this repository")}let n=await A.worktreeAutoSync.upsert({where:{worktreeId:t.id},create:{worktreeId:t.id,branch:t.branch,conflictWorkflowId:i,conflictWorkflowChoice:e.conflictWorkflowChoice?.trim()||null},update:{state:"ACTIVE",branch:t.branch,conflictWorkflowId:i,conflictWorkflowChoice:e.conflictWorkflowChoice?.trim()||null,activeJobId:null,workflowRunId:null,lastError:null,pauseReason:null}});return this.worktrees.publishAutomationChange(t.id,t.codebaseId),this.changed(),s(n)}async cancelAutoSync(e){let A=await (0,r.getPrismaClient)(),t=await A.worktreeAutoSync.findUnique({where:{worktreeId:e},select:{activeJobId:!0,workflowRunId:!0}});await this.stopAutoSyncWork(t);let i=await A.worktreeAutoSync.deleteMany({where:{worktreeId:e}});return this.worktrees.publishAutomationChange(e),i.count>0}async retryAutoSync(e){let A=await (0,r.getPrismaClient)(),t=await A.worktreeAutoSync.update({where:{worktreeId:e},data:{state:"ACTIVE",activeJobId:null,workflowRunId:null,lastError:null,pauseReason:null}});return this.worktrees.publishAutomationChange(e),this.changed(),s(t)}async autoMerge(e){let A=await (0,r.getPrismaClient)(),t=await A.worktreeAutoMerge.findUnique({where:{worktreeId:e}});return t?l(t):null}async configureAutoMerge(e){let A=await (0,r.getPrismaClient)(),t=await A.worktree.findFirst({where:{id:e.worktreeId,missingAt:null},select:{id:!0,primary:!0,branch:!0,codebaseId:!0,codebase:{select:{repository:{select:{canonicalOrigin:!0}}}}}});if(!t?.branch)throw Error("Auto Merge requires a branch");if(e.deleteWorktree&&t.primary)throw Error("The primary worktree cannot be deleted after merge");let i=await A.worktreeAutoMerge.findUnique({where:{worktreeId:t.id}}),n=await this.worktrees.ticketKeyForWorktree(t.id);if(e.moveTicketToDone){if(!n)throw Error("This worktree is not linked to a Jira ticket");let e=await A.jiraProject.findUnique({where:{key:n.split("-")[0]??""},select:{doneStatusId:!0}});if(!e?.doneStatusId)throw Error("Configure this Jira project's done status before enabling this option")}let a=o(e.repositoryNameWithOwner),s=await this.github.pullRequestAutomationState(a.owner,a.name,e.pullRequestNumber);if(s.headRefName!==t.branch)throw Error("The pull request does not belong to this worktree branch");if(!s.headRepositoryNameWithOwner)throw Error("The pull request head repository is unavailable");if(t.codebase.repository.canonicalOrigin.toLowerCase()!==`github.com/${s.headRepositoryNameWithOwner.toLowerCase()}`)throw Error("The pull request head repository does not match this worktree");let d=!!(i&&(i.repositoryNameWithOwner.toLowerCase()!==e.repositoryNameWithOwner.toLowerCase()||i.pullRequestNumber!==e.pullRequestNumber)),u=!1,c=!1;try{if(i&&d){let e=o(i.repositoryNameWithOwner),A=await this.github.pullRequestAutomationState(e.owner,e.name,i.pullRequestNumber);"OPEN"===A.state&&A.autoMergeEnabled&&(await this.github.disablePullRequestAutoMerge({...e,number:i.pullRequestNumber},"WORKTREE_AUTOMATION"),u=!0)}c=!0,await this.github.enablePullRequestAutoMerge({...a,number:e.pullRequestNumber,method:e.method,commitHeadline:e.commitHeadline,commitBody:e.commitBody,authorEmail:e.authorEmail},"WORKTREE_AUTOMATION");let r=await A.worktreeAutoMerge.upsert({where:{worktreeId:t.id},create:{worktreeId:t.id,repositoryNameWithOwner:e.repositoryNameWithOwner,pullRequestNumber:e.pullRequestNumber,branch:t.branch,mergeMethod:e.method,commitHeadline:e.commitHeadline.trim(),commitBody:e.commitBody,authorEmail:e.authorEmail?.trim()||null,deleteWorktree:e.deleteWorktree,moveTicketToDone:e.moveTicketToDone,ticketKey:n},update:{state:"ACTIVE",repositoryNameWithOwner:e.repositoryNameWithOwner,pullRequestNumber:e.pullRequestNumber,branch:t.branch,mergeMethod:e.method,commitHeadline:e.commitHeadline.trim(),commitBody:e.commitBody,authorEmail:e.authorEmail?.trim()||null,deleteWorktree:e.deleteWorktree,moveTicketToDone:e.moveTicketToDone,ticketKey:n,ticketMovedAt:null,deleteJobId:null,lastError:null}});return this.worktrees.publishAutomationChange(t.id,t.codebaseId),this.changed(),l(r)}catch(A){if(c&&await this.github.disablePullRequestAutoMerge({...a,number:e.pullRequestNumber},"WORKTREE_AUTOMATION").catch(()=>null),i&&(u||!d)){let e=o(i.repositoryNameWithOwner);await this.github.enablePullRequestAutoMerge({...e,number:i.pullRequestNumber,method:i.mergeMethod,commitHeadline:i.commitHeadline,commitBody:i.commitBody,authorEmail:i.authorEmail},"WORKTREE_AUTOMATION").catch(()=>null)}throw A}}async forceAutoSync(e,A){if(!A.trim())throw Error("requestId is required");let t=await (0,r.getPrismaClient)(),i=await t.worktreeAutoSync.findUnique({where:{worktreeId:e}});if(!i||"PAUSED"!==i.state||"PREPARATION_CONFLICT"!==i.pauseReason)throw Error("Auto Sync is not paused for a preparation conflict");let n=await this.worktrees.createAutoSyncJob(e,"SYNC",i.branch,A,!0);return await t.worktreeAutoSync.update({where:{worktreeId:e},data:{state:"SYNCING",activeJobId:n.id,workflowRunId:null,lastError:null,pauseReason:null}}),this.worktrees.publishAutomationChange(e),this.changed(),n}async cancelAutoMerge(e){let A=await (0,r.getPrismaClient)(),t=await A.worktreeAutoMerge.findUnique({where:{worktreeId:e}});if(!t)return!1;let i=o(t.repositoryNameWithOwner),n=await this.github.pullRequestAutomationState(i.owner,i.name,t.pullRequestNumber);return"OPEN"===n.state&&n.autoMergeEnabled&&await this.github.disablePullRequestAutoMerge({...i,number:t.pullRequestNumber},"WORKTREE_AUTOMATION"),await A.worktreeAutoMerge.delete({where:{worktreeId:e}}),this.worktrees.publishAutomationChange(e),!0}async retryAutoMerge(e){let A=await (0,r.getPrismaClient)(),t=await A.worktreeAutoMerge.findUniqueOrThrow({where:{worktreeId:e}}),i=o(t.repositoryNameWithOwner),n="MERGED"===(await this.github.pullRequestAutomationState(i.owner,i.name,t.pullRequestNumber)).state?"POST_MERGE":"ACTIVE",a=await A.worktreeAutoMerge.update({where:{worktreeId:e},data:{state:n,lastError:null,deleteJobId:null}});return this.worktrees.publishAutomationChange(e),this.changed(),l(a)}async reconcile(){if(this.running){this.rerunRequested=!0;return}this.running=!0;try{let e=async()=>{do this.rerunRequested=!1,await this.reconcileAutoSync(),await this.reconcileAutoMerge();while(this.rerunRequested)};this.polling?await this.polling.run(i,e):await e()}catch{}finally{this.running=!1,this.schedule()}}async reconcileAutoSync(){let e=await (0,r.getPrismaClient)();for(let t of(await e.worktreeAutoSync.findMany({where:{state:{in:["ACTIVE","SYNCING","RESOLVING"]}},include:{worktree:{select:{codebaseId:!0}}}})))try{let r=await e.worktree.findUnique({where:{id:t.worktreeId},select:{branch:!0}});if(r?.branch!==t.branch)throw Error("Auto Sync paused because the worktree branch changed");if("ACTIVE"===t.state){let r=await this.worktrees.createAutoSyncJob(t.worktreeId,"SYNC",t.branch,(0,A.randomUUID)());await e.worktreeAutoSync.update({where:{worktreeId:t.worktreeId},data:{state:"SYNCING",activeJobId:r.id,lastError:null,pauseReason:null}});continue}if("RESOLVING"===t.state){if(!t.workflowRunId)throw Error("The conflict workflow run is missing");let r=await this.workflows.run(t.workflowRunId);if(!r||!a.has(r.status))continue;if("SUCCEEDED"!==r.status)throw Error(`The conflict workflow ${r.status.toLowerCase()}`);let i=await this.worktrees.createAutoSyncJob(t.worktreeId,"FINALIZE",t.branch,(0,A.randomUUID)());await e.worktreeAutoSync.update({where:{worktreeId:t.worktreeId},data:{state:"SYNCING",activeJobId:i.id,workflowRunId:null,pauseReason:null}});continue}if(!t.activeJobId)throw Error("The Auto Sync job is missing");let i=await this.agentControl.getJob(t.activeJobId);if(!i||!n.has(i.status))continue;if("SUCCEEDED"!==i.status)throw Error(i.error||`Auto Sync ${i.status.toLowerCase()}`);let o=function(e){if(!e)return null;try{let A=JSON.parse(e);if(!A||"object"!=typeof A||Array.isArray(A))return null;return"string"==typeof A.outcome?String(A.outcome):null}catch{return null}}(i.resultJson);if("PREPARATION_CONFLICT"===o){let A=function(e){if(!e)return[];try{let A=JSON.parse(e);if(!A||"object"!=typeof A||Array.isArray(A))return[];let t=A.preparationConflictPaths;return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return[]}}(i.resultJson);await e.worktreeAutoSync.update({where:{worktreeId:t.worktreeId},data:{state:"PAUSED",activeJobId:null,workflowRunId:null,lastError:"Auto Sync paused because repository preparations block the rebase"+(A.length?`: ${A.join(", ")}`:""),pauseReason:"PREPARATION_CONFLICT"}});continue}if("CONFLICT"===o){if(!t.conflictWorkflowId){await e.worktreeAutoSync.update({where:{worktreeId:t.worktreeId},data:{state:"PAUSED",activeJobId:null,workflowRunId:null,lastError:"Auto Sync paused because the rebase has merge conflicts",pauseReason:"REBASE_CONFLICT"}});continue}let A=await this.workflows.trigger({workflowId:t.conflictWorkflowId,resourceKind:"WORKTREE",resourceId:t.worktreeId,subjectKey:`auto-sync:${t.worktreeId}:${i.id}`,choice:t.conflictWorkflowChoice});if(!A)throw Error("The conflict workflow did not start");await e.worktreeAutoSync.update({where:{worktreeId:t.worktreeId},data:{state:"RESOLVING",activeJobId:null,workflowRunId:A.id,lastError:null,pauseReason:null}});continue}if("UNRESOLVED"===o)throw Error("The conflict workflow did not fully resolve the rebase");if("SYNCED"!==o&&"NO_CHANGE"!==o)throw Error("The Auto Sync job returned an unknown result");await e.worktreeAutoSync.update({where:{worktreeId:t.worktreeId},data:{state:"ACTIVE",activeJobId:null,workflowRunId:null,lastError:null,pauseReason:null,..."SYNCED"===o?{lastSyncedAt:new Date}:{}}})}catch(n){let A=n instanceof Error?n.message:String(n),r=/offline|busy|already has an active job|temporarily/i.test(A),i=/branch changed/i.test(A)?"BRANCH_CHANGED":"ERROR";await e.worktreeAutoSync.updateMany({where:{worktreeId:t.worktreeId},data:{state:r?"ACTIVE":"PAUSED",activeJobId:null,workflowRunId:null,lastError:A,pauseReason:r?null:i}})}finally{this.worktrees.publishAutomationChange(t.worktreeId,t.worktree.codebaseId)}}async reconcileAutoMerge(){let e=await (0,r.getPrismaClient)();for(let t of(await e.worktreeAutoMerge.findMany({where:{state:{in:["ACTIVE","POST_MERGE"]}},include:{worktree:{select:{codebaseId:!0,branch:!0,headSha:!0,primary:!0}}}})))try{let r=o(t.repositoryNameWithOwner);if("ACTIVE"===t.state){let A=await this.github.pullRequestAutomationState(r.owner,r.name,t.pullRequestNumber);if("MERGED"===A.state)await e.worktreeAutoMerge.update({where:{worktreeId:t.worktreeId},data:{state:"POST_MERGE",lastError:null}}),this.rerunRequested=!0;else if("OPEN"!==A.state)throw Error("The pull request closed without merging");else if(!A.autoMergeEnabled)throw Error("GitHub Auto Merge is no longer enabled");continue}if(t.moveTicketToDone&&t.ticketKey&&!t.ticketMovedAt&&(await this.jira.transitionTicketToConfiguredDone(t.ticketKey),await e.worktreeAutoMerge.update({where:{worktreeId:t.worktreeId},data:{ticketMovedAt:new Date,lastError:null}})),!t.deleteWorktree){await e.worktreeAutoMerge.update({where:{worktreeId:t.worktreeId},data:{state:"COMPLETED",lastError:null}});continue}if(t.worktree.primary)throw Error("The primary worktree cannot be deleted");if(!t.deleteJobId){let i=await this.github.pullRequestAutomationState(r.owner,r.name,t.pullRequestNumber);if("MERGED"!==i.state)throw Error("The pull request is no longer merged");if(i.headRefName!==t.branch)throw Error("The merged pull request branch does not match the Auto Merge rule");if(t.worktree.branch!==t.branch)throw Error("The worktree branch changed after Auto Merge completed");if(!t.worktree.headSha||t.worktree.headSha!==i.headRefOid)throw Error("The worktree HEAD does not match the merged pull request");let n=await this.worktrees.deleteWorktree({worktreeId:t.worktreeId,deleteRemoteBranch:!1,requireClean:!0,expectedBranch:t.branch,expectedHeadSha:i.headRefOid,requestId:`auto-merge-${(0,A.randomUUID)()}`});await e.worktreeAutoMerge.update({where:{worktreeId:t.worktreeId},data:{deleteJobId:n.id,lastError:null}});continue}let i=await this.agentControl.getJob(t.deleteJobId);if(!i||!n.has(i.status))continue;if("SUCCEEDED"!==i.status)throw Error(i.error||`Worktree deletion ${i.status.toLowerCase()}`);await e.worktreeAutoMerge.updateMany({where:{worktreeId:t.worktreeId},data:{state:"COMPLETED",lastError:null}})}catch(A){await e.worktreeAutoMerge.updateMany({where:{worktreeId:t.worktreeId},data:{state:"ACTION_REQUIRED",lastError:A instanceof Error?A.message:String(A)}})}finally{this.worktrees.publishAutomationChange(t.worktreeId,t.worktree.codebaseId)}}}])},741193,e=>{"use strict";e.i(520962),e.i(374421),e.s([])},593464,e=>{"use strict";var A=e.i(666680),t=e.i(750227),r=e.i(904342),i=e.i(135475);e.i(256554);var n=e.i(848201);function a(e,A){let t=[],r=e.includes("CLAUDE");return r&&t.push("CLAUDE"),(e.includes("CODEX")||!r&&e.length>0||"GLOBAL"===A&&e.includes("GITHUB_COPILOT"))&&t.push("AGENTS"),t}let o="default",s=["PREPARING","READY","APPLYING","NEEDS_RESOLUTION"],l=["SCAN","READ"],d=[...l,"APPLY"],u={files:{orderBy:{path:"asc"}},groups:{include:{group:!0}}},c={skills:{include:{skill:{include:{files:!0}}}},repositories:{include:{repository:!0}}};function h(e,A){if(!e)return A;try{return JSON.parse(e)}catch{return A}}function g(e){return[...e.cursorEnabled?["CURSOR"]:[],...e.githubCopilotEnabled?["GITHUB_COPILOT"]:[],...e.codexEnabled?["CODEX"]:[],...e.claudeEnabled?["CLAUDE"]:[],...e.openCodeEnabled?["OPENCODE"]:[]]}function p(e,A){return"AGENTS"===A?[".agents","skills"]:"CLAUDE"===A?[".claude","skills"]:"GLOBAL"===e?"CURSOR"===A?[".cursor","skills"]:"GITHUB_COPILOT"===A?[".copilot","skills"]:"CODEX_LEGACY"===A?[".codex","skills"]:[".config","opencode","skills"]:"CURSOR"===A?[".cursor","skills"]:"GITHUB_COPILOT"===A?[".github","skills"]:"CODEX_LEGACY"===A?[".codex","skills"]:[".opencode","skills"]}function C(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")?t.win32:t.posix}function f(e,...A){return C(e).join(e,...A)}function I(e){return C(e).dirname(e)}e.s(["SkillsService",0,class{agentControl;constructor(e){this.agentControl=e,this.agentControl.registerCompletionHandler(r.SKILL_SCAN_JOB_KIND,e=>this.completeScan(e)),this.agentControl.registerCompletionHandler(r.SKILL_READ_JOB_KIND,e=>this.completeRead(e)),this.agentControl.registerCompletionHandler(r.SKILL_APPLY_JOB_KIND,e=>this.completeApply(e)),this.agentControl.registerConnectionHandler(async()=>{await this.requestAutoReconcile()})}publish(e){n.agentEventBus.publish(n.SKILLS_CHANGED_TOPIC,{id:e??null}),e&&n.agentEventBus.publish((0,n.skillSyncRunTopic)(e),{id:e})}subscribe(){return n.agentEventBus.iterate(n.SKILLS_CHANGED_TOPIC)}subscribeRun(e){return n.agentEventBus.iterate((0,n.skillSyncRunTopic)(e))}async settings(){return(await (0,i.getPrismaClient)()).skillSettings.upsert({where:{id:o},create:{id:o},update:{}})}async listSkills(e=""){let A=await (0,i.getPrismaClient)(),t=e.trim().toLocaleLowerCase(),r=await A.skill.findMany({where:{deletedAt:null},include:{groups:u.groups,files:{orderBy:{path:"asc"},omit:{contents:!0}}},orderBy:{name:"asc"}});return t?r.filter(e=>[e.name,e.description,...e.groups.map(({group:e})=>e.name)].some(e=>e.toLocaleLowerCase().includes(t))):r}async listGroups(){return(await (0,i.getPrismaClient)()).skillGroup.findMany({include:c,orderBy:{name:"asc"}})}async getGroup(e){return(await (0,i.getPrismaClient)()).skillGroup.findUnique({where:{id:e},include:c})}async observations(){return(await (0,i.getPrismaClient)()).skillToolObservation.findMany({include:{agent:!0},orderBy:[{tool:"asc"},{agent:{name:"asc"}}]})}async installations(e=""){let A=await (0,i.getPrismaClient)(),t=e.trim().toLocaleLowerCase(),r=await A.skillInstallation.findMany({where:{present:!0},include:{agent:!0,codebase:{include:{repository:!0}},worktree:!0,baseline:!0,skill:!0},orderBy:[{skillName:"asc"},{rootPath:"asc"}]});return t?r.filter(e=>[e.skillName,e.description,e.agent.name,e.rootPath,e.codebase?.repository.name??""].some(e=>e.toLocaleLowerCase().includes(t))):r}async repositories(){return(await (0,i.getPrismaClient)()).codebaseRepository.findMany({orderBy:{name:"asc"}})}async fileContents(e){let A=await (0,i.getPrismaClient)();return(await A.skillFile.findUniqueOrThrow({where:{id:e},select:{contents:!0}})).contents}async overview(e=""){let[A,t,r,i,n,a]=await Promise.all([this.listSkills(e),this.listGroups(),this.observations(),this.installations(e),this.settings(),this.repositories()]);return{skills:A,groups:t,observations:r,installations:i,settings:n,repositories:a}}async getSkill(e){return(await (0,i.getPrismaClient)()).skill.findFirst({where:{id:e,deletedAt:null},include:u})}async saveSkill(e){let t,n=(t=e.files.map(e=>({path:e.path,contentsBase64:e.contentsBase64,executable:e.executable})),(0,r.parseSkillPackage)({name:e.name,description:e.description,packageHash:(0,r.hashSkillFiles)(t),files:t})),a=[...new Set(e.groupIds)].slice(0,100),o=await (0,i.getPrismaClient)();if(await o.skillGroup.count({where:{id:{in:a}}})!==a.length)throw Error("One or more skill groups were not found");let s=await o.skill.findUnique({where:{name:n.name}});if(s&&s.id!==e.id)throw Error("Skill names must be unique");let l=e.id??(0,A.randomUUID)(),d=e.id?await o.skillGroupSkill.findMany({where:{skillId:l},select:{groupId:!0}}):[];return await o.$transaction(async t=>{await t.skill.upsert({where:{id:l},create:{id:l,name:n.name,description:n.description,syncGlobally:e.syncGlobally,packageHash:n.packageHash},update:{name:n.name,description:n.description,syncGlobally:e.syncGlobally,packageHash:n.packageHash,deletedAt:null}}),await t.skillFile.deleteMany({where:{skillId:l}}),await t.skillFile.createMany({data:n.files.map(e=>{let t=Buffer.from(e.contentsBase64,"base64");return{id:(0,A.randomUUID)(),skillId:l,path:e.path,contents:t,executable:e.executable,contentHash:(0,A.createHash)("sha256").update(t).digest("hex")}})}),await t.skillGroupSkill.deleteMany({where:{skillId:l}}),a.length&&await t.skillGroupSkill.createMany({data:a.map(e=>({groupId:e,skillId:l}))})}),this.publish(),await this.scheduleAutoSync([...a,...d.map(e=>e.groupId)]),await this.getSkill(l)}async deleteSkill(e){let A=await (0,i.getPrismaClient)(),t=await A.skill.findUnique({where:{id:e},include:{groups:!0}});return!!t&&(await A.skill.update({where:{id:e},data:{deletedAt:new Date}}),this.publish(),await this.scheduleAutoSync(t.groups.map(e=>e.groupId)),!0)}async saveGroup(e){let t=e.name.trim();if(!t||t.length>80)throw Error("Group names must contain 1-80 characters");let r=[...new Set(e.skillIds)].slice(0,500),n=[...new Set(e.repositoryIds)].slice(0,500),a=await (0,i.getPrismaClient)(),[o,s,l]=await Promise.all([a.skill.count({where:{id:{in:r},deletedAt:null}}),a.codebaseRepository.count({where:{id:{in:n}}}),a.skillGroup.findUnique({where:{name:t}})]);if(o!==r.length)throw Error("One or more skills were not found");if(s!==n.length)throw Error("One or more repositories were not found");if(l&&l.id!==e.id)throw Error("Group names must be unique");let d=e.id??(0,A.randomUUID)();return await a.$transaction(async e=>{await e.skillGroup.upsert({where:{id:d},create:{id:d,name:t},update:{name:t}}),await e.skillGroupSkill.deleteMany({where:{groupId:d}}),await e.codebaseRepositorySkillGroup.deleteMany({where:{groupId:d}}),r.length&&await e.skillGroupSkill.createMany({data:r.map(e=>({groupId:d,skillId:e}))}),n.length&&await e.codebaseRepositorySkillGroup.createMany({data:n.map(e=>({groupId:d,repositoryId:e}))})}),this.publish(),await this.scheduleAutoSync([d]),a.skillGroup.findUniqueOrThrow({where:{id:d},include:c})}async validateGroupIds(e){let A=[...new Set(e)].slice(0,100),t=await (0,i.getPrismaClient)();if(await t.skillGroup.count({where:{id:{in:A}}})!==A.length)throw Error("One or more skill groups were not found");return A}async groupsForRepository(e){let A=await (0,i.getPrismaClient)();return(await A.codebaseRepositorySkillGroup.findMany({where:{repositoryId:e},include:{group:!0},orderBy:{group:{name:"asc"}}})).map(e=>e.group)}async deleteGroup(e){let A=await (0,i.getPrismaClient)(),t=await A.skillGroup.deleteMany({where:{id:e}});return t.count&&this.publish(),t.count&&(await this.settings()).autoSyncProjectGroups&&await this.prepareSync("GROUP",null,!0),t.count>0}async saveSettings(e){let A=await (0,i.getPrismaClient)(),t=await A.skillSettings.upsert({where:{id:o},create:{id:o,...e},update:e});return this.publish(),t.autoSyncProjectGroups&&await this.prepareSync("GROUP",null,!0),t}async setRepositoryGroups(e,A){let t=await this.validateGroupIds(A),r=await (0,i.getPrismaClient)();await r.$transaction(async A=>{await A.codebaseRepositorySkillGroup.deleteMany({where:{repositoryId:e}}),t.length&&await A.codebaseRepositorySkillGroup.createMany({data:t.map(A=>({repositoryId:e,groupId:A}))})}),this.publish(),(await this.settings()).autoSyncProjectGroups&&await this.prepareSync("GROUP",null,!0)}async scheduleAutoSync(e){if((await this.settings()).autoSyncProjectGroups&&e.length)for(let A of[...new Set(e)])await this.prepareSync("GROUP",A,!0)}async requestAutoReconcile(){return(await this.settings()).autoSyncProjectGroups?this.prepareSync("GROUP",null,!0):null}async targets(e){let A=await (0,i.getPrismaClient)(),t=await A.codebase.findMany({where:{agentId:e,availability:"AVAILABLE"},include:{worktrees:{where:{missingAt:null}}}}),r=new Map;for(let e of t)for(let A of(r.set(e.folder,{codebaseId:e.id,worktreeId:null,folder:e.folder}),e.worktrees))r.set(A.folder,{codebaseId:e.id,worktreeId:A.id,folder:A.folder});return[...r.values()]}async prepareSync(e,t,n=!1){let a=await (0,i.getPrismaClient)();if(t&&!await a.skillGroup.findUnique({where:{id:t}}))throw Error("Skill group not found");if(n){let A=await a.skillSyncRun.findFirst({where:{kind:e,groupId:t??null,status:{in:s}},orderBy:{createdAt:"desc"}});if(A)return A}let o=await a.skillSyncRun.create({data:{id:(0,A.randomUUID)(),kind:e,groupId:t??null,automatic:n,status:"PREPARING"}}),l=g(await this.settings()),d=await a.agent.findMany({orderBy:{name:"asc"}});for(let e of d){let t=await a.skillSyncItem.create({data:{id:(0,A.randomUUID)(),runId:o.id,agentId:e.id,direction:"SCAN",status:"PENDING"}});await this.agentControl.createJob({agentId:e.id,kind:r.SKILL_SCAN_JOB_KIND,payload:{tools:l,targets:await this.targets(e.id),syncRunId:o.id,syncItemId:t.id},idempotencyKey:`skills:scan:${o.id}:${e.id}`,timeoutSeconds:300,visibility:n?"SYSTEM":"USER"})}return!d.length&&(await a.skillSyncRun.update({where:{id:o.id},data:{status:"READY"}}),n)?this.applyRun(o.id):(this.publish(o.id),this.getRun(o.id))}async getRun(e){return(await (0,i.getPrismaClient)()).skillSyncRun.findUnique({where:{id:e},include:{group:!0,items:{include:{skill:!0,installation:{include:{agent:!0}},agent:!0},orderBy:{createdAt:"asc"}}}})}completionIds(e){return h(e.payloadJson,{})}async completeScan(e){let{syncRunId:t,syncItemId:n}=this.completionIds(e);if(!t||!n)return;let a=await (0,i.getPrismaClient)();if(await a.skillSyncItem.findFirst({where:{id:n,runId:t,direction:"SCAN",status:"PENDING"}})){if("SUCCEEDED"===e.status&&e.resultJson){let t=h(e.resultJson,{configuredTools:[],installations:[],warnings:[]}),i=new Date;await a.$transaction(async a=>{for(let A of(await a.skillInstallation.updateMany({where:{agentId:e.agentId},data:{present:!1}}),t.configuredTools))r.AI_TOOLS.includes(A.tool)&&await a.skillToolObservation.upsert({where:{agentId_tool:{agentId:e.agentId,tool:A.tool}},create:{agentId:e.agentId,tool:A.tool,configured:A.configured,homePath:A.homePath,checkedAt:i},update:{configured:A.configured,homePath:A.homePath,checkedAt:i}});for(let r of t.installations){let t=await a.skill.findUnique({where:{name:r.skillName},select:{id:!0,deletedAt:!0}});await a.skillInstallation.upsert({where:{agentId_rootPath_skillName:{agentId:e.agentId,rootPath:r.rootPath,skillName:r.skillName}},create:{id:(0,A.randomUUID)(),agentId:e.agentId,skillId:t&&!t.deletedAt?t.id:null,codebaseId:r.codebaseId,worktreeId:r.worktreeId,scope:r.scope,rootKind:r.rootKind,rootPath:r.rootPath,skillName:r.skillName,description:r.description,packageHash:r.packageHash,present:!0,fileCount:r.fileCount,totalBytes:r.totalBytes,tracked:r.tracked,consumersJson:JSON.stringify(r.consumers),lastSeenAt:i},update:{skillId:t&&!t.deletedAt?t.id:void 0,codebaseId:r.codebaseId,worktreeId:r.worktreeId,scope:r.scope,rootKind:r.rootKind,description:r.description,packageHash:r.packageHash,present:!0,fileCount:r.fileCount,totalBytes:r.totalBytes,tracked:r.tracked,consumersJson:JSON.stringify(r.consumers),lastSeenAt:i}})}await a.skillSyncItem.updateMany({where:{id:n,status:"PENDING"},data:{status:"COMPLETE",error:t.warnings?.length?t.warnings.join("\n").slice(0,64e3):null}})})}else await a.skillSyncItem.updateMany({where:{id:n,status:"PENDING"},data:{status:"FAILED",error:e.error??"Skill scan failed"}});await a.skillSyncItem.count({where:{runId:t,direction:"SCAN",status:"PENDING"}})||await this.buildPlan(t),this.publish(t)}}async configuredByAgent(){let e=await (0,i.getPrismaClient)(),A=new Set(g(await this.settings())),t=await e.skillToolObservation.findMany({where:{configured:!0}}),r=new Map;for(let e of t){if(!A.has(e.tool))continue;let t=r.get(e.agentId)??[];t.push(e.tool),r.set(e.agentId,t)}return r}async desiredLocations(e,A=new Set){let t=await (0,i.getPrismaClient)(),r=await this.configuredByAgent(),n=await t.skillToolObservation.findMany({where:{configured:!0}}),o=new Map;for(let e of n)o.set(e.agentId,e.homePath);let s=[];if("ALL"===e.kind){let e=await t.skill.findMany({where:{deletedAt:null,syncGlobally:!0},include:u});for(let[t,i]of r){if(A.has(t))continue;let r=o.get(t);if(r)for(let A of a(i,"GLOBAL")){let i=f(r,...p("GLOBAL",A));for(let r of e)s.push({skill:r,agentId:t,codebaseId:null,worktreeId:null,scope:"GLOBAL",rootKind:A,folder:null,rootPath:i,targetPath:f(i,r.name)})}}}for(let i of(await t.skillGroup.findMany({where:"GROUP"===e.kind&&e.groupId?{id:e.groupId}:void 0,include:{skills:{where:{skill:{deletedAt:null}},include:{skill:{include:u}}},repositories:{include:{repository:{include:{codebases:{where:{availability:"AVAILABLE"},include:{worktrees:{where:{missingAt:null}}}}}}}}}})))for(let e of i.repositories)for(let t of e.repository.codebases){if(A.has(t.agentId))continue;let e=a(r.get(t.agentId)??[],"PROJECT");for(let A of[{folder:t.folder,worktreeId:null},...t.worktrees.map(e=>({folder:e.folder,worktreeId:e.id}))])for(let r of e){let e=f(A.folder,...p("PROJECT",r));for(let n of i.skills)s.push({skill:n.skill,agentId:t.agentId,codebaseId:t.id,worktreeId:A.worktreeId,scope:"PROJECT",rootKind:r,folder:A.folder,rootPath:e,targetPath:f(e,n.skill.name)})}}return[...new Map(s.map(e=>[`${e.agentId}\0${e.targetPath}`,e])).values()]}installationWhere(e,A){return{present:!0,...A.size?{agentId:{notIn:[...A]}}:{},..."GROUP"===e.kind?{scope:"PROJECT",...e.groupId?{codebase:{repository:{skillGroups:{some:{groupId:e.groupId}}}}}:{}}:{}}}async buildPlan(e){let t=await (0,i.getPrismaClient)(),n=await t.skillSyncRun.findUniqueOrThrow({where:{id:e}}),a=new Set((await t.skillSyncItem.findMany({where:{runId:e,direction:"SCAN",status:"SKIPPED"},select:{agentId:!0}})).flatMap(e=>e.agentId?[e.agentId]:[]));await t.skillSyncItem.deleteMany({where:{runId:e,direction:{not:"SCAN"}}});let[o,s,l,d,c]=await Promise.all([t.skill.findMany({where:{deletedAt:null},include:u}),t.skill.findMany({where:{deletedAt:{not:null}}}),t.skillInstallation.findMany({where:this.installationWhere(n,a),include:{baseline:!0}}),this.desiredLocations(n,a),"GROUP"===n.kind&&n.groupId?this.desiredLocations({...n,groupId:null},a):this.desiredLocations(n,a)]),h=new Map(o.map(e=>[e.name,e])),p=new Map(o.map(e=>[e.id,e])),C=new Map(s.map(e=>[e.name,e])),f=new Map(s.map(e=>[e.id,e])),I=new Map;for(let e of l){let A=I.get(e.skillName)??[];A.push(e.packageHash),I.set(e.skillName,A)}let w=new Set([...I].flatMap(([e,A])=>{var t;return(t=h.get(e)?.packageHash??null,new Set(A.filter(e=>null===t||e!==t)).size>1)?[e]:[]})),m=[];for(let t of d)l.find(e=>e.agentId===t.agentId&&e.rootPath===t.rootPath&&e.skillName===t.skill.name)||m.push({id:(0,A.randomUUID)(),runId:e,skillId:t.skill.id,agentId:t.agentId,direction:"EXPORT",status:"READY",sourceHash:t.skill.packageHash,candidatePackageJson:JSON.stringify({location:t})});for(let r of l){let i=r.baseline?.skillId??r.skillId,n=(i?p.get(i):void 0)??h.get(r.skillName),a=(i?f.get(i):void 0)??C.get(r.skillName),o=!!r.baseline&&!!n&&n.name!==r.skillName,s=d.find(e=>e.agentId===r.agentId&&e.rootPath===r.rootPath&&e.skill.name===r.skillName),l=c.find(e=>e.agentId===r.agentId&&e.rootPath===r.rootPath&&e.skill.name===r.skillName);n&&r.packageHash===n.packageHash&&!r.baseline&&await t.skillSyncBaseline.upsert({where:{installationId:r.id},create:{id:(0,A.randomUUID)(),installationId:r.id,skillId:n.id,packageHash:n.packageHash},update:{skillId:n.id,packageHash:n.packageHash,syncedAt:new Date}});let u="UNCHANGED",g="COMPLETE";if(a&&r.baseline&&!r.tracked)u="DELETE_MANAGED",g="READY";else if(o)u=r.tracked?"CONFLICT":"DELETE_MANAGED",g=r.tracked?"BLOCKED":"READY";else if(l||!r.baseline||r.tracked)if(n)if(r.packageHash!==n.packageHash){var E;g="CONFLICT"===(u=w.has(r.skillName)?"CONFLICT":(E={databaseHash:n.packageHash,targetHash:r.packageHash,baselineHash:r.baseline?.packageHash??null,tracked:r.tracked}).databaseHash===E.targetHash?"UNCHANGED":E.tracked?"CONFLICT":E.baselineHash===E.databaseHash?"IMPORT":E.baselineHash===E.targetHash?"EXPORT":"CONFLICT")?"BLOCKED":"READY"}else!l&&["CURSOR","GITHUB_COPILOT","CODEX_LEGACY","OPENCODE"].includes(r.rootKind)&&c.some(e=>e.agentId===r.agentId&&e.scope===r.scope&&("GLOBAL"===r.scope||e.codebaseId===r.codebaseId&&e.worktreeId===r.worktreeId)&&e.skill.name===r.skillName&&e.skill.packageHash===r.packageHash)&&!r.tracked&&(u="DELETE_REDUNDANT",g="READY");else g="CONFLICT"==(u=w.has(r.skillName)?"CONFLICT":"IMPORT")||"PROJECT"===r.scope?"BLOCKED":"READY";else u="DELETE_MANAGED",g="READY";m.push({id:(0,A.randomUUID)(),runId:e,skillId:n?.id??a?.id??null,installationId:r.id,agentId:r.agentId,direction:u,status:g,sourceHash:n?.packageHash??null,targetHash:r.packageHash,candidatePackageJson:JSON.stringify({location:{scope:r.scope,rootKind:r.rootKind,folder:"PROJECT"===r.scope?s?.folder??null:null,skillName:r.skillName},projectGroupRequired:!n&&"PROJECT"===r.scope})})}m.length&&await t.skillSyncItem.createMany({data:m});let y=await t.skillSyncItem.findMany({where:{runId:e,installationId:{not:null},direction:{in:["IMPORT","CONFLICT"]}},include:{installation:!0}}),B=new Map;for(let e of y){if(!e.agentId||!e.installation)continue;let A=B.get(e.agentId)??[];A.push(e),B.set(e.agentId,A)}let Q=g(await this.settings());for(let[i,n]of B){let a=await t.skillSyncItem.create({data:{id:(0,A.randomUUID)(),runId:e,agentId:i,direction:"READ",status:"PENDING"}}),o=await this.targets(i);await this.agentControl.createJob({agentId:i,kind:r.SKILL_READ_JOB_KIND,payload:{tools:Q,targets:o,requests:n.map(e=>({scope:e.installation.scope,rootKind:e.installation.rootKind,folder:"PROJECT"===e.installation.scope?o.find(A=>A.codebaseId===e.installation.codebaseId&&A.worktreeId===e.installation.worktreeId)?.folder??null:null,skillName:e.installation.skillName})),syncRunId:e,syncItemId:a.id},idempotencyKey:`skills:read:${e}:${i}`,timeoutSeconds:300})}await this.refreshRunStatus(e)}async completeRead(e){let{syncRunId:A,syncItemId:t}=this.completionIds(e);if(!A||!t)return;let r=await (0,i.getPrismaClient)();if(await r.skillSyncItem.findFirst({where:{id:t,runId:A,direction:"READ",status:"PENDING"}})){if("SUCCEEDED"===e.status&&e.resultJson){let i=h(e.resultJson,{packages:[]}),n=await r.skillSyncItem.findMany({where:{runId:A,agentId:e.agentId,installationId:{not:null},direction:{in:["IMPORT","CONFLICT"]}},include:{installation:!0}});for(let e of i.packages){let A=n.find(A=>A.installation?.skillName===e.package.name&&A.installation?.rootKind===e.rootKind&&A.installation?.scope===e.scope&&("GLOBAL"===e.scope||A.installation?.rootPath===f(e.folder,...p("PROJECT",e.rootKind))));if(!A)continue;let t=h(A.candidatePackageJson,{});await r.skillSyncItem.update({where:{id:A.id},data:{candidatePackageJson:JSON.stringify({...t,package:e.package})}})}await r.skillSyncItem.updateMany({where:{id:t,status:"PENDING"},data:{status:"COMPLETE"}})}else await r.skillSyncItem.updateMany({where:{id:t,status:"PENDING"},data:{status:"FAILED",error:e.error??"Skill package read failed"}});await this.refreshRunStatus(A),this.publish(A)}}async refreshRunStatus(e){let A=await (0,i.getPrismaClient)(),t=await A.skillSyncItem.findMany({where:{runId:e}});if(t.some(e=>l.includes(e.direction)&&"PENDING"===e.status))return;let r=t.some(e=>"BLOCKED"===e.status),n=t.some(e=>"FAILED"===e.status),a=r?"NEEDS_RESOLUTION":n?"PARTIAL":"READY",o=await A.skillSyncRun.update({where:{id:e},data:{status:a}});this.publish(e),o.automatic&&"READY"===a&&await this.applyRun(e)}async skipPending(e){let A=await (0,i.getPrismaClient)();await A.skillSyncRun.findUniqueOrThrow({where:{id:e}});let t=await A.skillSyncItem.findMany({where:{runId:e,direction:{in:d},status:"PENDING",agentId:{not:null}}}),r=[];for(let i of t){if(1!==(await A.skillSyncItem.updateMany({where:{id:i.id,status:"PENDING"},data:{status:"SKIPPED",resolution:"SKIP"}})).count||!i.agentId)continue;r.push(i);let t=await A.agentJob.findUnique({where:{agentId_idempotencyKey:{agentId:i.agentId,idempotencyKey:`skills:${i.direction.toLowerCase()}:${e}:${i.agentId}`}}});t&&await this.agentControl.cancelJob(t.id)}if(!r.length)return this.getRun(e);let n=[...new Set(r.flatMap(e=>"READ"===e.direction&&e.agentId?[e.agentId]:[]))];n.length&&await A.skillSyncItem.updateMany({where:{runId:e,agentId:{in:n},direction:{notIn:d},status:{in:["READY","BLOCKED"]}},data:{status:"SKIPPED",resolution:"SKIP"}});let a=r.filter(e=>"APPLY"===e.direction),o=a.flatMap(e=>{let{deployments:A=[]}=h(e.candidatePackageJson,{});return A.map(e=>e.id)});return o.length&&await A.skillDeployment.updateMany({where:{id:{in:o},status:"PENDING"},data:{status:"SKIPPED"}}),r.some(e=>"SCAN"===e.direction)?await A.skillSyncItem.count({where:{runId:e,direction:"SCAN",status:"PENDING"}})||await this.buildPlan(e):n.length&&await this.refreshRunStatus(e),a.length&&(await A.skillSyncItem.count({where:{runId:e,direction:"APPLY",status:"PENDING"}})||await A.skillSyncRun.update({where:{id:e},data:{status:"PARTIAL",finishedAt:new Date}})),this.publish(e),this.getRun(e)}async resolveItem(e){let A=await (0,i.getPrismaClient)(),t=await A.skillSyncItem.findUniqueOrThrow({where:{id:e.itemId}});if(!["BLOCKED","READY"].includes(t.status))throw Error("Sync item cannot be resolved");let n=h(t.candidatePackageJson,{});if("MANUAL"===e.resolution&&(n.package=(0,r.parseSkillPackage)(e.package,"manual resolution package")),"TARGET"===e.resolution&&!n.package)throw Error("The target package is unavailable");if("DELETE"===e.resolution&&!t.installationId)throw Error("The client skill installation is unavailable");if(n.projectGroupRequired&&["TARGET","MANUAL"].includes(e.resolution)){if(!e.groupId||!await A.skillGroup.findUnique({where:{id:e.groupId}}))throw Error("A project skill import requires a skill group");n.groupId=e.groupId}if(await A.skillSyncItem.update({where:{id:t.id},data:{resolution:e.resolution,direction:"DELETE"===e.resolution?"DELETE_REDUNDANT":t.direction,candidatePackageJson:JSON.stringify(n),status:"SKIP"===e.resolution?"SKIPPED":"READY"}}),["TARGET","MANUAL"].includes(e.resolution)){let e=n.package?.name??null;if(e){let r=(await A.skillSyncItem.findMany({where:{runId:t.runId,id:{not:t.id},direction:"CONFLICT",status:{in:["BLOCKED","READY"]}},include:{skill:!0,installation:!0}})).flatMap(A=>(A.skill?.name??A.installation?.skillName)===e?[A.id]:[]);r.length&&await A.skillSyncItem.updateMany({where:{id:{in:r}},data:{resolution:"DATABASE",status:"READY"}})}}return await this.refreshRunStatus(t.runId),this.getRun(t.runId)}async importCandidates(e){let t=await (0,i.getPrismaClient)();for(let r of(await t.skillSyncItem.findMany({where:{runId:e,status:"READY",OR:[{direction:"IMPORT"},{direction:"CONFLICT",resolution:{in:["TARGET","MANUAL"]}}]},include:{installation:!0}}))){let e=h(r.candidatePackageJson,{});if(!e.package)continue;let i=await t.skill.findUnique({where:{name:e.package.name},include:u}),n=await this.saveSkill({id:i?.id,name:e.package.name,description:e.package.description,syncGlobally:i?.syncGlobally??!e.groupId,groupIds:[...i?.groups.map(e=>e.groupId)??[],...e.groupId?[e.groupId]:[]],files:e.package.files});r.installationId&&(await t.skillInstallation.update({where:{id:r.installationId},data:{skillId:n.id}}),r.targetHash===n.packageHash&&await t.skillSyncBaseline.upsert({where:{installationId:r.installationId},create:{id:(0,A.randomUUID)(),installationId:r.installationId,skillId:n.id,packageHash:n.packageHash},update:{skillId:n.id,packageHash:n.packageHash,syncedAt:new Date}}))}}async applyRun(e){let t=await (0,i.getPrismaClient)(),n=await t.skillSyncRun.findUniqueOrThrow({where:{id:e}});if(await t.skillSyncItem.count({where:{runId:e,status:"BLOCKED"}}))throw Error("Resolve all conflicts before applying sync");await this.importCandidates(e);let a=new Set((await t.skillSyncItem.findMany({where:{runId:e,direction:{in:l},status:"SKIPPED"},select:{agentId:!0}})).flatMap(e=>e.agentId?[e.agentId]:[])),o=await this.desiredLocations(n,a),s=await t.skillInstallation.findMany({where:this.installationWhere(n,a)}),d=new Map,u=new Map,c=(e,A)=>{let t=d.get(e)??[];t.push(A),d.set(e,t)},h=(e,A)=>{let t=u.get(e)??[];t.push(A),u.set(e,t)};for(let e of o){let r=s.find(A=>A.agentId===e.agentId&&A.rootPath===e.rootPath&&A.skillName===e.skill.name);if(r?.packageHash===e.skill.packageHash||r?.tracked)continue;c(e.agentId,{kind:"WRITE",scope:e.scope,rootKind:e.rootKind,folder:e.folder,package:function(e){let A=e.files.map(e=>({path:e.path,contentsBase64:Buffer.from(e.contents).toString("base64"),executable:e.executable}));return{name:e.name,description:e.description,packageHash:e.packageHash,files:A}}(e.skill),manageGitExclude:"PROJECT"===e.scope});let i=await t.skillDeployment.upsert({where:{agentId_targetPath:{agentId:e.agentId,targetPath:e.targetPath}},create:{id:(0,A.randomUUID)(),skillId:e.skill.id,agentId:e.agentId,codebaseId:e.codebaseId,worktreeId:e.worktreeId,scope:e.scope,rootKind:e.rootKind,targetPath:e.targetPath,desiredHash:e.skill.packageHash,status:"PENDING"},update:{skillId:e.skill.id,desiredHash:e.skill.packageHash,status:"PENDING",lastError:null}});h(e.agentId,{id:i.id,desiredHash:e.skill.packageHash})}let g=await t.skillSyncItem.findMany({where:{runId:e,direction:{in:["DELETE_REDUNDANT","DELETE_MANAGED"]},status:"READY"},include:{installation:!0}}),p=new Set(g.flatMap(e=>e.installationId?[e.installationId]:[])),C=s.filter(e=>!p.has(e.id)&&!e.tracked&&["CURSOR","GITHUB_COPILOT","CODEX_LEGACY","OPENCODE"].includes(e.rootKind)&&!o.some(A=>A.agentId===e.agentId&&A.rootPath===e.rootPath&&A.skill.name===e.skillName)&&o.some(A=>A.agentId===e.agentId&&A.scope===e.scope&&("GLOBAL"===e.scope||A.codebaseId===e.codebaseId&&A.worktreeId===e.worktreeId)&&A.skill.name===e.skillName&&A.skill.packageHash===e.packageHash));for(let e of[...g.flatMap(e=>e.installation?[e.installation]:[]),...C]){if(!e||e.tracked)continue;let A=await this.targets(e.agentId),t="PROJECT"===e.scope?A.find(A=>A.codebaseId===e.codebaseId&&A.worktreeId===e.worktreeId)?.folder??null:null;("PROJECT"!==e.scope||t)&&c(e.agentId,{kind:"DELETE",scope:e.scope,rootKind:e.rootKind,folder:t,skillName:e.skillName,manageGitExclude:"PROJECT"===e.scope})}for(let[i,n]of d){let a=await t.skillSyncItem.create({data:{id:(0,A.randomUUID)(),runId:e,agentId:i,direction:"APPLY",status:"PENDING",candidatePackageJson:JSON.stringify({deployments:u.get(i)??[]})}});await this.agentControl.createJob({agentId:i,kind:r.SKILL_APPLY_JOB_KIND,payload:{operations:n,syncRunId:e,syncItemId:a.id},idempotencyKey:`skills:apply:${e}:${i}`,timeoutSeconds:600})}return await t.skillSyncRun.update({where:{id:e},data:d.size?{status:"APPLYING"}:{status:"SUCCEEDED",finishedAt:new Date}}),this.publish(e),this.getRun(e)}async completeApply(e){let{syncRunId:t,syncItemId:r}=this.completionIds(e);if(!t||!r)return;let n=await (0,i.getPrismaClient)(),a=await n.skillSyncItem.findFirst({where:{id:r,runId:t,direction:"APPLY",status:"PENDING"}});if(!a)return;let o="SUCCEEDED"===e.status,{deployments:s=[]}=h(a?.candidatePackageJson??null,{});await n.skillSyncItem.updateMany({where:{id:r,status:"PENDING"},data:{status:o?"COMPLETE":"FAILED",error:o?null:e.error??"Skill apply failed"}});let l=await n.skillDeployment.findMany({where:{id:{in:s.map(e=>e.id)},agentId:e.agentId,status:"PENDING"},include:{skill:{include:{files:!0}}}}),d=h(e.resultJson,{});if(o){let t=await this.configuredByAgent();for(let e of l){let r=s.find(A=>A.id===e.id),i=d.results?.find(A=>"WRITE"===A.kind&&A.path===e.targetPath);if(!r||e.desiredHash!==r.desiredHash||i?.packageHash!==r.desiredHash)continue;let a=await n.skillInstallation.upsert({where:{agentId_rootPath_skillName:{agentId:e.agentId,rootPath:I(e.targetPath),skillName:e.skill.name}},create:{id:(0,A.randomUUID)(),skillId:e.skillId,agentId:e.agentId,codebaseId:e.codebaseId,worktreeId:e.worktreeId,scope:e.scope,rootKind:e.rootKind,rootPath:I(e.targetPath),skillName:e.skill.name,description:e.skill.description,packageHash:e.desiredHash,present:!0,fileCount:e.skill.files.length,totalBytes:e.skill.files.reduce((e,A)=>e+A.contents.byteLength,0),tracked:!1,consumersJson:JSON.stringify(t.get(e.agentId)??[]),lastSeenAt:new Date},update:{skillId:e.skillId,codebaseId:e.codebaseId,worktreeId:e.worktreeId,scope:e.scope,rootKind:e.rootKind,description:e.skill.description,packageHash:e.desiredHash,present:!0,fileCount:e.skill.files.length,totalBytes:e.skill.files.reduce((e,A)=>e+A.contents.byteLength,0),tracked:!1,consumersJson:JSON.stringify(t.get(e.agentId)??[]),lastSeenAt:new Date}});await n.skillSyncBaseline.upsert({where:{installationId:a.id},create:{id:(0,A.randomUUID)(),installationId:a.id,skillId:e.skillId,packageHash:e.desiredHash},update:{skillId:e.skillId,packageHash:e.desiredHash,syncedAt:new Date}}),await n.skillDeployment.update({where:{id:e.id},data:{status:"INSTALLED",installedHash:e.desiredHash,lastError:null}})}for(let A of d.results??[])if("DELETE"===A.kind){var u;await n.skillInstallation.updateMany({where:{agentId:e.agentId,rootPath:I(A.path),skillName:C(u=A.path).basename(u)},data:{present:!1,lastSeenAt:new Date}})}}else for(let A of s)await n.skillDeployment.updateMany({where:{id:A.id,agentId:e.agentId,desiredHash:A.desiredHash,status:"PENDING"},data:{status:"FAILED",lastError:e.error??"Skill apply failed"}});if(!await n.skillSyncItem.count({where:{runId:t,direction:"APPLY",status:"PENDING"}})){let e=await n.skillSyncItem.count({where:{runId:t,direction:"APPLY",status:{in:["FAILED","SKIPPED"]}}});await n.skillSyncRun.update({where:{id:t},data:{status:e?"PARTIAL":"SUCCEEDED",finishedAt:new Date}})}this.publish(t)}}],593464)},333329,e=>{"use strict";e.i(593464),e.s([])},412150,142897,553434,e=>{"use strict";var A=e.i(374186);let t=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function r(e){return function e(A){return null===A?"null":Array.isArray(A)?`[${A.map(e).join(",")}]`:"object"==typeof A?`{${Object.entries(A).sort(([e],[A])=>e.localeCompare(A)).map(([A,t])=>`${JSON.stringify(A)}:${e(t)}`).join(",")}}`:JSON.stringify(A)}(e)}function i(e){return t.test(e)?`.${e}`:`[${JSON.stringify(e)}]`}function n(e,A){let t={},r=(e,A)=>{if(A&&"object"==typeof A&&!Array.isArray(A)&&Object.getPrototypeOf(A)===Object.prototype){let n=Object.entries(A);if(0===n.length)t[e]=A;else for(let[A,t]of n)r(`${e}${i(A)}`,t)}else t[e]=A};for(let[t,n]of Object.entries(A))r(`${e}${i(t)}`,n);return t}function a(e){let A={default:e.defaultParameters,additional:e.additionalParameters};return{...{source:e.entryType,time:e.clientTime,receivedAt:e.receivedAt,deviceIp:e.deviceIp,message:e.message,level:e.level,category:e.category,eventName:e.eventName,eventKind:e.eventKind,levelKind:e.level??e.eventKind,screenName:e.screenName,buildId:e.buildId,sessionId:e.sessionId,attributes:e.attributes,defaultParameters:e.defaultParameters,additionalParameters:e.additionalParameters,parameters:A,detail:"CONSOLE"===e.entryType?e.message:`${e.eventName??""}${e.screenName?` (${e.screenName})`:""}`},...n("attributes",e.attributes),...n("defaultParameters",e.defaultParameters),...n("additionalParameters",e.additionalParameters)}}function o(e){return null==e?"":"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e?String(e):r(e)}function s(e){return Object.entries(a(e)).flatMap(([e,A])=>[e,o(A)]).join("\n")}e.s(["stableJson",0,r,"telemetryDisplay",0,o,"telemetryFields",0,a,"telemetrySearchText",0,s],142897);let l=["TEXT","GLOB","REGEX"],d=["CONTAINS","DOES_NOT_CONTAIN","IS","IS_NOT","MATCHES_GLOB","MATCHES_REGEX","NO_REGEX_MATCH","IS_EMPTY","IS_NOT_EMPTY"];e.s(["DEFAULT_TELEMETRY_COLUMNS",0,{CONSOLE:["time","level","category","message","buildId","sessionId"],ANALYTICS:["time","eventKind","eventName","screenName","parameters","buildId","sessionId"],UNIFIED:["time","source","levelKind","detail","buildId","sessionId"]},"TELEMETRY_COLORS",0,["gray","stone","red","rose","orange","amber","yellow","lime","green","emerald","teal","cyan","sky","blue","indigo","violet","purple","fuchsia","pink"],"TELEMETRY_FILTER_OPERATORS",0,d,"TELEMETRY_SEARCH_MODES",0,l,"TELEMETRY_VIEWS",0,["CONSOLE","ANALYTICS","UNIFIED"]],553434);let u=new Map;function c(e,t,r){let i;if(t.length>1024)throw Error("Pattern must not exceed 1024 characters");if(!l.includes(e))throw Error("Unknown search mode");let n=`${e}\u0000${r?"1":"0"}\u0000${t}`,a=u.get(n);if(a)return a;if("TEXT"===e){let e=r?t:t.toLocaleLowerCase();i=A=>(r?A:A.toLocaleLowerCase()).includes(e)}else{let n="GLOB"===e?`^${function(e){let A="";for(let t=0;t<e.length;t+=1){let r=e[t];if("*"===r)A+=".*";else if("?"===r)A+=".";else if("["===r){let r=e.indexOf("]",t+1);if(-1===r)throw Error("Invalid glob pattern: missing ]");{let i=e.slice(t+1,r).replace(/^!/,"^");A+=`[${i}]`,t=r}}else A+=r.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&")}return A}(t)}$`:t,a=new A.default(n,r?"su":"isu");i=e=>a.test(e)}return u.set(n,i),u.size>100&&u.delete(u.keys().next().value),i}function h(e){return null==e||""===e||Array.isArray(e)&&0===e.length||"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length}function g(e){return"CONSOLE"===e?["CONSOLE"]:"ANALYTICS"===e?["ANALYTICS"]:["CONSOLE","ANALYTICS"]}e.s(["fieldsForFacet",0,function(e){return a(e)},"matchesTelemetryQuery",0,function(e,A){return"SEPARATOR"!==e.entryType&&!!g(A.view).includes(e.entryType)&&(!A.search||!!c(A.searchMode??"TEXT",A.search,!0===A.caseSensitive)(s(e)))&&function(e,A){if(!A)return!0;let t=a(e);return Object.entries(A).every(([e,A])=>0===A.length||A.includes(o(t[e])))}(e,A.quickFilters)&&function(e,A){if(!A?.conditions.length)return!0;let t=A.conditions.filter(A=>!A.sources?.length||"SEPARATOR"!==e.entryType&&A.sources.includes(e.entryType));if(0===t.length)return!0;let r=a(e),i=t.map(e=>(function(e,A){if(!d.includes(A.operator))throw Error("Unknown filter operator");let t=e[A.field];if("IS_EMPTY"===A.operator)return h(t);if("IS_NOT_EMPTY"===A.operator)return!h(t);let r=o(t),i=A.value??"",n=!0===A.caseSensitive,a=n?r:r.toLocaleLowerCase(),s=n?i:i.toLocaleLowerCase();if("CONTAINS"===A.operator)return a.includes(s);if("DOES_NOT_CONTAIN"===A.operator)return!a.includes(s);if("IS"===A.operator)return a===s;if("IS_NOT"===A.operator)return a!==s;if("MATCHES_GLOB"===A.operator)return c("GLOB",i,n)(r);let l=c("REGEX",i,n)(r);return"MATCHES_REGEX"===A.operator?l:!l})(r,e));return"ANY"===A.mode?i.some(Boolean):i.every(Boolean)}(e,A.advancedFilter)},"sourcesForView",0,g,"validateTelemetryQuery",0,function(e){for(let A of(e.search&&c(e.searchMode??"TEXT",e.search,!0===e.caseSensitive),e.advancedFilter?.conditions??[]))["MATCHES_GLOB","MATCHES_REGEX","NO_REGEX_MATCH"].includes(A.operator)&&c("MATCHES_GLOB"===A.operator?"GLOB":"REGEX",A.value??"",!0===A.caseSensitive)}],412150)},342572,e=>{"use strict";var A=e.i(794231),t=e.i(666680),r=e.i(135475);e.i(256554);var i=e.i(848201),n=e.i(660526),a=e.i(412150),o=e.i(142897),s=e.i(553434);let l="default";function d(e){try{let A=JSON.parse(e);return A&&"object"==typeof A&&!Array.isArray(A)?A:{}}catch{return{}}}function u(e){return{id:e.id,entryType:e.entryType,clientTime:e.clientTime.toISOString(),receivedAt:e.receivedAt.toISOString(),deviceIp:e.deviceIp,message:e.message,level:e.level,category:e.category,eventName:e.eventName,eventKind:e.eventKind,screenName:e.screenName,buildId:e.buildId,sessionId:e.sessionId,attributes:d(e.attributesJson),defaultParameters:d(e.defaultParametersJson),additionalParameters:d(e.additionalParametersJson),highlightColor:e.highlightColor,separatorKind:e.separatorKind,separatorName:e.separatorName}}function c(e){if(!s.TELEMETRY_VIEWS.includes(e))throw Error("Unknown telemetry view");return e}function h(e){let A=e.trim();if(!A||A.length>100)throw Error("Name must contain 1-100 characters");return{name:A,normalizedName:A.toLocaleLowerCase()}}function g(e){let A;try{A=new URL(e.trim())}catch{throw Error("Telemetry URL must be a valid HTTP(S) origin")}if(!["http:","https:"].includes(A.protocol)||A.username||A.password||"/"!==A.pathname&&""!==A.pathname||A.search||A.hash)throw Error("Telemetry URL must be an HTTP(S) origin without a path, credentials, query, or fragment");return A.origin}function p(e){return e?.trim()?g(e):null}function C(e){if(!e?.trim())return null;try{let A=new URL(e.trim());return["http:","https:"].includes(A.protocol)?A.origin:null}catch{return null}}function f(e){if(!e)return null;try{let A=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));if(A&&"object"==typeof A&&"string"==typeof A.clientTime&&"string"==typeof A.receivedAt&&"string"==typeof A.id&&Number.isFinite(Date.parse(A.clientTime))&&Number.isFinite(Date.parse(A.receivedAt)))return A}catch{}throw Error("Invalid telemetry cursor")}function I(e){let A=new Date(e.clientTime),t=new Date(e.receivedAt);return{OR:[{clientTime:{lt:A}},{clientTime:A,receivedAt:{lt:t}},{clientTime:A,receivedAt:t,id:{lt:e.id}}]}}function w(e){return Buffer.from(JSON.stringify({clientTime:e.clientTime,receivedAt:e.receivedAt,id:e.id})).toString("base64url")}function m(e,A){return e.clientTime!==A.clientTime?e.clientTime<A.clientTime:e.receivedAt!==A.receivedAt?e.receivedAt<A.receivedAt:e.id<A.id}function E(e){return!!(e.search||Object.values(e.quickFilters??{}).some(e=>e.length)||e.advancedFilter?.conditions.length)}function y(e){return{entryType:{in:(0,a.sourcesForView)(e)}}}let B={source:{name:"entryType",nullable:!1},deviceIp:{name:"deviceIp",nullable:!0},message:{name:"message",nullable:!0},level:{name:"level",nullable:!0},category:{name:"category",nullable:!0},eventName:{name:"eventName",nullable:!0},eventKind:{name:"eventKind",nullable:!0},screenName:{name:"screenName",nullable:!0},buildId:{name:"buildId",nullable:!0},sessionId:{name:"sessionId",nullable:!0}};function Q(e){let A=[...new Set(e.map(e=>e.trim()).filter(Boolean))];if(0===A.length||A.length>100||A.some(e=>e.length>512))throw Error("Columns must contain 1-100 valid column identifiers");return JSON.stringify(A)}function D(e,A){try{let A=JSON.parse(e);if(Array.isArray(A)&&A.every(e=>"string"==typeof e)&&A.length)return A}catch{}return s.DEFAULT_TELEMETRY_COLUMNS[A]}e.s(["TelemetryService",0,class{subscribe(e){let t=i.agentEventBus.iterate(i.TELEMETRY_CHANGED_TOPIC);return e?(0,A.filterAsyncIterator)(t,A=>!A.views||A.views.includes(e)):t}subscribeSettings(){return i.agentEventBus.iterate(i.TELEMETRY_SETTINGS_CHANGED_TOPIC)}publish(e,A,t){i.agentEventBus.publish(i.TELEMETRY_CHANGED_TOPIC,{ids:e,reason:A,...t?{views:t}:{}})}notifyChange(e,A){this.publish(e,A)}async rawSettings(){return(await (0,r.getPrismaClient)()).telemetrySettings.upsert({where:{id:l},create:{id:l},update:{}})}async settings(e={}){let[A,t]=await Promise.all([this.rawSettings(),Promise.resolve(function(e={}){let A,t=C(e.requestOrigin),r=(e.localOrigins??function(){let e=Number(process.env.PORT??3e3),A=Number.isInteger(e)&&e>0&&e<=65535?e:3e3;var t=(0,n.networkInterfaces)();let r=new Set;for(let e of Object.values(t))for(let t of e??[])t&&!t.internal&&("IPv4"===t.family?r.add(`http://${t.address}:${A}`):"IPv6"!==t.family||t.address.toLowerCase().startsWith("fe80:")||r.add(`http://[${t.address}]:${A}`));return[...r]}()).flatMap(e=>{try{return[g(e)]}catch{return[]}}),i=C(e.publicBaseUrl??process.env.PUBLIC_BASE_URL),a=!!t&&("localhost"===(A=new URL(t).hostname.toLowerCase().replace(/^\[|\]$/g,""))||"::1"===A||A.endsWith(".local")||/^127\./.test(A)||/^10\./.test(A)||/^192\.168\./.test(A)||/^172\.(1[6-9]|2\d|3[01])\./.test(A)),o=t&&a?t:r[0]??t??"http://127.0.0.1:3000",s=i??t??o;return{local:o,remote:s}}(e))]);return{localBaseUrlOverride:A.localBaseUrlOverride,remoteBaseUrlOverride:A.remoteBaseUrlOverride,consoleCollectionEnabled:A.consoleCollectionEnabled,analyticsCollectionEnabled:A.analyticsCollectionEnabled,detectedLocalBaseUrl:t.local,detectedRemoteBaseUrl:t.remote,effectiveLocalBaseUrl:A.localBaseUrlOverride??t.local,effectiveRemoteBaseUrl:A.remoteBaseUrlOverride??t.remote,updatedAt:A.updatedAt.toISOString()}}async saveSettings(e,A={}){let t=await (0,r.getPrismaClient)(),n=await this.rawSettings(),a=await t.telemetrySettings.update({where:{id:l},data:{localBaseUrlOverride:void 0===e.localBaseUrlOverride?n.localBaseUrlOverride:p(e.localBaseUrlOverride),remoteBaseUrlOverride:void 0===e.remoteBaseUrlOverride?n.remoteBaseUrlOverride:p(e.remoteBaseUrlOverride),consoleCollectionEnabled:e.consoleCollectionEnabled??n.consoleCollectionEnabled,analyticsCollectionEnabled:e.analyticsCollectionEnabled??n.analyticsCollectionEnabled}});return i.agentEventBus.publish(i.TELEMETRY_SETTINGS_CHANGED_TOPIC,{updatedAt:a.updatedAt.toISOString()}),this.settings(A)}async buildSettings(e,A={}){let t=await this.settings(A),r="SIMULATOR"===e?t.effectiveLocalBaseUrl:t.effectiveRemoteBaseUrl;return{localBaseUrl:t.effectiveLocalBaseUrl,remoteBaseUrl:t.effectiveRemoteBaseUrl,selectedBaseUrl:r,consoleLogsUrl:`${r}/api/telemetry/console-logs`,analyticsEventsUrl:`${r}/api/telemetry/analytics-events`,consoleCollectionEnabled:t.consoleCollectionEnabled,analyticsCollectionEnabled:t.analyticsCollectionEnabled}}async ingestConsole(e,A){if(!(await this.rawSettings()).consoleCollectionEnabled)return{collected:!1,items:[]};let i=await (0,r.getPrismaClient)(),n=new Date,a=e.map(e=>{let r={id:(0,t.randomUUID)(),entryType:"CONSOLE",clientTime:new Date(e.time),receivedAt:n,deviceIp:A,message:e.message,level:e.level,category:e.category,buildId:e.buildId,sessionId:e.sessionId,attributesJson:JSON.stringify(e.attributes),searchText:""},i=u({...r,eventName:null,eventKind:null,screenName:null,defaultParametersJson:"{}",additionalParametersJson:"{}",highlightColor:null,separatorKind:null,separatorName:null});return{...r,searchText:(0,o.telemetrySearchText)(i)}});return await i.telemetryEntry.createMany({data:a}),this.publish(a.map(({id:e})=>e),"INGESTED",["CONSOLE","UNIFIED"]),{collected:!0,items:a.map(({id:e})=>({id:e,receivedAt:n.toISOString(),deviceIp:A}))}}async ingestAnalytics(e,A){if(!(await this.rawSettings()).analyticsCollectionEnabled)return{collected:!1,items:[]};let i=await (0,r.getPrismaClient)(),n=new Date,a=e.map(e=>{let r={id:(0,t.randomUUID)(),entryType:"ANALYTICS",clientTime:new Date(e.time),receivedAt:n,deviceIp:A,eventName:e.eventName,eventKind:e.kind,screenName:e.screenName,buildId:e.buildId,sessionId:e.sessionId,defaultParametersJson:JSON.stringify(e.defaultParameters),additionalParametersJson:JSON.stringify(e.additionalParameters),searchText:""},i=u({...r,message:null,level:null,category:null,attributesJson:"{}",highlightColor:null,separatorKind:null,separatorName:null});return{...r,searchText:(0,o.telemetrySearchText)(i)}});return await i.telemetryEntry.createMany({data:a}),this.publish(a.map(({id:e})=>e),"INGESTED",["ANALYTICS","UNIFIED"]),{collected:!0,items:a.map(({id:e})=>({id:e,receivedAt:n.toISOString(),deviceIp:A}))}}async scan(e,A,t=1e3){let i=await (0,r.getPrismaClient)(),n=null;for(;;){let r=await i.telemetryEntry.findMany({where:n?{AND:[e,{OR:[{clientTime:{lt:n.clientTime}},{clientTime:n.clientTime,receivedAt:{lt:n.receivedAt}},{clientTime:n.clientTime,receivedAt:n.receivedAt,id:{lt:n.id}}]}]}:e,orderBy:[{clientTime:"desc"},{receivedAt:"desc"},{id:"desc"}],take:t});for(let e of r)if(await A(u(e))===!1)return;if(r.length<t)break;n=r.at(-1)}}async timeline(e){let A=c(e.view);(0,a.validateTelemetryQuery)(e);let t=Math.min(500,Math.max(1,e.first??200)),i=f(e.after),n=await (0,r.getPrismaClient)(),o=await n.telemetryEntry.count({where:y(A)}),s=E(e);if(!s){let e=[],r=0,n=!1,s=null,l=!1,d={entryType:{in:[...(0,a.sourcesForView)(A),"SEPARATOR"]}};return(await this.scan(i?{AND:[d,I(i)]}:d,A=>{if("SEPARATOR"===A.entryType){l&&e.push(A),l=!1;return}if(r<t){e.push(A),r+=1,s=A,l=!0;return}return n=!0,!1},Math.min(1e3,t+1)),s)?{items:e,nextCursor:n?w(s):null,matchingCount:o,totalCount:o}:{items:[],nextCursor:null,matchingCount:o,totalCount:o}}let l=[],d=0,u=!1,h=0,g=null,p=!1,C=!1,Q=function(e){let A=[];for(let[t,r]of(e.search&&(e.searchMode??"TEXT")==="TEXT"&&!0===e.caseSensitive&&A.push({searchText:{contains:e.search}}),Object.entries(e.quickFilters??{}))){if(!r.length)continue;let e=B[t];if(!e)continue;let i=function(e,A){let t=[...new Set(A)],r=t.filter(Boolean),i=[];return(r.length&&i.push({[e.name]:{in:r}}),t.includes("")&&(i.push({[e.name]:""}),e.nullable&&i.push({[e.name]:null})),0===i.length)?null:1===i.length?i[0]:{OR:i}}(e,r);i&&A.push(i)}if(e.advancedFilter?.mode==="ALL")for(let t of e.advancedFilter.conditions){if(t.sources?.length||!0!==t.caseSensitive)continue;let e=B[t.field],r=t.value??"";e&&r&&("IS"===t.operator?A.push({[e.name]:r}):"CONTAINS"===t.operator&&A.push({[e.name]:{contains:r}}))}return A.length?1===A.length?A[0]:{AND:A}:null}(e);return(await this.scan(Q?{OR:[{entryType:"SEPARATOR"},{AND:[y(A),Q]}]}:{entryType:{in:[...(0,a.sourcesForView)(A),"SEPARATOR"]}},A=>{if("SEPARATOR"===A.entryType){(!i||m(A,i))&&(!s&&!u||s&&p&&!C)&&l.push(A),p=!1,C=!1;return}!(0,a.matchesTelemetryQuery)(A,e)||(d+=1,(!i||m(A,i))&&(h<t?(l.push(A),h+=1,g=A,p=!0):(u=!0,C=!0)))}),g)?{items:l,nextCursor:u?w(g):null,matchingCount:d,totalCount:o}:{items:[],nextCursor:null,matchingCount:d,totalCount:o}}async entries(e){let A=await (0,r.getPrismaClient)(),t=[...new Set(e)].slice(0,1e3);return(await A.telemetryEntry.findMany({where:{id:{in:t}}})).map(u)}async entry(e,A){let t=c(A),r=(await this.entries([e]))[0]??null;if(!r)return null;if("SEPARATOR"===r.entryType||!(0,a.sourcesForView)(t).includes(r.entryType))throw Error(`Telemetry entry ${e} does not belong to ${t}`);return r}async latestSeparator(){let e=await (0,r.getPrismaClient)(),A=await e.telemetryEntry.findFirst({where:{entryType:"SEPARATOR"},orderBy:[{clientTime:"desc"},{receivedAt:"desc"},{id:"desc"}]});return A?u(A):null}async separators(e){let A=Math.min(500,Math.max(1,e.first??100)),t=f(e.after),i=[{entryType:"SEPARATOR"}];e.kind?.trim()&&i.push({separatorKind:e.kind.trim()}),e.name?.trim()&&i.push({separatorName:{contains:e.name.trim()}}),e.buildId?.trim()&&i.push({buildId:e.buildId.trim()}),t&&i.push(I(t));let n=await (0,r.getPrismaClient)(),a=await n.telemetryEntry.findMany({where:{AND:i},orderBy:[{clientTime:"desc"},{receivedAt:"desc"},{id:"desc"}],take:A+1}),o=a.length>A,s=a.slice(0,A).map(u);return{items:s,nextCursor:o&&s.length?w(s.at(-1)):null}}async timelineSinceLatestSeparator(e){let A,t,i=c(e.view);(0,a.validateTelemetryQuery)(e);let n=Math.min(500,Math.max(1,e.first??200)),o=f(e.after),s=await this.latestSeparator(),l=s?{clientTime:s.clientTime,receivedAt:s.receivedAt,id:s.id}:null,d=E(e),u=l?{AND:[y(i),(A=new Date(l.clientTime),{OR:[{clientTime:{gt:A}},{clientTime:A,receivedAt:{gt:t=new Date(l.receivedAt)}},{clientTime:A,receivedAt:t,id:{gt:l.id}}]})]}:y(i);if(!d){let e=await (0,r.getPrismaClient)(),A=await e.telemetryEntry.count({where:u}),t=[],i=!1,a=null;return await this.scan(o?{AND:[u,I(o)]}:u,e=>{if(t.length<n){t.push(e),a=e;return}return i=!0,!1},Math.min(1e3,n+1)),{separator:s,items:t,nextCursor:i&&a?w(a):null,matchingCount:A,totalCount:A}}let h=[],g=0,p=0,C=!1,B=null;return await this.scan(u,A=>{p+=1,!(0,a.matchesTelemetryQuery)(A,e)||(g+=1,(!o||m(A,o))&&(h.length<n?(h.push(A),B=A):C=!0))}),{separator:s,items:h,nextCursor:C&&B?w(B):null,matchingCount:g,totalCount:p}}async facets(e){let A=c(e),t="CONSOLE"===A?["level","category","deviceIp","buildId","sessionId"]:"ANALYTICS"===A?["eventKind","eventName","screenName","deviceIp","buildId","sessionId"]:["source","level","eventKind","deviceIp","buildId","sessionId"],r=Object.fromEntries(t.map(e=>[e,new Set]));return await this.scan(y(A),e=>{let i=(0,a.fieldsForFacet)(e);for(let e of t){let A=i[e];null!=A&&""!==String(A)&&r[e].add(String(A))}"UNIFIED"===A&&r.source.add(e.entryType)}),Object.fromEntries(Object.entries(r).map(([e,A])=>[e,[...A].sort((e,A)=>e.localeCompare(A))]))}async fields(e){let A=c(e),t=new Set;return await this.scan(y(A),e=>{for(let A of Object.keys((0,a.fieldsForFacet)(e)))t.add(A)}),[...t].sort((e,A)=>e.localeCompare(A))}async addSeparator(e){let A=e?.trim()||null;if(A&&A.length>100)throw Error("Separator name must not exceed 100 characters");let i=await (0,r.getPrismaClient)(),n=await i.telemetryEntry.create({data:{id:(0,t.randomUUID)(),entryType:"SEPARATOR",clientTime:new Date,receivedAt:new Date,separatorKind:"MANUAL",separatorName:A}});return this.publish([n.id],"SEPARATOR_ADDED"),u(n)}async addBuildSeparator(e){let A=await (0,r.getPrismaClient)(),i=await A.telemetryEntry.upsert({where:{separatorKind_buildId:{separatorKind:"BUILD",buildId:e.buildId}},create:{id:(0,t.randomUUID)(),entryType:"SEPARATOR",clientTime:e.clientTime??new Date,receivedAt:new Date,separatorKind:"BUILD",separatorName:e.name.slice(0,100),buildId:e.buildId},update:{}});return this.publish([i.id],"BUILD_SEPARATOR_ADDED"),u(i)}async highlight(e,A){if(null!==A&&!s.TELEMETRY_COLORS.includes(A))throw Error("Unknown telemetry highlight color");let t=await (0,r.getPrismaClient)();if("SEPARATOR"===(await t.telemetryEntry.findUniqueOrThrow({where:{id:e}})).entryType)throw Error("Separators cannot be highlighted");let i=await t.telemetryEntry.update({where:{id:e},data:{highlightColor:A}});return this.publish([e],"HIGHLIGHT_CHANGED"),u(i)}selectionRanges(e){return(Array.isArray(e.ranges)?e.ranges.slice(0,500):[]).map(e=>{if(!e||"object"!=typeof e)throw Error("Invalid telemetry selection range");let A=e.startTime?Date.parse(e.startTime):null,t=e.endTime?Date.parse(e.endTime):null;if(null!==A&&!Number.isFinite(A)||null!==t&&!Number.isFinite(t)||null!==A&&null!==t&&A>=t)throw Error("Invalid telemetry selection range");return{start:A,end:t,includeSeparators:!0===e.includeSeparators}})}async selectionIds(e){let A=new Set((Array.isArray(e.ids)?e.ids:[]).filter(e=>"string"==typeof e).slice(0,1e5)),t=new Set((Array.isArray(e.excludedIds)?e.excludedIds:[]).filter(e=>"string"==typeof e).slice(0,1e5));if(!e.query){for(let e of t)A.delete(e);return[...A]}if("object"!=typeof e.query||Array.isArray(e.query))throw Error("Invalid telemetry selection query");c(e.query.view),(0,a.validateTelemetryQuery)(e.query);let r=this.selectionRanges(e);return await this.scan(e.includeSeparators||r.some(e=>e.includeSeparators)?{entryType:{in:[...(0,a.sourcesForView)(e.query.view),"SEPARATOR"]}}:y(e.query.view),i=>{let n=Date.parse(i.clientTime),o=r.filter(e=>(null===e.start||n>=e.start)&&(null===e.end||n<e.end));if((!(r.length>0)||0!==o.length)&&!t.has(i.id)){if("SEPARATOR"===i.entryType){(e.includeSeparators||o.some(e=>e.includeSeparators))&&A.add(i.id);return}(0,a.matchesTelemetryQuery)(i,e.query)&&A.add(i.id)}}),[...A]}async clearSelected(e){let A=await this.selectionIds(e);if(!A.length)return 0;let t=await (0,r.getPrismaClient)(),i=0;for(let e=0;e<A.length;e+=500)i+=(await t.telemetryEntry.deleteMany({where:{id:{in:A.slice(e,e+500)}}})).count;return this.publish([],"CLEARED"),i}async clearAll(e,A=!1){let t=c(e),i=await (0,r.getPrismaClient)(),n=await i.telemetryEntry.deleteMany({where:A?{entryType:{in:[...(0,a.sourcesForView)(t),"SEPARATOR"]}}:y(t)});return this.publish([],A?"CLEARED_WITH_SEPARATORS":"CLEARED",A||"UNIFIED"===t?void 0:[t,"UNIFIED"]),n.count}async clearBeforeLatestSeparator(e,A=!1){let t=c(e),i=await this.latestSeparator();if(!i)return 0;let n=await (0,r.getPrismaClient)(),o=await n.telemetryEntry.deleteMany({where:{AND:[A?{entryType:{in:[...(0,a.sourcesForView)(t),"SEPARATOR"]}}:y(t),I({clientTime:i.clientTime,receivedAt:i.receivedAt,id:i.id})]}});return this.publish([],"CLEARED_BEFORE_SEPARATOR"),o.count}async clearScoped(e){let A=c(e.view);if("ALL"===e.scope)return this.clearAll(A,!!e.includeSeparators);if("BEFORE_LATEST_SEPARATOR"===e.scope)return this.clearBeforeLatestSeparator(A,!!e.includeSeparators);if("MATCHING"===e.scope){if(!e.query)throw Error("A matching query is required");return this.clearSelected({query:{...e.query,view:A}})}let t=[...new Set(e.ids??[])].slice(0,1e3);if(!t.length)throw Error("At least one telemetry entry ID is required");let i=await (0,r.getPrismaClient)(),n=await i.telemetryEntry.findMany({where:{id:{in:t},entryType:{in:[...(0,a.sourcesForView)(A),"SEPARATOR"]}},select:{id:!0}});if(!n.length)return 0;let o=await i.telemetryEntry.deleteMany({where:{id:{in:n.map(({id:e})=>e)}}});return this.publish([],"CLEARED"),o.count}async viewSettings(e){let A=c(e),t=await (0,r.getPrismaClient)(),i=await t.telemetryViewSettings.upsert({where:{view:A},create:{id:A,view:A,columnsJson:JSON.stringify(s.DEFAULT_TELEMETRY_COLUMNS[A])},update:{}});return{view:A,columns:D(i.columnsJson,A),timeFormat:"24"===i.timeFormat?"24":"12",activeColumnPresetId:i.activeColumnPresetId,activeSavedFilterId:i.activeSavedFilterId}}async saveViewSettings(e){let A=c(e.view);if(e.timeFormat&&!["12","24"].includes(e.timeFormat))throw Error("Unknown time format");let t=await this.viewSettings(A),i=await (0,r.getPrismaClient)();return await i.telemetryViewSettings.upsert({where:{view:A},create:{id:A,view:A,columnsJson:Q(e.columns??t.columns),timeFormat:e.timeFormat??t.timeFormat,activeColumnPresetId:e.activeColumnPresetId??null,activeSavedFilterId:e.activeSavedFilterId??null},update:{columnsJson:e.columns?Q(e.columns):void 0,timeFormat:e.timeFormat??void 0,activeColumnPresetId:void 0===e.activeColumnPresetId?void 0:e.activeColumnPresetId,activeSavedFilterId:void 0===e.activeSavedFilterId?void 0:e.activeSavedFilterId}}),this.viewSettings(A)}async columnPresets(e){let A=c(e),t=await (0,r.getPrismaClient)();return(await t.telemetryColumnPreset.findMany({where:{view:A},orderBy:[{isDefault:"desc"},{name:"asc"}]})).map(e=>({id:e.id,view:A,name:e.name,columns:D(e.columnsJson,A),isDefault:e.isDefault,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}))}async saveColumnPreset(e){let A=c(e.view),{name:i,normalizedName:n}=h(e.name),a=await (0,r.getPrismaClient)(),o=e.id??(0,t.randomUUID)();return await a.$transaction(async t=>{e.isDefault&&await t.telemetryColumnPreset.updateMany({where:{view:A},data:{isDefault:!1}}),await t.telemetryColumnPreset.upsert({where:{id:o},create:{id:o,view:A,name:i,normalizedName:n,columnsJson:Q(e.columns),isDefault:!0===e.isDefault},update:{name:i,normalizedName:n,columnsJson:Q(e.columns),isDefault:e.isDefault??void 0}})}),(await this.columnPresets(A)).find(e=>e.id===o)}async deleteColumnPreset(e){let A=await (0,r.getPrismaClient)();return await A.telemetryViewSettings.updateMany({where:{activeColumnPresetId:e},data:{activeColumnPresetId:null}}),(await A.telemetryColumnPreset.deleteMany({where:{id:e}})).count>0}async savedFilters(e){let A=c(e),t=await (0,r.getPrismaClient)();return(await t.telemetrySavedFilter.findMany({where:{view:A},orderBy:{name:"asc"}})).map(e=>({id:e.id,view:A,name:e.name,definition:JSON.parse(e.definitionJson),createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}))}async saveFilter(e){let A=c(e.view);(0,a.validateTelemetryQuery)({view:A,advancedFilter:e.definition});let{name:i,normalizedName:n}=h(e.name),s=await (0,r.getPrismaClient)(),l=e.id??(0,t.randomUUID)();return await s.telemetrySavedFilter.upsert({where:{id:l},create:{id:l,view:A,name:i,normalizedName:n,definitionJson:(0,o.stableJson)(e.definition)},update:{name:i,normalizedName:n,definitionJson:(0,o.stableJson)(e.definition)}}),(await this.savedFilters(A)).find(e=>e.id===l)}async deleteFilter(e){let A=await (0,r.getPrismaClient)();return await A.telemetryViewSettings.updateMany({where:{activeSavedFilterId:e},data:{activeSavedFilterId:null}}),(await A.telemetrySavedFilter.deleteMany({where:{id:e}})).count>0}async exportEntries(e){(0,a.validateTelemetryQuery)(e.query);let A=e.selection??(e.ids?.length?{ids:e.ids}:null);if(A){let e=new Set(await this.selectionIds(A)),t=[],r=[...e];for(let e=0;e<r.length;e+=500)await this.scan({id:{in:r.slice(e,e+500)}},e=>{t.push(e)});return t.sort((e,A)=>{let t=A.clientTime.localeCompare(e.clientTime);return t||A.receivedAt.localeCompare(e.receivedAt)||A.id.localeCompare(e.id)}),t}let t=[],r=!1,i=E(e.query);return await this.scan({entryType:{in:[...(0,a.sourcesForView)(e.query.view),"SEPARATOR"]}},A=>{"SEPARATOR"===A.entryType?((!i||r)&&t.push(A),r=!1):(0,a.matchesTelemetryQuery)(A,e.query)&&(t.push(A),r=!0)}),t}}],342572)},829111,e=>{"use strict";let A={type:"object",required:["collected","items"],properties:{collected:{type:"boolean"},items:{type:"array",items:{type:"object",required:["id","receivedAt","deviceIp"],properties:{id:{type:"string",format:"uuid"},receivedAt:{type:"string",format:"date-time"},deviceIp:{type:"string"}}}}}};function t(e,t,r){return{post:{tags:["Telemetry"],summary:r,description:"Unauthenticated ingestion. Accepts one record or an atomic `{ items: [...] }` batch of at most 500 records. The request body is capped at 2 MiB.",requestBody:{required:!0,content:{"application/json":{schema:{oneOf:[e,{type:"object",additionalProperties:!1,required:["items"],properties:{items:{type:"array",minItems:1,maxItems:500,items:e}}}]},examples:{single:{value:t},batch:{value:{items:[t]}}}}}},responses:{201:{description:"Records collected",content:{"application/json":{schema:A}}},202:{description:"Payload valid but collection is disabled",content:{"application/json":{schema:A}}},400:{$ref:"#/components/responses/TelemetryBadRequest"},413:{$ref:"#/components/responses/TelemetryPayloadTooLarge"},415:{$ref:"#/components/responses/TelemetryUnsupportedMediaType"},500:{$ref:"#/components/responses/InternalError"}}}}}t({$ref:"#/components/schemas/ConsoleLogInput"},{message:"Checkout completed",time:"2026-07-20T18:30:00.000Z",level:"info",category:"checkout",buildId:"build-123",sessionId:"session-456",attributes:{durationMs:412,cache:{hit:!0}}},"Collect console logs"),t({$ref:"#/components/schemas/AnalyticsEventInput"},{eventName:"checkout_completed",kind:"product",screenName:"Checkout",time:"2026-07-20T18:30:00.000Z",defaultParameters:{appVersion:"1.0"},additionalParameters:{cartItems:3},buildId:"build-123",sessionId:"session-456"},"Collect analytics events"),e.s([])},826587,e=>{"use strict";e.i(902157),e.i(912714),e.i(660526),e.i(750227),e.i(81111),e.i(188646);let A=globalThis;A.buildArtifactTransfers??(A.buildArtifactTransfers=new Map),e.s([])},354473,e=>e.a(async(A,t)=>{try{e.s(["cachedArtifact",()=>c]);var r=e.i(666680),i=e.i(912714),n=e.i(660526),a=e.i(750227);e.i(135475),e.i(826587);var o=e.i(604104),s=A([o]);[o]=s.then?(await s)():s;let h=process.env.ARTIFACT_CACHE_DIRECTORY?.trim()||(0,a.join)((0,n.tmpdir)(),"ade-build-artifact-cache");process.env.ARTIFACT_CACHE_MAX_BYTES;let g=globalThis;async function l(e){try{let A=JSON.parse(await (0,i.readFile)(e,"utf8"));if(!A||"object"!=typeof A)return null;let{filename:t,contentType:r,size:n}=A;if("string"!=typeof t||"string"!=typeof r||"number"!=typeof n)return null;return{filename:t,contentType:r,size:n}}catch{return null}}async function d(e){let A=(0,a.join)(h,e),t=await l(`${A}.json`);if(!t)return null;try{let r=await (0,i.stat)(A);if(!r.isFile()||r.size!==t.size)return null;let n=new Date;return await (0,i.utimes)(A,n,n).catch(()=>{}),{path:A,etag:`"${e}"`,...t}}catch{return null}}async function u(e,A){var t;let i=(0,o.getServerServices)(),n=await i.buildsService.artifactForInstall(e,A);if(!n)throw Error("Build artifact not found");return{artifact:n,key:(t=n.checksum??n.createdAt,(0,r.createHash)("sha1").update(`${A}:${t}`).digest("hex"))}}async function c(e,A){let{key:t}=await u(e,A);return d(t)}g.buildArtifactMaterializations??(g.buildArtifactMaterializations=new Map),t()}catch(e){t(e)}},!1),250746,e=>e.a(async(A,t)=>{try{e.s(["buildArtifactFileChecksum",()=>u,"failBuildArtifactTransferForJob",()=>c]);var r=e.i(666680),i=e.i(902157);e.i(912714);var n=e.i(660526),a=e.i(750227),o=e.i(135475);e.i(256554);var s=e.i(848201),l=e.i(354473),d=A([l]);[l]=d.then?(await d)():d,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 u(e){let A=(0,r.createHash)("sha256");for await(let t of(0,i.createReadStream)(e))A.update(t);return A.digest("hex")}async function c(e,A){let t=await (0,o.getPrismaClient)(),r=await t.buildArtifactTransfer.findFirst({where:{OR:[{sourceJobId:e},{targetJobId:e}]},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:A,finishedAt:new Date}}),t.buildDeployment.updateMany({where:{transferId:r.id,status:{in:["QUEUED","TRANSFERRING"]}},data:{status:"FAILED",error:A,finishedAt:new Date}})]),i=r.artifact.buildId,s.agentEventBus.publish((0,s.buildTopic)(i),{buildChanged:{id:i}}),s.agentEventBus.publish(s.BUILDS_CHANGED_TOPIC,{buildsChanged:{id:i}})}}h.buildArtifactTransferLocks??(h.buildArtifactTransferLocks=new Map),t()}catch(e){t(e)}},!1),868756,e=>e.a(async(A,t)=>{try{e.s(["BuildsService",()=>R]);var r=e.i(794231),i=e.i(666680),n=e.i(750227),a=e.i(662114),o=e.i(96945),s=e.i(135475);e.i(256554);var l=e.i(118387),d=e.i(848201),u=e.i(988438),c=e.i(354473),h=e.i(250746),g=A([c,h]);[c,h]=g.then?(await g)():g;let D=new Set(a.BUILD_CONFIGURATION_ICON_KEYS),b=new Set(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"]),S=["QUEUED","PREPARING","RUNNING"];function p(e,A=null){if(null===e)return A;try{return JSON.parse(e)}catch{return A}}function C(e,A){if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`${A} must be an object`);return e}function f(e){return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}function I(e){return null!==e.lastSeenAt&&Date.now()-e.lastSeenAt.getTime()<=(0,l.agentOnlineWindowMs)(e)&&null===e.disconnectedAt}function w(e){return f(p(e.capabilitiesJson,[]))}function m(e,A,t=80){let r=e.trim();if(!r)throw Error(`${A} is required`);if(r.length>t)throw Error(`${A} is too long`);return r}function E(e){return e.split(".").map(e=>Number.parseInt(e,10)||0)}function y(e,A){let t="string"==typeof A.minimumOSVersion?A.minimumOSVersion:null;if("SIMULATOR"!==e.type||!t||!e.osVersion)return e;let r=E(e.osVersion),i=E(t),n=Math.max(r.length,i.length);for(let A=0;A<n&&!((r[A]??0)>(i[A]??0));A+=1)if((r[A]??0)<(i[A]??0))return{...e,available:!1};return e}function B(e){if(e.codebaseId)return e.codebaseId;let A=p(e.snapshotJson,{});if(A&&"object"==typeof A&&!Array.isArray(A)){let e=A.codebase;if(e&&"object"==typeof e&&!Array.isArray(e)){let A=e.id;if("string"==typeof A&&A.trim())return A}}throw Error("Build coordination metadata is unavailable")}function Q(e){return"SUCCEEDED"===e?"SUCCEEDED":"CANCELLED"===e?"CANCELLED":"FAILED"}let k={agent:!0,codebase:{include:{repository:!0}},worktree:{include:{_count:{select:{builds:{where:{status:{in:S}}}}}}},configuration:{include:{source:!0,project:!0}},artifacts:{orderBy:{createdAt:"asc"}},scriptExecutions:{orderBy:[{phase:"asc"},{position:"asc"}]},deployments:{orderBy:{createdAt:"desc"},include:{targetAgent:!0,transfer:{include:{sourceAgent:!0,targetAgent:!0}}}},exports:{orderBy:{createdAt:"desc"}}};class R{agentControl;telemetry;notifications;diskSpace;constructor(e,A,t,r){this.agentControl=e,this.telemetry=A,this.notifications=t,this.diskSpace=r,this.agentControl.registerCompletionHandler(a.IOS_BUILD_JOB_KIND,e=>this.projectBuildCompletion(e)),this.agentControl.registerCompletionHandler(a.IOS_DEPLOY_JOB_KIND,e=>this.projectDeploymentCompletion(e)),this.agentControl.registerCompletionHandler(a.IOS_REMOTE_DEPLOY_JOB_KIND,e=>this.projectDeploymentCompletion(e)),this.agentControl.registerCompletionHandler(a.IOS_ARTIFACT_TRANSFER_UPLOAD_JOB_KIND,async e=>{"SUCCEEDED"!==e.status&&await (0,h.failBuildArtifactTransferForJob)(e.id,e.error||"The build agent could not upload the runnable app")}),this.agentControl.registerCompletionHandler(a.IOS_EXPORT_JOB_KIND,e=>this.projectExportCompletion(e)),this.agentControl.registerCompletionHandler(a.IOS_TEST_RESULTS_JOB_KIND,e=>this.projectGeneratedReportCompletion(e)),this.agentControl.registerCompletionHandler(a.IOS_COVERAGE_REPORT_JOB_KIND,e=>this.projectGeneratedReportCompletion(e)),this.agentControl.registerCompletionHandler(o.COVERAGE_IMPORT_JOB_KIND,e=>this.importedCoverageCompletion(e))}subscribeBuildChanges(e,A){let t=d.agentEventBus.iterate(d.BUILDS_CHANGED_TOPIC);return e||A?(0,r.filterAsyncIterator)(t,async({buildsChanged:{id:t}})=>{let r=await (0,s.getPrismaClient)(),i=await r.build.findUnique({where:{id:t},select:{worktreeId:!0,repository:{select:{apps:{where:{appId:e??void 0},select:{appId:!0},take:1}}}}});return!i||(!A||i.worktreeId===A)&&(!e||!!i.repository?.apps.length)}):t}async repositoryIdForBuild(e){let A=await (0,s.getPrismaClient)();return(await A.build.findUnique({where:{id:e},select:{repositoryId:!0}}))?.repositoryId??null}publish(e){d.agentEventBus.publish((0,d.buildTopic)(e),{buildChanged:{id:e}}),d.agentEventBus.publish(d.BUILDS_CHANGED_TOPIC,{buildsChanged:{id:e}}),d.agentEventBus.publish(d.SIDEBAR_STATUS_CHANGED_TOPIC,{sidebarStatusChanged:!0}),d.agentEventBus.publish(d.ACTION_CENTER_CHANGED_TOPIC,{actionCenterChanged:!0})}async requireWorktree(e,A,t="Agent must be updated to use iOS builds"){let r=await (0,s.getPrismaClient)(),i=await r.worktree.findUnique({where:{id:e},include:{codebase:{include:{agent:!0,repository:!0}}}});if(!i||i.missingAt||"AVAILABLE"!==i.availability)throw Error("Worktree is unavailable");if(!I(i.codebase.agent))throw Error("Agent is offline");if(!w(i.codebase.agent).includes(A))throw Error(t);return i}identity(e){return{codebaseId:e.codebaseId,worktreeId:e.id,branch:e.branch,folder:e.folder,gitDirectory:e.gitDirectory,expectedOrigin:e.codebase.repository.canonicalOrigin,headSha:e.headSha,baseBranch:e.baseBranchOverride??e.codebase.defaultBranch??null}}async ensureProject(e){let A=await (0,s.getPrismaClient)(),t=await A.codebase.findUnique({where:{id:e},select:{repositoryId:!0}});if(!t)throw Error("Codebase not found");return A.codebaseProject.upsert({where:{repositoryId_type:{repositoryId:t.repositoryId,type:"IOS_APP"}},create:{id:(0,i.randomUUID)(),repositoryId:t.repositoryId,type:"IOS_APP"},update:{}})}async project(e){let A=await (0,s.getPrismaClient)(),t=await A.codebase.findUnique({where:{id:e},include:{repository:!0}});if(!t)return null;let r=await A.codebaseProject.findUnique({where:{repositoryId_type:{repositoryId:t.repositoryId,type:"IOS_APP"}},include:{configurations:{orderBy:{name:"asc"},include:{source:{include:{observations:{where:{codebaseId:e},orderBy:{lastParseAttemptAt:"desc"},take:1}}}}}}}),i=await A.codebaseRepositoryBuildScript.findMany({where:{repositoryId:t.repositoryId,script:{deletedAt:null}},orderBy:[{position:"asc"},{script:{name:"asc"}}],include:{script:!0}});return r?{...r,repository:t.repository,allowedScripts:i}:null}async createProject(e){return await this.ensureProject(e),this.project(e)}async projectForWorktree(e){let A=await (0,s.getPrismaClient)(),t=await A.worktree.findUnique({where:{id:e},select:{codebaseId:!0}});return t?this.project(t.codebaseId):null}async saveConfiguration(e){let A=await this.ensureProject(e.codebaseId),t=(0,a.parseBuildSource)({kind:e.sourceKind,relativePath:e.sourcePath}),r=m(e.name,"Configuration name"),n=m(e.scheme,"Scheme",256),o=m(e.buildConfiguration,"Xcode configuration",256);if(!a.BUILD_ACTIONS.includes(e.defaultAction))throw Error("Build action is invalid");let l=e.iconKey?.trim()||null;if(l&&!D.has(l))throw Error("Icon is invalid");let d=(0,a.parseBuildAdvancedSettings)(e.advancedSettings??a.DEFAULT_BUILD_ADVANCED_SETTINGS),u=!0===e.autoExport;if(u&&"ARCHIVE"!==e.defaultAction)throw Error("Auto Export is available only for Archive configurations");let c=e.exportSettings?(0,a.parseBuildExportSettings)(e.exportSettings):null;if(u&&!c)throw Error("Auto Export settings are required");let h=await (0,s.getPrismaClient)(),g=e.id?await h.buildConfiguration.findUnique({where:{id:e.id}}):null;if(e.id&&(!g||g.projectId!==A.id))throw Error("Build configuration not found");let p=await h.buildSource.upsert({where:{projectId_relativePath:{projectId:A.id,relativePath:t.relativePath}},create:{id:(0,i.randomUUID)(),projectId:A.id,kind:t.kind,relativePath:t.relativePath},update:{kind:t.kind}}),C=g?.id??(0,i.randomUUID)();return h.buildConfiguration.upsert({where:{id:C},create:{id:C,projectId:A.id,sourceId:p.id,name:r,iconKey:l,scheme:n,buildConfiguration:o,defaultAction:e.defaultAction,advancedSettingsJson:JSON.stringify(d),autoExport:u,exportSettingsJson:c?JSON.stringify(c):null},update:{sourceId:p.id,name:r,iconKey:l,scheme:n,buildConfiguration:o,defaultAction:e.defaultAction,advancedSettingsJson:JSON.stringify(d),autoExport:u,exportSettingsJson:c?JSON.stringify(c):null},include:{source:!0}})}async deleteConfiguration(e){let A=await (0,s.getPrismaClient)();if(await A.build.findFirst({where:{configurationId:e,status:{in:S}}}))throw Error("Configuration has an active build");let t=await A.buildConfiguration.deleteMany({where:{id:e}});return 1===t.count}async scripts(){return(await (0,s.getPrismaClient)()).buildScript.findMany({where:{deletedAt:null},orderBy:{name:"asc"}})}async saveScript(e){let A=m(e.name,"Script name"),t=e.preBuildScript?.trim()||null,r=e.postBuildScript?.trim()||null;if(!t&&!r)throw Error("A pre-build or post-build script is required");let n=e.timeoutSeconds??300;if(!Number.isInteger(n)||n<1||n>3600)throw Error("Script timeout must be between 1 and 3600 seconds");if(!a.BUILD_SCRIPT_FAILURE_BEHAVIORS.includes(e.failureBehavior))throw Error("Script failure behavior is invalid");let o=await (0,s.getPrismaClient)(),l=e.id??(0,i.randomUUID)(),u=await o.buildScript.upsert({where:{id:l},create:{id:l,name:A,preBuildScript:t,postBuildScript:r,enabledByDefault:e.enabledByDefault,timeoutSeconds:n,failureBehavior:e.failureBehavior},update:{name:A,preBuildScript:t,postBuildScript:r,enabledByDefault:e.enabledByDefault,timeoutSeconds:n,failureBehavior:e.failureBehavior,deletedAt:null}});return d.agentEventBus.publish(d.BUILD_SCRIPTS_CHANGED_TOPIC,{buildScriptsChanged:!0}),u}async deleteScript(e){let A=await (0,s.getPrismaClient)(),t=await A.buildScript.updateMany({where:{id:e,deletedAt:null},data:{deletedAt:new Date}});return await A.codebaseRepositoryBuildScript.deleteMany({where:{scriptId:e}}),t.count&&d.agentEventBus.publish(d.BUILD_SCRIPTS_CHANGED_TOPIC,{buildScriptsChanged:!0}),1===t.count}async setAllowedScripts(e,A){let t=await (0,s.getPrismaClient)(),r=await t.codebase.findUnique({where:{id:e}});if(!r)throw Error("Codebase not found");let i=[...new Set(A)];if((await t.buildScript.findMany({where:{id:{in:i},deletedAt:null}})).length!==i.length)throw Error("Build script not found");return await t.$transaction(async e=>{await e.codebaseRepositoryBuildScript.deleteMany({where:{repositoryId:r.repositoryId}}),i.length&&await e.codebaseRepositoryBuildScript.createMany({data:i.map((e,A)=>({repositoryId:r.repositoryId,scriptId:e,position:A}))})}),this.project(e)}async waitForJob(e,A=12e4){let t=d.agentEventBus.iterate((0,d.agentJobChangedTopic)(e)),r=Date.now()+A;try{for(;Date.now()<r;){let A=await this.agentControl.getJob(e);if(!A)throw Error("Agent job disappeared");if(b.has(A.status))return A;await Promise.race([t.next(),new Promise(e=>setTimeout(e,Math.max(1,r-Date.now())))])}throw await this.agentControl.cancelJob(e),Error("Agent did not respond in time")}finally{await t.return?.()}}result(e){if("SUCCEEDED"!==e.status)throw Error(e.error||"Agent operation failed");return C(p(e.resultJson,{}),"agent result")}async discoverSources(e,A){let t=await this.requireWorktree(e,a.IOS_SOURCE_DISCOVER_JOB_KIND),r=await this.agentControl.createJob({agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,kind:a.IOS_SOURCE_DISCOVER_JOB_KIND,payload:this.identity(t),idempotencyKey:`ios:source:discover:${A}:${t.id}`,timeoutSeconds:60,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(r.id));return Array.isArray(e.sources)?e.sources:[]}finally{let e=await (0,s.getPrismaClient)();await e.agentJob.deleteMany({where:{id:r.id,visibility:"SYSTEM"}})}}async reparse(e,A,t){let r=await this.requireWorktree(A,a.IOS_SOURCE_PARSE_JOB_KIND),n=await (0,s.getPrismaClient)(),o=await n.buildConfiguration.findUnique({where:{id:e},include:{source:{include:{project:!0}}}});if(!o||o.source.project.repositoryId!==r.codebase.repositoryId)throw Error("Build configuration is not available for this worktree");let l=`worktree:${r.id}`,d=await n.buildSourceObservation.findUnique({where:{sourceId_scopeKey:{sourceId:o.sourceId,scopeKey:l}}}),u=new Date;await n.buildSourceObservation.upsert({where:{sourceId_scopeKey:{sourceId:o.sourceId,scopeKey:l}},create:{id:(0,i.randomUUID)(),sourceId:o.sourceId,scopeKey:l,codebaseId:r.codebaseId,worktreeId:r.id,status:"PARSING",lastParseAttemptAt:u},update:{status:"PARSING",error:null,lastParseAttemptAt:u}});let c=await this.agentControl.createJob({agentId:r.codebase.agentId,codebaseId:r.codebaseId,worktreeId:r.id,kind:a.IOS_SOURCE_PARSE_JOB_KIND,payload:{...this.identity(r),source:{kind:o.source.kind,relativePath:o.source.relativePath},scheme:o.scheme},idempotencyKey:`ios:source:parse:${t}:${o.id}:${r.id}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(c.id)),A=f(e.schemes),t=f(e.configurations),i=A.includes(o.scheme)&&t.includes(o.buildConfiguration);return n.buildSourceObservation.update({where:{sourceId_scopeKey:{sourceId:o.sourceId,scopeKey:l}},data:{status:i?"VALID":"INVALID",schemesJson:JSON.stringify(A),configurationsJson:JSON.stringify(t),testPlansJson:JSON.stringify(f(e.testPlans)),error:i?null:"The saved scheme or configuration is no longer available",stale:!1,headSha:"string"==typeof e.headSha?e.headSha:r.headSha,xcodeVersion:"string"==typeof e.xcodeVersion?e.xcodeVersion:null,lastParsedAt:new Date}})}catch(A){let e=A instanceof Error?A.message:String(A);return n.buildSourceObservation.update({where:{sourceId_scopeKey:{sourceId:o.sourceId,scopeKey:l}},data:{status:"ERROR",error:e,stale:!!d?.lastParsedAt}})}finally{await n.agentJob.deleteMany({where:{id:c.id,visibility:"SYSTEM"}})}}async inspectSource(e){let A=await this.requireWorktree(e.worktreeId,a.IOS_SOURCE_PARSE_JOB_KIND),t=(0,a.parseBuildSource)({kind:e.sourceKind,relativePath:e.sourcePath}),r=await this.agentControl.createJob({agentId:A.codebase.agentId,codebaseId:A.codebaseId,worktreeId:A.id,kind:a.IOS_SOURCE_PARSE_JOB_KIND,payload:{...this.identity(A),source:t,scheme:e.scheme?.trim()||null,configuration:e.configuration?.trim()||null},idempotencyKey:`ios:source:inspect:${e.requestId}:${A.id}:${t.relativePath}:${e.scheme??""}:${e.configuration??""}`,timeoutSeconds:120,visibility:"SYSTEM"});try{var i;let e=this.result(await this.waitForJob(r.id));return{source:t,schemes:f(e.schemes),configurations:f(e.configurations),testPlans:f(e.testPlans),signingRequirements:(i=e.signingRequirements,Array.isArray(i)?i.flatMap(e=>!e||"object"!=typeof e||Array.isArray(e)||"string"!=typeof e.bundleId||"string"!=typeof e.name||"string"!=typeof e.target?[]:[{bundleId:e.bundleId,name:e.name,target:e.target,platform:"string"==typeof e.platform?e.platform:null,teamId:"string"==typeof e.teamId?e.teamId:null,provisioningProfileSpecifier:"string"==typeof e.provisioningProfileSpecifier?e.provisioningProfileSpecifier:null}]):[]),headSha:"string"==typeof e.headSha?e.headSha:A.headSha,xcodeVersion:"string"==typeof e.xcodeVersion?e.xcodeVersion:null}}finally{let e=await (0,s.getPrismaClient)();await e.agentJob.deleteMany({where:{id:r.id,visibility:"SYSTEM"}})}}async destinations(e){let A=await this.requireWorktree(e.worktreeId,a.IOS_DESTINATIONS_JOB_KIND),t=await (0,s.getPrismaClient)(),r=await t.buildConfiguration.findUnique({where:{id:e.configurationId},include:{source:{include:{project:!0}}}});if(!r||r.source.project.repositoryId!==A.codebase.repositoryId)throw Error("Build configuration is not available for this worktree");let i=e.action??r.defaultAction;if(!a.BUILD_ACTIONS.includes(i))throw Error("Build action is invalid");let n=(0,a.genericBuildDestinations)(i);if("ARCHIVE"===i)return n;let o=await this.agentControl.createJob({agentId:A.codebase.agentId,codebaseId:A.codebaseId,worktreeId:A.id,kind:a.IOS_DESTINATIONS_JOB_KIND,payload:{...this.identity(A),source:{kind:r.source.kind,relativePath:r.source.relativePath},scheme:r.scheme,configuration:r.buildConfiguration,action:i},idempotencyKey:`ios:destinations:${e.requestId}:${r.id}:${A.id}:${i}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(o.id));return(Array.isArray(e.destinations)?e.destinations:[]).map(e=>(0,a.parseBuildDestination)(e)).filter(e=>!1!==e.available)}finally{await t.agentJob.deleteMany({where:{id:o.id,visibility:"SYSTEM"}})}}async signingOptionsForBuild(e){let A=await (0,s.getPrismaClient)(),t=await A.build.findUnique({where:{id:e},include:{artifacts:!0}}),r=t?.artifacts.find(e=>"ARCHIVE"===e.kind);if(!t||"SUCCEEDED"!==t.status||!t.worktreeId)throw Error("A successful archive build is required");if(!r)throw Error("Build does not contain an archive");let i=await this.requireWorktree(t.worktreeId,a.IOS_SIGNING_INSPECT_JOB_KIND),n=await this.agentControl.createJob({agentId:i.codebase.agentId,codebaseId:i.codebaseId,worktreeId:i.id,kind:a.IOS_SIGNING_INSPECT_JOB_KIND,payload:{buildId:t.id,codebaseId:i.codebaseId,artifactDirectory:t.artifactDirectory,archiveRelativePath:r.relativePath},idempotencyKey:`ios:signing:${t.id}:${r.id}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(n.id));return{teams:Array.isArray(e.teams)?e.teams:[],identities:Array.isArray(e.identities)?e.identities:[],profiles:Array.isArray(e.profiles)?e.profiles:[],bundles:Array.isArray(e.bundles)?e.bundles:[]}}finally{await A.agentJob.deleteMany({where:{id:n.id,visibility:"SYSTEM"}})}}async runAgentsForBuild(e){let A=await (0,s.getPrismaClient)(),t=await A.build.findUnique({where:{id:e},include:{artifacts:!0,agent:!0,worktree:!0}}),r=t?.artifacts.find(e=>"RUNNABLE_APP"===e.kind);if(!t||"SUCCEEDED"!==t.status||!r||!t.agentId)throw Error("A successful runnable build is required");let i=C(p(r.metadataJson,{}),"runnable metadata"),n=new Set(f(i.architectures).map(e=>"x64"===e?"x86_64":e)),o=await (0,c.cachedArtifact)(t.id,r.id),l=t.agent?w(t.agent):[];return(await A.agent.findMany({orderBy:{name:"asc"}})).map(e=>{let A=e.id===t.agentId,r=null;return e.osVersion.toLocaleLowerCase().startsWith("macos")?I(e)?A?w(e).includes(a.IOS_RUN_DESTINATIONS_JOB_KIND)&&w(e).includes(a.IOS_DEPLOY_JOB_KIND)||(r="AGENT_UPDATE_REQUIRED"):w(e).includes(a.IOS_AGENT_RUN_DESTINATIONS_JOB_KIND)&&w(e).includes(a.IOS_REMOTE_DEPLOY_JOB_KIND)?o||t.agent&&I(t.agent)&&l.includes(a.IOS_ARTIFACT_TRANSFER_UPLOAD_JOB_KIND)?"SIMULATOR"===t.destinationType&&n.size>0&&!n.has("x64"===e.architecture?"x86_64":e.architecture)&&(r="INCOMPATIBLE_ARCHITECTURE"):r="BUILD_AGENT_UNAVAILABLE":r="AGENT_UPDATE_REQUIRED":r="OFFLINE":r="NOT_MACOS",{agent:e,isBuildAgent:A,available:null===r,unavailableReason:r}}).sort((e,A)=>Number(A.isBuildAgent)-Number(e.isBuildAgent)||e.agent.name.localeCompare(A.agent.name))}async destinationsForBuild(e,A,t){let r=await (0,s.getPrismaClient)(),i=await r.build.findUnique({where:{id:e},include:{artifacts:!0}});if(!i||"SUCCEEDED"!==i.status||!i.artifacts.some(e=>"RUNNABLE_APP"===e.kind))throw Error("A successful runnable build is required");let n=i.artifacts.find(e=>"RUNNABLE_APP"===e.kind),o=C(p(n.metadataJson,{}),"runnable metadata"),l=t??i.agentId;if(!l)throw Error("Build agent is unavailable");if(l!==i.agentId){let e=(await this.runAgentsForBuild(i.id)).find(e=>e.agent.id===l);if(!e?.available)throw Error("The selected run agent is unavailable");let t=await this.agentControl.createJob({agentId:l,kind:a.IOS_AGENT_RUN_DESTINATIONS_JOB_KIND,payload:{destinationType:i.destinationType},idempotencyKey:`ios:agent-build-destinations:${m(A,"Request ID",200)}:${i.id}:${l}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(t.id));return(Array.isArray(e.destinations)?e.destinations:[]).map(e=>(0,a.parseBuildDestination)(e)).map(e=>y(e,o)).filter(e=>e.type===i.destinationType&&!e.generic)}finally{await r.agentJob.deleteMany({where:{id:t.id,visibility:"SYSTEM"}})}}if(!i.worktreeId)throw Error("The build worktree is unavailable");let d=await this.requireWorktree(i.worktreeId,a.IOS_RUN_DESTINATIONS_JOB_KIND);if(i.agentId!==d.codebase.agentId||i.codebaseId!==d.codebaseId)throw Error("The build no longer belongs to this worktree checkout");let u=await this.agentControl.createJob({agentId:d.codebase.agentId,codebaseId:d.codebaseId,worktreeId:d.id,kind:a.IOS_RUN_DESTINATIONS_JOB_KIND,payload:{...this.identity(d),destinationType:i.destinationType},idempotencyKey:`ios:build-destinations:${m(A,"Request ID",200)}:${i.id}`,timeoutSeconds:120,visibility:"SYSTEM"});try{let e=this.result(await this.waitForJob(u.id));return(Array.isArray(e.destinations)?e.destinations:[]).map(e=>(0,a.parseBuildDestination)(e)).map(e=>y(e,o)).filter(e=>e.type===i.destinationType&&!e.generic)}finally{await r.agentJob.deleteMany({where:{id:u.id,visibility:"SYSTEM"}})}}async startBuild(e){let A=m(e.requestId,"Request ID",200),t=`${e.worktreeId}:${A}`,r=await (0,s.getPrismaClient)(),o=await r.build.findUnique({where:{requestKey:t},include:k});if(o){if(this.telemetry){let e=p(o.snapshotJson,{}),A=C(e.configuration??{},"build configuration snapshot"),t=C(e.destination??{},"build destination snapshot");await this.telemetry.addBuildSeparator({buildId:o.id,name:`Build \xb7 ${String(A.name??"iOS")} \xb7 ${String(t.name??"Destination")}`,clientTime:o.createdAt})}return o}let l=await this.requireWorktree(e.worktreeId,a.IOS_BUILD_JOB_KIND);if(await this.diskSpace?.assertWorktreeCanStart(l.id),e.worktreeCoverage&&!w(l.codebase.agent).includes(a.IOS_COVERAGE_REPORT_JOB_KIND))throw Error("Build agent must be updated for worktree coverage");let d=await r.buildConfiguration.findUnique({where:{id:e.configurationId},include:{source:{include:{project:!0}}}});if(!d||d.source.project.repositoryId!==l.codebase.repositoryId)throw Error("Build configuration is not available for this worktree");let c=await r.buildSourceObservation.findUnique({where:{sourceId_scopeKey:{sourceId:d.sourceId,scopeKey:`worktree:${l.id}`}}}),h=e.action??d.defaultAction;if(!a.BUILD_ACTIONS.includes(h))throw Error("Build action is invalid");if(e.exportWhenComplete&&"ARCHIVE"!==h)throw Error("Export when complete is available only for Archive builds");let g="ARCHIVE"===h&&(e.exportWhenComplete??d.autoExport),f=e.exportSettings??p(d.exportSettingsJson,null),I=g||f?(0,a.parseBuildExportSettings)(f):null;if(g&&!I)throw Error("Export settings are required when automatic export is enabled");let E=(0,a.parseBuildDestination)(e.destination);if(!a.BUILD_DESTINATION_TYPES.includes(E.type))throw Error("Destination is invalid");if("ARCHIVE"===h&&("PHYSICAL_DEVICE"!==E.type||!E.generic))throw Error("Archive builds require the generic physical iOS destination");if(E.generic&&!a.GENERIC_BUILD_DESTINATION_ACTIONS.includes(h))throw Error("This build action requires a concrete destination");let y=C(p(d.advancedSettingsJson,{}),"saved advanced settings"),B=e.advancedSettings?C(e.advancedSettings,"advanced settings override"):{},Q=(0,a.parseBuildAdvancedSettings)({...y,...B,buildSettingOverrides:{...C(y.buildSettingOverrides??{},"saved overrides"),...C(B.buildSettingOverrides??{},"run overrides")}});if("TEST_WITHOUT_BUILDING"===h){if(!Q.priorBuildForTestingId)throw Error("Test Without Building requires a prior Build for Testing result");let e=await r.build.findUnique({where:{id:Q.priorBuildForTestingId},include:{artifacts:{where:{kind:{in:["TEST_PRODUCTS","XCTESTRUN"]}},orderBy:{createdAt:"asc"}}}});if(!e||"SUCCEEDED"!==e.status||"BUILD_FOR_TESTING"!==e.action)throw Error("Test Without Building requires a successful Build for Testing result");if(e.agentId!==l.codebase.agentId||e.worktreeId!==l.id||e.configurationId!==d.id)throw Error("The prior Build for Testing result is not compatible with this agent, worktree, and configuration");if(e.destinationType!==E.type)throw Error("The prior Build for Testing result uses a different destination type");let A=C(p(e.snapshotJson,{}),"prior Build for Testing snapshot"),t=C(A.configuration??{},"prior Build for Testing configuration snapshot"),i=(0,a.parseBuildAdvancedSettings)(t.advancedSettings??{});if(Q.testPlan&&i.testPlan&&Q.testPlan!==i.testPlan)throw Error("The selected test plan does not match the prior Build for Testing result");let o=Q.testPlan??i.testPlan??null,s=e.artifacts.filter(e=>"TEST_PRODUCTS"===e.kind&&e.relativePath.endsWith(".xctestproducts")),u=e.artifacts.filter(e=>"XCTESTRUN"===e.kind&&e.relativePath.endsWith(".xctestrun"));if(s.length>1)throw Error("The prior Build for Testing result contains multiple test-products artifacts");let c=s[0];if(c||1!==u.length||(c=u[0]),!c&&u.length>1&&o&&(c=u.find(e=>C(p(e.metadataJson,{}),"test-run artifact metadata").testPlan===o||e.relativePath.endsWith(`/${o}.xctestrun`)||e.relativePath===`${o}.xctestrun`)),!c&&u.length>1)throw Error("Select a test plan to choose among the captured .xctestrun artifacts");let h=c?.relativePath??"test-products.xctestproducts",g=(0,n.resolve)(e.artifactDirectory),f=(0,n.resolve)(g,h),I=(0,n.relative)(g,f);if(!I||I.startsWith("..")||(0,n.isAbsolute)(I))throw Error("The prior Build for Testing artifact path is invalid");Q={...Q,testPlan:o,priorTestProductsPath:h.endsWith(".xctestproducts")?f:null,priorXctestrunPath:h.endsWith(".xctestrun")?f:null}}let D=await r.codebaseRepositoryBuildScript.findMany({where:{repositoryId:l.codebase.repositoryId,script:{deletedAt:null}},orderBy:[{position:"asc"},{script:{name:"asc"}}],include:{script:!0}}),b=new Set(e.scriptIds??[]);if([...b].some(e=>!D.some(A=>A.scriptId===e)))throw Error("A selected build script is not allowed for this codebase");let S=D.filter(e=>b.has(e.scriptId)),R=(0,i.randomUUID)(),v=(0,u.effectiveBuildsDirectory)(l.codebase.agent);if(!v)throw Error("The agent builds directory is unavailable");let G=(0,n.join)(v,R),T={kind:d.source.kind,relativePath:d.source.relativePath},M=function(e){var A;let t=e.advancedSettings,r="TEST_WITHOUT_BUILDING"===e.action,i=["xcodebuild",...r?[]:[..."PACKAGE"===e.source.kind?[]:"PROJECT"===e.source.kind?["-project",e.source.relativePath]:["-workspace",e.source.relativePath],"-scheme",e.scheme,"-configuration",e.configuration],"-destination",(A=e.destination).generic?"SIMULATOR"===A.type?"generic/platform=iOS Simulator":"generic/platform=iOS":"SIMULATOR"===A.type?`platform=iOS Simulator,id=${A.id}`:`platform=iOS,id=${A.id}`,"-hideShellScriptEnvironment","-resultBundlePath",(0,n.join)(e.artifactDirectory,"result.xcresult")];for(let e of(!r&&("RESOLVED_ONLY"===t.packageResolution?i.push("-onlyUsePackageVersionsFromResolvedFile"):"SKIP_UPDATES"===t.packageResolution?i.push("-skipPackageUpdates"):"DISABLE_AUTOMATIC"===t.packageResolution&&i.push("-disableAutomaticPackageResolution"),t.disablePackageRepositoryCache&&i.push("-disablePackageRepositoryCache"),"PROJECT_DEFAULT"!==t.signingStyle&&i.push(`CODE_SIGN_STYLE=${"AUTOMATIC"===t.signingStyle?"Automatic":"Manual"}`),t.developmentTeam&&i.push(`DEVELOPMENT_TEAM=${t.developmentTeam}`),t.codeSignIdentity&&i.push(`CODE_SIGN_IDENTITY=${t.codeSignIdentity}`),t.provisioningProfileSpecifier&&i.push(`PROVISIONING_PROFILE_SPECIFIER=${t.provisioningProfileSpecifier}`),t.productBundleIdentifier&&i.push(`PRODUCT_BUNDLE_IDENTIFIER=${t.productBundleIdentifier}`),t.allowProvisioningUpdates&&i.push("-allowProvisioningUpdates"),t.allowProvisioningDeviceRegistration&&i.push("-allowProvisioningDeviceRegistration")),t.testPlan&&i.push("-testPlan",t.testPlan),t.codeCoverage&&i.push("-enableCodeCoverage","YES"),null!==t.parallelTesting&&i.push("-parallel-testing-enabled",t.parallelTesting?"YES":"NO"),null!==t.parallelTestingWorkers&&i.push("-parallel-testing-worker-count",String(t.parallelTestingWorkers)),t.onlyTesting))i.push(`-only-testing:${e}`);for(let e of t.skipTesting)i.push(`-skip-testing:${e}`);if(!r)for(let[e,A]of Object.entries(t.buildSettingOverrides))i.push(`${e}=${A}`);"ARCHIVE"===e.action&&i.push("-archivePath",(0,n.join)(e.artifactDirectory,"archive.xcarchive")),"BUILD_FOR_TESTING"===e.action&&i.push("-testProductsPath",(0,n.join)(e.artifactDirectory,"test-products.xctestproducts")),"TEST_WITHOUT_BUILDING"===e.action&&t.priorTestProductsPath&&i.push("-testProductsPath",t.priorTestProductsPath),"TEST_WITHOUT_BUILDING"===e.action&&!t.priorTestProductsPath&&t.priorXctestrunPath&&i.push("-xctestrun",t.priorXctestrunPath),i.push({BUILD:"build",TEST:"test",ANALYZE:"analyze",ARCHIVE:"archive",BUILD_FOR_TESTING:"build-for-testing",TEST_WITHOUT_BUILDING:"test-without-building"}[e.action]);let a=i.map(e=>/^[A-Za-z0-9_./:=,-]+$/.test(e)?e:JSON.stringify(e)).join(" ");return`cd ${JSON.stringify(e.folder)} && xcrun ${a}`}({folder:l.folder,source:T,scheme:d.scheme,configuration:d.buildConfiguration,destination:E,action:h,advancedSettings:Q,artifactDirectory:G}),N=S.map(({script:e,position:A})=>({id:e.id,name:e.name,preBuildScript:e.preBuildScript,postBuildScript:e.postBuildScript,timeoutSeconds:e.timeoutSeconds,failureBehavior:e.failureBehavior,position:A})),O=await this.telemetry?.buildSettings(E.type,{requestOrigin:e.telemetryRequestOrigin}),H={repository:{id:l.codebase.repository.id,name:l.codebase.repository.name,canonicalOrigin:l.codebase.repository.canonicalOrigin},codebase:{id:l.codebase.id,folder:l.codebase.folder},worktree:{id:l.id,folder:l.folder,branch:l.branch,headSha:l.headSha,codeStateHash:l.codeStateHash,hasStagedChanges:l.hasStagedChanges,hasUnstagedChanges:l.hasUnstagedChanges},agent:{id:l.codebase.agent.id,name:l.codebase.agent.name,hostname:l.codebase.agent.hostname},configuration:{id:d.id,name:d.name,iconKey:d.iconKey,source:T,scheme:d.scheme,buildConfiguration:d.buildConfiguration,action:h,advancedSettings:Q,autoExport:g,exportSettings:I,parse:c?{status:c.status,schemes:p(c.schemesJson,[]),configurations:p(c.configurationsJson,[]),testPlans:p(c.testPlansJson,[]),headSha:c.headSha,xcodeVersion:c.xcodeVersion,parsedAt:c.lastParsedAt?.toISOString()??null}:{status:"UNPARSED",schemes:[],configurations:[],testPlans:[],headSha:null,xcodeVersion:null,parsedAt:null}},destination:E,scripts:N,...O?{telemetry:O}:{},worktreeCoverage:!0===e.worktreeCoverage},U=new Date,_=r.build.create({data:{id:R,requestKey:t,requestId:A,agentId:l.codebase.agentId,codebaseId:l.codebaseId,worktreeId:l.id,repositoryId:l.codebase.repository.id,configurationId:d.id,status:"QUEUED",action:h,destinationType:E.type,destinationJson:JSON.stringify(E),snapshotJson:JSON.stringify(H),commandSummary:M,artifactDirectory:G,createdAt:U,scriptExecutions:{create:N.flatMap(e=>[...e.preBuildScript?[{id:(0,i.randomUUID)(),scriptId:e.id,phase:"PRE_BUILD",position:e.position,nameSnapshot:e.name,sourceSnapshot:e.preBuildScript,timeoutSeconds:e.timeoutSeconds,failureBehavior:e.failureBehavior}]:[],...e.postBuildScript?[{id:(0,i.randomUUID)(),scriptId:e.id,phase:"POST_BUILD",position:e.position,nameSnapshot:e.name,sourceSnapshot:e.postBuildScript,timeoutSeconds:e.timeoutSeconds,failureBehavior:e.failureBehavior}]:[]])}}});if(this.telemetry){let e=(0,i.randomUUID)();await r.$transaction([_,r.telemetryEntry.create({data:{id:e,entryType:"SEPARATOR",clientTime:U,receivedAt:U,separatorKind:"BUILD",separatorName:`Build \xb7 ${d.name} \xb7 ${E.name}`.slice(0,100),buildId:R}})]),this.telemetry.notifyChange([e],"BUILD_SEPARATOR_ADDED")}else await _;try{let t=await this.agentControl.createJob({agentId:l.codebase.agentId,codebaseId:l.codebaseId,worktreeId:l.id,kind:a.IOS_BUILD_JOB_KIND,payload:{...this.identity(l),buildId:R,artifactDirectory:G,source:T,scheme:d.scheme,configuration:d.buildConfiguration,action:h,destination:E,advancedSettings:Q,scripts:N,...O?{telemetry:O}:{},worktreeCoverage:!0===e.worktreeCoverage},idempotencyKey:`ios:build:${A}:${l.id}`,timeoutSeconds:604800});await r.build.update({where:{id:R},data:{jobId:t.id}})}catch(e){throw await r.build.update({where:{id:R},data:{status:"FAILED",errorCode:"QUEUE_FAILED",error:e instanceof Error?e.message:String(e),finishedAt:new Date}}),e}return this.publish(R),r.build.findUniqueOrThrow({where:{id:R},include:k})}async rebuildBuild(e,A,t){let r=await (0,s.getPrismaClient)(),i=await r.build.findUnique({where:{id:e},select:{worktreeId:!0,configurationId:!0,destinationJson:!0,action:!0,snapshotJson:!0}});if(!i)throw Error("Build not found");let n=C(p(i.snapshotJson,{}),"build snapshot"),a=C(n.worktree??{},"build worktree snapshot"),o=C(n.configuration??{},"build configuration snapshot"),l=Array.isArray(n.scripts)?n.scripts:[],d=i.worktreeId??("string"==typeof a.id?a.id:null),u=i.configurationId??("string"==typeof o.id?o.id:null);if(!d||!u)throw Error("The original build settings are unavailable");return this.startBuild({worktreeId:d,configurationId:u,destination:p(i.destinationJson,{}),scriptIds:l.flatMap(e=>{if(!e||"object"!=typeof e||Array.isArray(e))return[];let A=e.id;return"string"==typeof A?[A]:[]}),action:i.action,advancedSettings:o.advancedSettings,exportWhenComplete:!0===o.autoExport,...Object.hasOwn(o,"exportSettings")?{exportSettings:o.exportSettings}:{},requestId:A,...t?{telemetryRequestOrigin:t}:{}})}async startWorktreeCoverage(e){let A=await (0,s.getPrismaClient)(),t=await A.worktree.findUnique({where:{id:e.worktreeId},select:{baseBranchOverride:!0,codebase:{select:{defaultBranch:!0}}}});if(!t||!(t.baseBranchOverride??t.codebase.defaultBranch))throw Error("A base branch is required for worktree coverage");let r=C(e.advancedSettings??{},"coverage advanced settings");return this.startBuild({...e,action:"TEST",advancedSettings:{...r,codeCoverage:!0,parseTestResults:!0},worktreeCoverage:!0})}async importCoverageReport(e){let A=await (0,s.getPrismaClient)(),t=await this.requireWorktree(e.worktreeId,o.COVERAGE_IMPORT_JOB_KIND,"Agent must be updated to import coverage reports"),r=t.baseBranchOverride??t.codebase.defaultBranch??null,a=(e.format||"AUTO").toUpperCase();if(!o.COVERAGE_REPORT_FORMATS.includes(a))throw Error("Coverage format must be AUTO, LCOV, or ISTANBUL");let l=m(e.buildName??"Coverage report","Build name",200),d=m(e.reportPath,"Coverage file",4e3),c=m(e.requestId,"Request ID",200),h=`coverage:${e.worktreeId}:${c}`,g=await A.build.findUnique({where:{requestKey:h}});if(g)return g;let p=(0,i.randomUUID)(),C=(0,u.effectiveBuildsDirectory)(t.codebase.agent);if(!C)throw Error("The agent builds directory is unavailable");let f={repository:{id:t.codebase.repository.id,name:t.codebase.repository.name,canonicalOrigin:t.codebase.repository.canonicalOrigin},codebase:{id:t.codebase.id,folder:t.codebase.folder},worktree:{id:t.id,folder:t.folder,branch:t.branch,headSha:t.headSha,codeStateHash:t.codeStateHash,hasStagedChanges:t.hasStagedChanges,hasUnstagedChanges:t.hasUnstagedChanges},agent:{id:t.codebase.agent.id,name:t.codebase.agent.name,hostname:t.codebase.agent.hostname},configuration:{name:l},coverageImport:{reportPath:d,format:a,baseBranch:r},worktreeCoverage:!0},I={type:"HOST",id:t.codebase.agent.id,name:t.codebase.agent.name,platform:t.codebase.agent.architecture,osVersion:t.codebase.agent.osVersion||null,state:"Connected"},w=await A.build.create({data:{id:p,requestKey:h,requestId:c,agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,repositoryId:t.codebase.repository.id,status:"RUNNING",action:"TEST",destinationType:"HOST",destinationJson:JSON.stringify(I),snapshotJson:JSON.stringify(f),commandSummary:`Import coverage from ${d}`,artifactDirectory:(0,n.join)(C,p),startedAt:new Date}}),E=null;try{await A.buildReport.create({data:{id:(0,i.randomUUID)(),buildId:p,kind:"CODE_COVERAGE",source:"WORKTREE",status:"PENDING"}}),this.publish(p);let e=await this.agentControl.createJob({agentId:t.codebase.agentId,codebaseId:t.codebaseId,worktreeId:t.id,kind:o.COVERAGE_IMPORT_JOB_KIND,payload:{buildId:p,codebaseId:t.codebaseId,worktreeId:t.id,folder:t.folder,reportPath:d,format:a,baseBranch:r},idempotencyKey:`coverage:import:${c}:${p}`,timeoutSeconds:300,visibility:"SYSTEM"});return E=e.id,await A.build.update({where:{id:p},data:{jobId:e.id}}),{...w,jobId:e.id}}catch(r){E&&await this.agentControl.cancelJob(E).catch(()=>void 0);let e=r instanceof Error?r.message:String(r),t=new Date;throw await A.$transaction(async A=>{await A.buildReport.upsert({where:{buildId_kind:{buildId:p,kind:"CODE_COVERAGE"}},create:{id:(0,i.randomUUID)(),buildId:p,kind:"CODE_COVERAGE",source:"WORKTREE",status:"FAILED",error:e,finishedAt:t},update:{status:"FAILED",error:e,finishedAt:t}}),await A.build.update({where:{id:p},data:{status:"FAILED",errorCode:"QUEUE_FAILED",error:e,finishedAt:t}})}),this.publish(p),r}}async importedCoverageCompletion(e){let A=C(p(e.payloadJson,{}),"coverage import payload");if("string"!=typeof A.buildId)return;let t=A.buildId,r=C(p(e.resultJson,{}),"coverage import result"),n="SUCCEEDED"===e.status&&!!r.report&&"object"==typeof r.report,a=await (0,s.getPrismaClient)();await a.$transaction(async A=>{n?await this.upsertReportProjection(A,t,r.report,"WORKTREE"):await A.buildReport.upsert({where:{buildId_kind:{buildId:t,kind:"CODE_COVERAGE"}},create:{id:(0,i.randomUUID)(),buildId:t,kind:"CODE_COVERAGE",source:"WORKTREE",status:"FAILED",error:e.error||"Coverage import failed",finishedAt:new Date},update:{status:"FAILED",error:e.error||"Coverage import failed",finishedAt:new Date}}),await A.build.update({where:{id:t},data:{status:n?"SUCCEEDED":"FAILED",error:n?null:e.error||"Coverage import failed",finishedAt:new Date}})}),this.publish(t)}async generateReport(e,A,t){let r=await (0,s.getPrismaClient)(),n=await r.buildReport.findUnique({where:{buildId_kind:{buildId:e,kind:A}},include:{artifact:!0}});if(n?.status==="READY")return n;let o=await r.build.findUnique({where:{id:e},include:{agent:!0,artifacts:!0}});if(!o)throw Error("Build not found");if(S.includes(o.status))throw Error("Wait for the build to finish before generating reports");if(!o.agentId||!o.agent||!I(o.agent))throw Error("Build agent is offline");let l="TEST_RESULTS"===A?a.IOS_TEST_RESULTS_JOB_KIND:a.IOS_COVERAGE_REPORT_JOB_KIND;if(!w(o.agent).includes(l))throw Error("Build agent must be updated to generate reports");if(!o.artifacts.some(e=>"RESULT_BUNDLE"===e.kind))throw Error("The build result bundle is unavailable");if("TEST_RESULTS"===A&&!["TEST","TEST_WITHOUT_BUILDING"].includes(o.action))throw Error("This build did not run tests");let d=await r.buildReport.upsert({where:{buildId_kind:{buildId:e,kind:A}},create:{id:(0,i.randomUUID)(),buildId:e,kind:A,source:"MANUAL",status:"PENDING"},update:{source:"MANUAL",status:"PENDING",error:null,finishedAt:null}});this.publish(e);let u=B(o),c=await this.agentControl.createJob({agentId:o.agentId,codebaseId:u,worktreeId:o.worktreeId,kind:l,payload:{buildId:e,artifactDirectory:o.artifactDirectory,codebaseId:u,reportKind:A,source:"MANUAL"},idempotencyKey:`ios:report:${A}:${m(t,"Request ID",200)}:${e}`,timeoutSeconds:180,visibility:"SYSTEM"});try{return await this.waitForJob(c.id,17e4),r.buildReport.findUniqueOrThrow({where:{id:d.id},include:{artifact:!0}})}finally{await r.agentJob.deleteMany({where:{id:c.id,visibility:"SYSTEM"}})}}async coverageHistory(e){return(await (0,s.getPrismaClient)()).buildReport.findMany({where:{kind:"CODE_COVERAGE",source:"WORKTREE",build:{worktreeId:e}},orderBy:{createdAt:"desc"},take:50,select:{id:!0,buildId:!0,artifactId:!0,kind:!0,source:!0,status:!0,summaryJson:!0,error:!0,createdAt:!0,updatedAt:!0,finishedAt:!0,artifact:!0,build:{select:{id:!0,status:!0,action:!0,destinationType:!0,destinationJson:!0,snapshotJson:!0,createdAt:!0,startedAt:!0,finishedAt:!0,updatedAt:!0,worktree:{select:{headSha:!0,codeStateHash:!0,hasStagedChanges:!0,hasUnstagedChanges:!0,lastCheckedAt:!0,_count:{select:{builds:{where:{status:{in:S}}}}}}},artifacts:{orderBy:{createdAt:"asc"}}}}}})}async reportsForBuild(e,A,t=!0){return(await (0,s.getPrismaClient)()).buildReport.findMany({where:{buildId:e,...A?{kind:A}:{}},orderBy:{createdAt:"asc"},...t?{}:{omit:{dataJson:!0}},include:{artifact:!0}})}async reportData(e){let A=await (0,s.getPrismaClient)(),t=await A.buildReport.findUnique({where:{id:e},select:{dataJson:!0}});return t?.dataJson??"{}"}async builds(e={}){let A=await (0,s.getPrismaClient)(),t=Math.max(1,Math.min(e.first??50,200)),r=await A.build.findMany({where:{...e.status?{status:e.status}:{},...e.codebaseId?{codebaseId:e.codebaseId}:{},...e.worktreeId?{worktreeId:e.worktreeId}:{},...e.appId?{repository:{apps:{some:{appId:e.appId}}}}:{}},orderBy:[{createdAt:"desc"},{id:"desc"}],...e.after?{cursor:{id:e.after},skip:1}:{},take:t+1,include:k});return{items:r.slice(0,t),nextCursor:r.length>t?r[t-1].id:null}}async getBuild(e){return(await (0,s.getPrismaClient)()).build.findUnique({where:{id:e},include:k})}async deleteBuilds(e){let A=[...new Set(e)];if(!A.length)return 0;if(A.length>200)throw Error("At most 200 builds can be deleted at once");let t=await (0,s.getPrismaClient)(),r=await t.build.findMany({where:{id:{in:A}},select:{id:!0,status:!0,artifactDirectory:!0,snapshotJson:!0,agentId:!0,agent:{select:{capabilitiesJson:!0}},codebaseId:!0,worktreeId:!0,deployments:{where:{status:{in:S}},select:{id:!0}},exports:{where:{status:{in:S}},select:{id:!0}}}});if(r.some(e=>S.includes(e.status)))throw Error("Running builds cannot be deleted");if(r.some(e=>e.deployments.length>0||e.exports.length>0))throw Error("Builds with running deployments or exports cannot be deleted");for(let e of r){if(!(0,n.isAbsolute)(e.artifactDirectory)||(0,n.basename)(e.artifactDirectory)!==e.id)throw Error(`Build folder is invalid for ${e.id}`);if(e.agentId){let A=B(e);if(!e.agent||!w(e.agent).includes(a.IOS_BUILD_DELETE_JOB_KIND))throw Error("Build agent must be updated to delete builds");await this.agentControl.createJob({agentId:e.agentId,codebaseId:A,worktreeId:e.worktreeId,kind:a.IOS_BUILD_DELETE_JOB_KIND,payload:{buildId:e.id,artifactDirectory:e.artifactDirectory,codebaseId:A},idempotencyKey:`ios:build:delete:${e.id}`,timeoutSeconds:300,visibility:"SYSTEM"})}}let i=await t.build.deleteMany({where:{id:{in:r.map(e=>e.id)}}});for(let e of r)this.publish(e.id);return i.count}async artifactForInstall(e,A){let t=await (0,s.getPrismaClient)(),r=await t.buildArtifact.findFirst({where:{id:A,buildId:e}});return r?{id:r.id,kind:r.kind,relativePath:r.relativePath,sizeBytes:r.sizeBytes,checksum:r.checksum,createdAt:r.createdAt.toISOString(),metadata:C(p(r.metadataJson,{}),"build artifact metadata")}:null}async prepareArtifactDownload(e,A,t,r=17e4){let i=await (0,s.getPrismaClient)(),n=await i.buildArtifact.findFirst({where:{id:A,buildId:e},include:{build:{include:{agent:!0}}}});if(!n)throw Error("Build artifact not found");let{build:o}=n;if(!o.agentId||!o.agent)throw Error("The build agent is no longer available");if(!I(o.agent))throw Error("Build agent is offline");if(!w(o.agent).includes(a.IOS_ARTIFACT_DOWNLOAD_JOB_KIND))throw Error("Build agent must be updated to download artifacts");let l=B(o),d=await this.agentControl.createJob({agentId:o.agentId,codebaseId:l,worktreeId:o.worktreeId,kind:a.IOS_ARTIFACT_DOWNLOAD_JOB_KIND,payload:{buildId:o.id,artifactDirectory:o.artifactDirectory,artifactRelativePath:n.relativePath,uploadId:t,codebaseId:l},idempotencyKey:`ios:artifact:download:${t}`,timeoutSeconds:Math.ceil(r/1e3)+10,visibility:"SYSTEM"});try{this.result(await this.waitForJob(d.id,r))}finally{await i.agentJob.deleteMany({where:{id:d.id,visibility:"SYSTEM"}})}}async logChunks(e,A=null,t=1e3,r=[],i={}){if(r.some(e=>!Number.isInteger(e.fromSequence)||e.fromSequence<0||!Number.isInteger(e.throughSequence)||e.throughSequence<e.fromSequence))throw Error("Build log ranges must contain ordered non-negative sequence numbers");let n=await (0,s.getPrismaClient)(),a=A?await n.buildLogChunk.findFirst({where:{id:A,buildId:e},select:{id:!0,createdAt:!0,sequence:!0}}):null;if(A&&!a)throw Error("Build log cursor not found");let o=async A=>{if(!A)return null;let t=await n.buildLogChunk.findFirst({where:{id:A,buildId:e},select:{id:!0,createdAt:!0,sequence:!0}});if(!t)throw Error("Build log cursor not found");return t},[l,d]=await Promise.all([o(i.before),o(i.from)]),u=!!(i.latest||l),c=await n.buildLogChunk.findMany({where:{buildId:e,...l||d?{AND:[...l?[{OR:[{createdAt:{lt:l.createdAt}},{createdAt:l.createdAt,sequence:{lt:l.sequence}},{createdAt:l.createdAt,sequence:l.sequence,id:{lt:l.id}}]}]:[],...d?[{OR:[{createdAt:{gt:d.createdAt}},{createdAt:d.createdAt,sequence:{gt:d.sequence}},{createdAt:d.createdAt,sequence:d.sequence,id:{gte:d.id}}]}]:[]]}:{},...r.length?{NOT:r.map(e=>({scope:e.scope,scopeId:e.scopeId,sequence:{gte:e.fromSequence,lte:e.throughSequence}}))}:{},...a?{OR:[{createdAt:{gt:a.createdAt}},{createdAt:a.createdAt,sequence:{gt:a.sequence}},{createdAt:a.createdAt,sequence:a.sequence,id:{gt:a.id}}]}:{}},orderBy:[{createdAt:u?"desc":"asc"},{sequence:u?"desc":"asc"},{id:u?"desc":"asc"}],take:Math.max(1,Math.min(t,5e3))});return u?c.reverse():c}async cancelBuild(e){let A=await (0,s.getPrismaClient)(),t=await A.build.findUnique({where:{id:e}});if(!t)throw Error("Build not found");return S.includes(t.status)&&(t.jobId&&await this.agentControl.cancelJob(t.jobId),await A.build.update({where:{id:e},data:{status:"CANCELLED",finishedAt:new Date,errorCode:"CANCELLED"}}),this.publish(e)),this.getBuild(e)}async reportProgress(e,A){if(!["PREPARING","RUNNING"].includes(A.status))throw Error("Build progress status is invalid");let t=await (0,s.getPrismaClient)(),r=await t.build.findUnique({where:{id:A.buildId}});if(!r||r.agentId!==e)throw Error("Build not found for agent");if(!S.includes(r.status))return r;let i=await t.build.update({where:{id:A.buildId},data:{status:A.status,startedAt:r.startedAt??(A.startedAt?new Date(A.startedAt):new Date),errorCode:A.errorCode??void 0,error:A.error??void 0}});return this.publish(A.buildId),i}async appendLogChunks(e,A,t){if(!t.length||t.length>200)throw Error("Build log batches must contain 1 to 200 chunks");let r=await (0,s.getPrismaClient)(),n=await r.build.findUnique({where:{id:A}});if(!n||n.agentId!==e)throw Error("Build not found for agent");let a=t.map(e=>{if(!Number.isInteger(e.sequence)||e.sequence<0)throw Error("Log sequence must be a non-negative integer");if(!["STDOUT","STDERR","SYSTEM"].includes(e.stream))throw Error("Log stream is invalid");let t=Buffer.from(e.dataBase64,"base64");if(t.length!==e.byteLength||t.length>262144)throw Error("Log byte length is invalid");let r=Buffer.from(t.toString("utf8").replace(/(Bearer\s+)[A-Za-z0-9._~+\/-]+=*/gi,"$1[REDACTED]").replace(/([A-Za-z][A-Za-z0-9+.-]*:\/\/)[^\s/@]+@/g,"$1[REDACTED]@").replace(/\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY)[A-Z0-9_]*)\s*=\s*[^\s]+/gi,"$1=[REDACTED]").replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g,"[REDACTED PRIVATE KEY]"),"utf8"),n=new Date(e.createdAt);if(Number.isNaN(n.valueOf()))throw Error("Log date is invalid");return{id:(0,i.randomUUID)(),buildId:A,scope:m(e.scope,"Log scope",40),scopeId:m(e.scopeId,"Log scope ID",200),sequence:e.sequence,phase:m(e.phase,"Log phase",80),stream:e.stream,dataBase64:r.toString("base64"),byteLength:r.byteLength,createdAt:n}}),o=[];for(let e of a){let t=await r.buildLogChunk.upsert({where:{scope_scopeId_sequence:{scope:e.scope,scopeId:e.scopeId,sequence:e.sequence}},create:e,update:{}});o.push(t),d.agentEventBus.publish((0,d.buildLogChunkTopic)(A),{buildLogChunkAdded:t})}return o}async runBuild(e){let A=await (0,s.getPrismaClient)(),t=await A.build.findUnique({where:{id:e.buildId},include:{artifacts:!0,worktree:{include:{codebase:{include:{agent:!0,repository:!0}}}}}});if(!t||"SUCCEEDED"!==t.status)throw Error("A successful build is required");let r=t.artifacts.find(e=>"RUNNABLE_APP"===e.kind);if(!r)throw Error("Build does not contain a runnable app");let n=C(p(r.metadataJson,{}),"runnable metadata"),o=m(String(n.bundleIdentifier??""),"Runnable bundle identifier",512),l=e.destinations.map(a.parseBuildDestination);if(!l.length)throw Error("Select at least one destination");if(new Set(l.map(e=>`${e.type}:${e.id}`)).size!==l.length)throw Error("Run destinations must be unique");if(l.some(e=>e.type!==t.destinationType))throw Error("Run destinations must match the build destination type");let d=t.agentId??t.worktree?.codebase.agentId,u=e.targetAgentId??d;if(!u)throw Error("Build agent is unavailable");let g=u===d;if(!g){let e=(await this.runAgentsForBuild(t.id)).find(e=>e.agent.id===u);if(!e?.available)throw Error("The selected run agent is unavailable")}let f=await this.destinationsForBuild(t.id,`${m(e.requestId,"Request ID",200)}:preflight`,u),I=l.map(e=>f.find(A=>A.type===e.type&&A.id===e.id));if(I.some(e=>!e)||(l=I).some(e=>!1===e.available))throw Error("A selected run destination is no longer available");if(g&&!t.worktree)throw Error("The build worktree is unavailable");let w=g?await this.requireWorktree(t.worktree.id,a.IOS_DEPLOY_JOB_KIND):null,E=(0,i.randomUUID)(),y=[];for(let r of l){let n=`${r.type}:${r.id}`,a=await A.buildDeployment.findUnique({where:{buildId_requestId_targetAgentId_destinationKey:{buildId:t.id,requestId:e.requestId,targetAgentId:u,destinationKey:n}}});y.push(a??await A.buildDeployment.create({data:{id:(0,i.randomUUID)(),buildId:t.id,batchId:E,requestId:e.requestId,destinationJson:JSON.stringify(r),destinationKey:n,targetAgentId:u,status:g?"QUEUED":"TRANSFERRING",commandSummary:"SIMULATOR"===r.type?`open -a Simulator --args -CurrentDeviceUDID ${r.id}; xcrun simctl install/launch ${r.id}`:`xcrun devicectl device install/process launch --device ${r.id}`}}))}let B=y.map((e,A)=>({id:e.id,destination:l[A]}));if(g&&w){let i=await this.agentControl.createJob({agentId:w.codebase.agentId,codebaseId:w.codebaseId,worktreeId:w.id,kind:a.IOS_DEPLOY_JOB_KIND,payload:{...this.identity(w),buildId:t.id,artifactDirectory:t.artifactDirectory,artifactRelativePath:r.relativePath,bundleIdentifier:o,deployments:B},idempotencyKey:`ios:deploy:${t.id}:${e.requestId}`,timeoutSeconds:3600});await A.buildDeployment.updateMany({where:{id:{in:y.map(e=>e.id)}},data:{jobId:i.id}})}else if(!y.find(e=>e.transferId)?.transferId){let n=(0,i.randomUUID)(),s=await (0,c.cachedArtifact)(t.id,r.id),l=s?await (0,h.buildArtifactFileChecksum)(s.path):null;await A.buildArtifactTransfer.create({data:{id:n,artifactId:r.id,sourceAgentId:t.agentId,targetAgentId:u,status:s?"READY":"QUEUED",uploadOffset:s?.size??0,uploadLength:s?.size??null,checksum:l,filename:s?.filename??null,contentType:s?.contentType??null,stagingPath:s?.path??null,expiresAt:new Date(Date.now()+216e5)}});try{let i=null;s||(i=(await this.agentControl.createJob({agentId:t.agentId,kind:a.IOS_ARTIFACT_TRANSFER_UPLOAD_JOB_KIND,payload:{transferId:n,buildId:t.id,artifactDirectory:t.artifactDirectory,artifactRelativePath:r.relativePath},idempotencyKey:`ios:artifact-transfer:${n}`,timeoutSeconds:3600,visibility:"SYSTEM"})).id,await A.buildArtifactTransfer.update({where:{id:n},data:{sourceJobId:i}}));let l=await this.agentControl.createJob({agentId:u,kind:a.IOS_REMOTE_DEPLOY_JOB_KIND,payload:{transferId:n,buildId:t.id,bundleIdentifier:o,deployments:B},idempotencyKey:`ios:remote-deploy:${t.id}:${e.requestId}:${u}`,timeoutSeconds:7200});await A.$transaction([A.buildArtifactTransfer.update({where:{id:n},data:{sourceJobId:i,targetJobId:l.id}}),A.buildDeployment.updateMany({where:{id:{in:y.map(e=>e.id)}},data:{jobId:l.id,transferId:n,targetAgentId:u}})])}catch(i){let e=i instanceof Error?i.message:String(i),r=new Date;throw await A.$transaction([A.buildArtifactTransfer.update({where:{id:n},data:{status:"FAILED",error:e,finishedAt:r}}),A.buildDeployment.updateMany({where:{id:{in:y.map(e=>e.id)}},data:{status:"FAILED",error:e,finishedAt:r}})]).catch(()=>{}),this.publish(t.id),i}}return this.publish(t.id),A.buildDeployment.findMany({where:{id:{in:y.map(e=>e.id)}},orderBy:{createdAt:"asc"}})}async exportArchive(e){let A=await (0,s.getPrismaClient)(),t=await A.buildExport.findUnique({where:{buildId_requestId:{buildId:e.buildId,requestId:e.requestId}}});if(t)return t;let r=await A.build.findUnique({where:{id:e.buildId},include:{artifacts:!0,worktree:!0}});if(!r||"SUCCEEDED"!==r.status||!r.worktree)throw Error("A successful archive build is required");let n=r.artifacts.find(e=>"ARCHIVE"===e.kind);if(!n)throw Error("Build does not contain an archive");let o=(0,a.parseBuildExportSettings)(e.settings),l=await this.requireWorktree(r.worktree.id,a.IOS_EXPORT_JOB_KIND),d=(0,i.randomUUID)(),u=await A.buildExport.create({data:{id:d,buildId:r.id,requestId:e.requestId,settingsSnapshotJson:JSON.stringify(o),commandSummary:`xcrun xcodebuild -exportArchive -archivePath ${JSON.stringify(n.relativePath)} -exportPath exports/${d}`}});try{let t=await this.agentControl.createJob({agentId:l.codebase.agentId,codebaseId:l.codebaseId,worktreeId:l.id,kind:a.IOS_EXPORT_JOB_KIND,payload:{...this.identity(l),buildId:r.id,exportId:d,artifactDirectory:r.artifactDirectory,archiveRelativePath:n.relativePath,settings:o},idempotencyKey:`ios:export:${r.id}:${e.requestId}`,timeoutSeconds:3600}),i=await A.buildExport.update({where:{id:u.id},data:{jobId:t.id}});return this.publish(r.id),i}catch(t){let e=await A.buildExport.update({where:{id:u.id},data:{status:"FAILED",error:t instanceof Error?t.message:String(t),finishedAt:new Date}});return this.publish(r.id),e}}async upsertArtifacts(e,A,t){for(let r of(0,a.parseBuildArtifactSnapshots)(t)){let t={kind:r.kind,sizeBytes:r.sizeBytes,checksum:r.checksum,metadataJson:JSON.stringify(r.metadata)};await e.buildArtifact.upsert({where:{buildId_relativePath:{buildId:A,relativePath:r.relativePath}},create:{id:(0,i.randomUUID)(),buildId:A,relativePath:r.relativePath,...t},update:t})}}async upsertReportProjection(e,A,t,r){let n=C(t,"build report");if("TEST_RESULTS"!==n.kind&&"CODE_COVERAGE"!==n.kind)return;let a=n.kind,o=n.artifact&&"object"==typeof n.artifact?C(n.artifact,"build report artifact"):null,s=o&&"string"==typeof o.relativePath?await e.buildArtifact.findUnique({where:{buildId_relativePath:{buildId:A,relativePath:o.relativePath}}}):null,l="READY"===n.status?"READY":"FAILED";await e.buildReport.upsert({where:{buildId_kind:{buildId:A,kind:a}},create:{id:(0,i.randomUUID)(),buildId:A,artifactId:s?.id??null,kind:a,source:r,status:l,summaryJson:JSON.stringify(n.summary&&"object"==typeof n.summary?n.summary:{}),dataJson:JSON.stringify(n.data&&"object"==typeof n.data?n.data:{}),error:"string"==typeof n.error?n.error:null,finishedAt:new Date},update:{artifactId:s?.id??null,source:r,status:l,summaryJson:JSON.stringify(n.summary&&"object"==typeof n.summary?n.summary:{}),dataJson:JSON.stringify(n.data&&"object"==typeof n.data?n.data:{}),error:"string"==typeof n.error?n.error:null,finishedAt:new Date}})}async projectBuildCompletion(e){let A=await (0,s.getPrismaClient)(),t=await A.build.findFirst({where:{jobId:e.id},include:{worktree:{select:{highlightColor:!0}}}});if(!t)return;let r=C(p(e.resultJson,{}),"build result"),n="CANCELLED"===t.status?"CANCELLED":Q(e.status),a="string"==typeof r.sourceStateHash?r.sourceStateHash:null,o="string"==typeof r.finalStateHash?r.finalStateHash:null,l="string"==typeof r.codeStateObservedAt&&Number.isFinite(Date.parse(r.codeStateObservedAt))?new Date(r.codeStateObservedAt):new Date,d=o?l:new Date,u=t.snapshotJson;if(a){let e=C(p(t.snapshotJson,{}),"build snapshot"),A=C(e.worktree??{},"build worktree snapshot");u=JSON.stringify({...e,worktree:{...A,codeStateHash:a}})}let c=null;await A.$transaction(async A=>{if(await A.build.update({where:{id:t.id},data:{status:n,errorCode:"string"==typeof r.errorCode?r.errorCode:"TIMED_OUT"===e.status?"TIMEOUT":"FAILED"===n?"XCODEBUILD_FAILED":t.errorCode,error:e.error??("string"==typeof r.error?r.error:t.error),startedAt:t.startedAt??new Date,finishedAt:d,snapshotJson:u}}),t.worktreeId&&o&&await A.worktree.updateMany({where:{id:t.worktreeId,OR:[{lastCheckedAt:null},{lastCheckedAt:{lt:l}}]},data:{codeStateHash:o,lastCheckedAt:l}}),Array.isArray(r.artifacts))for(let e of r.artifacts){let r=C(e,"build artifact");"string"==typeof r.relativePath&&"string"==typeof r.kind&&await A.buildArtifact.upsert({where:{buildId_relativePath:{buildId:t.id,relativePath:r.relativePath}},create:{id:(0,i.randomUUID)(),buildId:t.id,kind:r.kind,relativePath:r.relativePath,sizeBytes:"number"==typeof r.sizeBytes?r.sizeBytes:null,checksum:"string"==typeof r.checksum?r.checksum:null,metadataJson:JSON.stringify(r.metadata&&"object"==typeof r.metadata?r.metadata:{})},update:{}})}if(Array.isArray(r.scriptExecutions))for(let e of r.scriptExecutions){let r=C(e,"script execution");"string"==typeof r.phase&&"number"==typeof r.position&&await A.buildScriptExecution.updateMany({where:{buildId:t.id,phase:r.phase,position:r.position},data:{status:"string"==typeof r.status?r.status:"FAILED",exitCode:"number"==typeof r.exitCode?r.exitCode:null,durationMs:"number"==typeof r.durationMs?r.durationMs:null,causedBuildFailure:!0===r.causedBuildFailure,outputRelativePath:"string"==typeof r.outputRelativePath?r.outputRelativePath:null,error:"string"==typeof r.error?r.error:null}})}if(Array.isArray(r.reports))for(let e of r.reports){let r=e&&"object"==typeof e&&!Array.isArray(e)?e:{};await this.upsertReportProjection(A,t.id,e,"CODE_COVERAGE"===r.kind?"WORKTREE":"AUTOMATIC")}if(this.notifications&&("SUCCEEDED"===n||"FAILED"===n)){let e=C(p(u,{}),"build notification snapshot"),r=C(e.repository??{},"build repository snapshot"),i=C(e.configuration??{},"build configuration snapshot"),a=C(e.worktree??{},"build worktree snapshot"),o=["string"==typeof r.name?r.name:null,"string"==typeof i.name?i.name:null,"string"==typeof a.branch?a.branch:"string"==typeof a.folder?a.folder:null].filter(e=>!!e);c=await this.notifications.recordInTransaction(A,{dedupeKey:`ios-build:${t.id}:${n}`,typeKey:"SUCCEEDED"===n?"IOS_BUILD_SUCCEEDED":"IOS_BUILD_FAILED",title:"SUCCEEDED"===n?"iOS build succeeded":"iOS build failed",body:o.join(" · ")||`Build ${t.id}`,href:`/builds/${t.id}`,resourceKind:"BUILD",resourceId:t.id,worktreeId:t.worktreeId,highlightColor:t.worktree?.highlightColor??null})}}),this.publish(t.id),this.notifications?.created(c),"SUCCEEDED"===n&&await this.queueAutomaticExport(t.id,u)}async queueAutomaticExport(e,A){let t=C(p(A,{}),"build snapshot"),r=C(t.configuration??{},"build configuration snapshot");if(!0!==r.autoExport)return;let n=r.exportSettings;try{await this.exportArchive({buildId:e,requestId:"automatic",settings:n})}catch(r){let A=await (0,s.getPrismaClient)(),t=r instanceof Error?r.message:String(r);await A.buildExport.upsert({where:{buildId_requestId:{buildId:e,requestId:"automatic"}},create:{id:(0,i.randomUUID)(),buildId:e,requestId:"automatic",status:"FAILED",settingsSnapshotJson:JSON.stringify(n??{}),commandSummary:"Automatic archive export",error:t,finishedAt:new Date},update:{status:"FAILED",error:t,finishedAt:new Date}}),this.publish(e)}}async projectGeneratedReportCompletion(e){let A=C(p(e.payloadJson,{}),"build report payload");if("string"!=typeof A.buildId)return;let t=A.buildId,r=C(p(e.resultJson,{}),"build report result"),n=await (0,s.getPrismaClient)();await n.$transaction(async n=>{if(await this.upsertArtifacts(n,t,r.artifacts),r.report&&"object"==typeof r.report)await this.upsertReportProjection(n,t,r.report,"WORKTREE"===A.source?"WORKTREE":"MANUAL");else{let r="CODE_COVERAGE"===A.reportKind?"CODE_COVERAGE":"TEST_RESULTS";await n.buildReport.upsert({where:{buildId_kind:{buildId:t,kind:r}},create:{id:(0,i.randomUUID)(),buildId:t,kind:r,source:"WORKTREE"===A.source?"WORKTREE":"MANUAL",status:"FAILED",error:e.error||"Report generation failed",finishedAt:new Date},update:{status:"FAILED",error:e.error||"Report generation failed",finishedAt:new Date}})}}),this.publish(t)}async projectDeploymentCompletion(e){let A=await (0,s.getPrismaClient)(),t=await A.buildDeployment.findMany({where:{jobId:e.id}});if(!t.length)return;let r=C(p(e.resultJson,{}),"deployment result"),i=Array.isArray(r.deployments)?r.deployments:[];for(let r of t){let t=i.map(e=>C(e,"deployment outcome")).find(e=>e.id===r.id);await A.buildDeployment.update({where:{id:r.id},data:{status:"string"==typeof t?.status?t.status:Q(e.status),error:"string"==typeof t?.error?t.error:e.error,outputRelativePath:"string"==typeof t?.outputRelativePath?t.outputRelativePath:null,startedAt:r.startedAt??new Date,finishedAt:new Date}})}for(let r of[...new Set(t.map(e=>e.transferId).filter(e=>!!e))]){let n=t.some(e=>{let A=i.map(e=>C(e,"deployment outcome")).find(A=>A.id===e.id);return A?.status!=="SUCCEEDED"});await A.buildArtifactTransfer.update({where:{id:r},data:{status:n||"SUCCEEDED"!==e.status?"FAILED":"SUCCEEDED",error:n||"SUCCEEDED"!==e.status?e.error||"One or more remote deployments failed":null,finishedAt:new Date}})}this.publish(t[0].buildId)}async projectExportCompletion(e){let A=await (0,s.getPrismaClient)(),t=await A.buildExport.findFirst({where:{jobId:e.id}});if(!t)return;let r=C(p(e.resultJson,{}),"export result");if(await A.buildExport.update({where:{id:t.id},data:{status:Q(e.status),error:e.error??("string"==typeof r.error?r.error:null),outputRelativePath:"string"==typeof r.outputRelativePath?r.outputRelativePath:null,startedAt:t.startedAt??new Date,finishedAt:new Date}}),"SUCCEEDED"===e.status&&"string"==typeof r.outputRelativePath){let e=r.outputRelativePath;await A.$transaction(async A=>{await A.buildArtifact.upsert({where:{buildId_relativePath:{buildId:t.buildId,relativePath:e}},create:{id:(0,i.randomUUID)(),buildId:t.buildId,kind:"EXPORT",relativePath:e,sizeBytes:"number"==typeof r.sizeBytes?r.sizeBytes:null,metadataJson:JSON.stringify({exportId:t.id})},update:{}}),await this.upsertArtifacts(A,t.buildId,r.artifacts)})}this.publish(t.buildId)}}t()}catch(e){t(e)}},!1),988438,e=>{"use strict";var A=e.i(750227);e.s(["effectiveBuildsDirectory",0,function(e){var t;return e.buildsDirectory??((t=e.baseRepoDirectory)?/^[a-z]:[\\/]/i.test(t)||t.startsWith("\\\\")?A.win32.join(t,"Builds"):A.posix.join(t,"Builds"):null)}])},89003,e=>{"use strict";var A=e.i(749906);let t=A.object({status:A.string().optional(),codebaseId:A.string().optional(),worktreeId:A.string().optional(),first:A.number().int().min(1).max(200).default(50),after:A.string().optional()}),r=A.object({builds:A.array(A.unknown()),nextCursor:A.string().nullable()}),i=A.object({buildId:A.string().min(1),afterLogId:A.string().min(1).nullable().default(null),logLimit:A.number().int().min(1).max(5e3).default(1e3)}),n=A.object({build:A.unknown(),logs:A.array(A.unknown())}),a=A.object({worktreeId:A.string().min(1)}),o=A.object({project:A.unknown().nullable()}),s=A.union([A.object({buildId:A.string().min(1),requestId:A.string().min(1)}),A.object({worktreeId:A.string().min(1),configurationId:A.string().min(1),action:A.string().optional(),requestId:A.string().min(1)})]),l=A.object({destinations:A.array(A.unknown())}),d=A.object({worktreeId:A.string().min(1),configurationId:A.string().min(1),destination:A.record(A.string(),A.unknown()),scriptIds:A.array(A.string()).default([]),action:A.string().optional(),advancedSettings:A.record(A.string(),A.unknown()).optional(),requestId:A.string().min(1)}),u=A.object({build:A.unknown()}),c=A.object({worktreeId:A.string().min(1),reportPath:A.string().min(1).max(4e3),format:A.enum(["AUTO","LCOV","ISTANBUL"]).default("AUTO"),requestId:A.string().min(1)}),h=A.object({build:A.unknown()}),g=A.object({buildId:A.string().min(1),requestId:A.string().min(1)}),p=A.object({build:A.unknown()}),C=A.object({buildId:A.string().min(1),destinations:A.array(A.record(A.string(),A.unknown())).min(1),requestId:A.string().min(1)}),f=A.object({deployments:A.array(A.unknown())}),I=A.object({buildId:A.string().min(1),settings:A.record(A.string(),A.unknown()),requestId:A.string().min(1)}),w=A.object({export:A.unknown()});e.s(["CancelBuildToolInputSchema",0,g,"CancelBuildToolOutputSchema",0,p,"ExportBuildToolInputSchema",0,I,"ExportBuildToolOutputSchema",0,w,"GetBuildConfigurationsInputSchema",0,a,"GetBuildConfigurationsOutputSchema",0,o,"GetBuildDestinationsInputSchema",0,s,"GetBuildDestinationsOutputSchema",0,l,"GetBuildInputSchema",0,i,"GetBuildOutputSchema",0,n,"GetBuildsInputSchema",0,t,"GetBuildsOutputSchema",0,r,"ImportCoverageReportToolInputSchema",0,c,"ImportCoverageReportToolOutputSchema",0,h,"RunBuildToolInputSchema",0,C,"RunBuildToolOutputSchema",0,f,"StartBuildToolInputSchema",0,d,"StartBuildToolOutputSchema",0,u])},108829,e=>e.a(async(A,t)=>{try{e.s([]);var r=e.i(868756);e.i(89003);var i=A([r]);[r]=i.then?(await i)():i,t()}catch(e){t(e)}},!1),933653,e=>{"use strict";var A=e.i(794231),t=e.i(666680),r=e.i(591135),i=e.i(380592),n=e.i(135475),a=e.i(751976),o=e.i(454228);e.i(256554);var s=e.i(118387),l=e.i(848201),d=e.i(999585);let u="default";function c(e){if("SUCCEEDED"!==e.status||!e.resultJson)throw Error(e.error||`${e.kind} failed`);let A=JSON.parse(e.resultJson);if(!A||"object"!=typeof A||Array.isArray(A))throw Error(`${e.kind} returned an invalid result`);return A}function h(e){try{let A=JSON.parse(e.capabilitiesJson);return Array.isArray(A)?A.filter(e=>"string"==typeof e):[]}catch{return[]}}function g(e){return null!==e.lastSeenAt&&Date.now()-e.lastSeenAt.getTime()<=(0,s.agentOnlineWindowMs)(e)&&null===e.disconnectedAt}e.s(["CodebasesService",0,class{agentControl;skillsService;stateInspections;cleanupInFlight;lastCleanupAt;constructor(e,A){for(const t of(this.agentControl=e,this.skillsService=A,this.stateInspections=new Map,this.cleanupInFlight=null,this.lastCleanupAt=0,[r.CODEBASE_REFRESH_JOB_KIND,r.CODEBASE_FETCH_JOB_KIND]))this.agentControl.registerCompletionHandler(t,e=>this.projectJob(e));this.agentControl.registerCompletionHandler(r.CODEBASE_GIT_OPERATION_JOB_KIND,e=>this.projectGitOperation(e))}async overview(e){return await this.cleanupInternalJobs(),(await (0,n.getPrismaClient)()).codebaseRepository.findMany({...e?{where:{codebases:{some:{agentId:e}}}}:{},orderBy:[{name:"asc"},{canonicalOrigin:"asc"}],include:{skillGroups:{include:{group:!0}},quickActionWorkflows:{include:{workflow:!0}},codebases:{...e?{where:{agentId:e}}:{},orderBy:{folder:"asc"},include:{agent:!0,repository:!0,jobs:{where:o.ACTIVE_CODEBASE_BLOCKING_JOB_WHERE,orderBy:{createdAt:"desc"},take:1}}}}})}async repositoryDetail(e){return await this.cleanupInternalJobs(),(await (0,n.getPrismaClient)()).codebaseRepository.findUnique({where:{id:e},include:{skillGroups:{include:{group:!0}},quickActionWorkflows:{include:{workflow:!0}},codebases:{orderBy:[{agent:{name:"asc"}},{folder:"asc"}],include:{agent:!0,repository:!0,jobs:{where:o.ACTIVE_CODEBASE_BLOCKING_JOB_WHERE,orderBy:{createdAt:"desc"},take:1}}}}})}async repositoryPreparations(e){let A=await (0,n.getPrismaClient)();if(!await A.codebaseRepository.findUnique({where:{id:e},select:{id:!0}}))throw Error("Repository not found");return A.codebaseRepositoryPreparation.findMany({where:{repositoryId:e},orderBy:[{kind:"asc"},{path:"asc"}]})}async detail(e){return await this.cleanupInternalJobs(),(await (0,n.getPrismaClient)()).codebase.findUnique({where:{id:e},include:{agent:!0,repository:{include:{skillGroups:{include:{group:!0}}}},jobs:{where:o.ACTIVE_CODEBASE_BLOCKING_JOB_WHERE,orderBy:{createdAt:"desc"},take:1}}})}async agentCodebases(e){return(await (0,n.getPrismaClient)()).codebase.findMany({where:{agentId:e},orderBy:{folder:"asc"},select:{id:!0,folder:!0,defaultBranch:!0,lastFetchedAt:!0,lastFetchAttemptAt:!0,repository:{select:{canonicalOrigin:!0,keepBaseBranchUpToDate:!0}},worktrees:{where:{missingAt:null},select:{id:!0,folder:!0,branch:!0,gitDirectory:!0,baseBranchOverride:!0}}}})}async settings(){let e=await (0,n.getPrismaClient)(),A=await e.codebaseSettings.findUnique({where:{id:u}});return A||e.codebaseSettings.upsert({where:{id:u},create:{id:u,refreshIntervalSeconds:r.DEFAULT_CODEBASE_RECONCILE_INTERVAL_SECONDS,fetchIntervalSeconds:i.DEFAULT_WORKTREE_FETCH_INTERVAL_SECONDS,defaultJiraBranchRegex:i.DEFAULT_JIRA_BRANCH_REGEX},update:{}})}async agentConfiguration(e){let A=await (0,n.getPrismaClient)(),[t,r,i]=await Promise.all([this.settings(),A.agent.findUnique({where:{id:e},select:{codebaseScanIntervalSeconds:!0,gitFetchIntervalSeconds:!0}}),this.agentCodebases(e)]);return{refreshIntervalSeconds:r?.codebaseScanIntervalSeconds??t.refreshIntervalSeconds,fetchIntervalSeconds:r?.gitFetchIntervalSeconds??t.fetchIntervalSeconds,codebases:i}}async updateSettings(e){let A="number"==typeof e?e:e.refreshIntervalSeconds,t="number"==typeof e?i.DEFAULT_WORKTREE_FETCH_INTERVAL_SECONDS:e.fetchIntervalSeconds;if(!Number.isInteger(A)||A<r.MIN_CODEBASE_RECONCILE_INTERVAL_SECONDS||A>r.MAX_CODEBASE_RECONCILE_INTERVAL_SECONDS)throw Error(`Refresh interval must be an integer from ${r.MIN_CODEBASE_RECONCILE_INTERVAL_SECONDS} to ${r.MAX_CODEBASE_RECONCILE_INTERVAL_SECONDS} seconds`);if(!Number.isInteger(t)||t<i.MIN_WORKTREE_FETCH_INTERVAL_SECONDS||t>i.MAX_WORKTREE_FETCH_INTERVAL_SECONDS)throw Error(`Fetch interval must be an integer from ${i.MIN_WORKTREE_FETCH_INTERVAL_SECONDS} to ${i.MAX_WORKTREE_FETCH_INTERVAL_SECONDS} seconds`);let o="number"==typeof e?i.DEFAULT_JIRA_BRANCH_REGEX:e.defaultJiraBranchRegex.trim();o&&(0,a.compileRe2)(o,{flags:"i",label:"Default Jira branch regex"});let s=await (0,n.getPrismaClient)(),l="number"==typeof e?{refreshIntervalSeconds:A}:{refreshIntervalSeconds:A,fetchIntervalSeconds:t,defaultJiraBranchRegex:o},d=await s.codebaseSettings.upsert({where:{id:u},create:{id:u,...l},update:l});return this.publish(null,null),d}async browse(e,A,t){await this.cleanupInternalJobs(),await this.requireAgentCapability(e,r.CODEBASE_BROWSE_JOB_KIND);let i=await this.agentControl.createJob({agentId:e,kind:r.CODEBASE_BROWSE_JOB_KIND,payload:{path:A},idempotencyKey:`codebase:browse:${t}`,timeoutSeconds:30,visibility:"SYSTEM"}),a=await this.waitForJob(i.id),o=(0,r.parseCodebaseDirectoryListing)(c(a).listing),s=await (0,n.getPrismaClient)();return await s.agentJob.deleteMany({where:{id:i.id}}),o}async inspect(e,A,t){await this.cleanupInternalJobs(),await this.requireAgentCapability(e,r.CODEBASE_INSPECT_JOB_KIND);let i=await this.agentControl.createJob({agentId:e,kind:r.CODEBASE_INSPECT_JOB_KIND,payload:{folder:A},idempotencyKey:`codebase:inspect:${t}`,timeoutSeconds:30,visibility:"SYSTEM"}),a=await this.waitForJob(i.id),o=(0,r.parseCodebaseSnapshot)(c(a).snapshot);if("AVAILABLE"!==o.availability)throw Error(o.error||"The selected folder is unavailable");if(o.linkedWorktree)throw Error("Linked Git worktrees are not supported yet");if(!o.canonicalOrigin)throw Error("Git origin is required");let s=await (0,n.getPrismaClient)(),l=await s.codebaseRepository.findUnique({where:{canonicalOrigin:o.canonicalOrigin}});return{jobId:i.id,snapshot:o,repository:l}}async confirm(e){let A=await (0,n.getPrismaClient)(),i=await A.agentJob.findUnique({where:{id:e.inspectionJobId}});if(!i||i.kind!==r.CODEBASE_INSPECT_JOB_KIND)throw Error("Codebase inspection was not found");if(!i.finishedAt||Date.now()-i.finishedAt.getTime()>9e5)throw Error("Codebase inspection expired; inspect the folder again");let a=(0,r.parseCodebaseSnapshot)(c(i).snapshot);if("AVAILABLE"!==a.availability||a.linkedWorktree||!a.canonicalOrigin||!a.displayOrigin||!a.observedOrigin)throw Error("Codebase inspection is not eligible for confirmation");let o=e.name?.trim()??"",s=e.description?.trim()??"";if(o.length>120)throw Error("Name must be 120 characters or fewer");if(s.length>2e3)throw Error("Description must be 2,000 characters or fewer");let l=await A.$transaction(async e=>{let A=await e.codebaseRepository.findUnique({where:{canonicalOrigin:a.canonicalOrigin}});if(!A){if(!o)throw Error("Name is required for a new repository");A=await e.codebaseRepository.upsert({where:{canonicalOrigin:a.canonicalOrigin},create:{id:(0,t.randomUUID)(),canonicalOrigin:a.canonicalOrigin,displayOrigin:a.displayOrigin,name:o,description:s},update:{}})}let r=await e.codebase.findUnique({where:{agentId_folder:{agentId:i.agentId,folder:a.folder}},select:{lastFetchedAt:!0}}),n=a.fetchedAt?new Date(a.fetchedAt):null,l=n&&(!r?.lastFetchedAt||n>r.lastFetchedAt)?n:r?.lastFetchedAt??null;return e.codebase.upsert({where:{agentId_folder:{agentId:i.agentId,folder:a.folder}},create:{id:(0,t.randomUUID)(),agentId:i.agentId,repositoryId:A.id,...this.snapshotData(a,l)},update:{repositoryId:A.id,...this.snapshotData(a,l)},include:{agent:!0,repository:!0,jobs:!0}})});return this.publish(l.id,l.repositoryId),await A.agentJob.deleteMany({where:{id:e.inspectionJobId,visibility:"SYSTEM"}}),await this.agentControl.requestCodebaseReconcile([l.agentId]),await this.skillsService?.requestAutoReconcile(),l}async updateRepository(e,A,t,r,i=!0,o){let s=A.trim(),l=t.trim();if(!s)throw Error("Name is required");if(s.length>120)throw Error("Name must be 120 characters or fewer");if(l.length>2e3)throw Error("Description must be 2,000 characters or fewer");let d=r?.trim()||null;d&&(0,a.compileRe2)(d,{flags:"i",label:"Jira branch regex"});let u=null==o?null:await this.skillsService?.validateGroupIds(o),c=await (0,n.getPrismaClient)(),h=await c.codebaseRepository.update({where:{id:e},data:{name:s,description:l,jiraBranchRegex:d,keepBaseBranchUpToDate:i}});return u&&await this.skillsService?.setRepositoryGroups(e,u),this.publish(null,e),h}async saveRepositoryPreparations(e,A){if(A.length>d.MAX_REPOSITORY_PREPARATIONS)throw Error("A repository can have at most 500 preparations");let r=await (0,n.getPrismaClient)(),a=await r.codebaseRepository.findUnique({where:{id:e},include:{preparations:{include:{statuses:!0}}}});if(!a)throw Error("Repository not found");let o=new Map(a.preparations.map(e=>[e.id,e])),s=new Set,l=new Set,u=0,c=A.map((e,A)=>{if(!i.WORKTREE_PREPARATION_KINDS.includes(e.kind))throw Error(`Preparation ${A+1} has an invalid kind`);let t=(0,d.normalizePreparationPath)(e.path);if(l.has(t))throw Error(`Preparation path ${t} is duplicated`);l.add(t);let r=e.id?.trim()||null,n=r?o.get(r):null;if(r&&!n)throw Error(`Preparation ${r} does not belong to this repository`);if(r&&s.has(r))throw Error(`Preparation ${r} is duplicated`);r&&s.add(r);let a=null;if("WRITE"===e.kind){if(null===(a=null!==e.contentBase64&&void 0!==e.contentBase64?(0,d.decodePreparationContents)(e.contentBase64):n?.kind==="WRITE"&&n.contents?Buffer.from(n.contents):null))throw Error(`Uploaded contents are required for ${t}`);u+=a.byteLength}else if(null!==e.contentBase64&&void 0!==e.contentBase64)throw Error("Uploaded contents are only supported for write preparations");return{id:r,kind:e.kind,path:t,contents:a,definitionHash:(0,d.preparationDefinitionHash)({kind:e.kind,path:t,contents:a})}});if(u>d.MAX_PREPARATION_TOTAL_BYTES)throw Error("Repository preparation uploads must total 20 MiB or less");let h=a.preparations.filter(e=>{let A=c.find(A=>A.id===e.id);return(!A||A.kind!==e.kind||A.path!==e.path)&&(e.statuses?.some(e=>"UNDONE"!==e.state&&"NOT_APPLICABLE"!==e.state)??!1)});if(h.length>0)throw Error(`Undo preparation ${h[0].path} on all worktrees before removing or moving it`);return await r.$transaction(async A=>{let r=c.flatMap(e=>e.id?[e.id]:[]);for(let i of(await A.codebaseRepositoryPreparation.deleteMany({where:{repositoryId:e,...r.length?{id:{notIn:r}}:{}}}),c)){let e=i.id?o.get(i.id):null;e&&e.path!==i.path&&await A.codebaseRepositoryPreparation.update({where:{id:e.id},data:{path:`.aide-preparation-replacement/${(0,t.randomUUID)()}`}})}for(let r of c){let i=r.id??(0,t.randomUUID)(),n={kind:r.kind,path:r.path,contents:r.contents?Uint8Array.from(r.contents):null,contentSha256:r.contents?(0,d.preparationContentSha256)(r.contents):null,byteCount:r.contents?.byteLength??null,definitionHash:r.definitionHash};r.id?await A.codebaseRepositoryPreparation.update({where:{id:i},data:n}):await A.codebaseRepositoryPreparation.create({data:{id:i,repositoryId:e,...n}})}}),this.publish(null,e),this.repositoryDetail(e)}async removeCodebase(e){let A=await (0,n.getPrismaClient)(),t=await A.$transaction(async A=>{let t=await A.codebase.findUnique({where:{id:e},select:{id:!0,repositoryId:!0,agentId:!0}});if(!t)throw Error("Codebase not found");await A.codebase.delete({where:{id:e}});let r=await A.codebase.count({where:{repositoryId:t.repositoryId}}),i=await A.appRepository.count({where:{repositoryId:t.repositoryId}}),n=0===r&&0===i;return n&&await A.codebaseRepository.delete({where:{id:t.repositoryId}}),{id:t.id,agentId:t.agentId,repositoryId:t.repositoryId,repositoryRemoved:n}});return this.publish(t.id,t.repositoryId,t.agentId),t}async report(e,A){let t=[],i=!1;try{for(let n of A.slice(0,500)){let A=(0,r.parseCodebaseSnapshot)(n.snapshot),a=await this.applySnapshot(e,n.codebaseId,A);t.push(a.codebase),i||=a.changed}}finally{i&&this.publish(null,null)}return t}async runOperation(e,A,t){if(!t.trim())throw Error("requestId is required");let i=await (0,n.getPrismaClient)(),a=await i.codebase.findMany({where:{id:{in:[...new Set(A)].slice(0,500)}},include:{agent:!0,repository:!0,jobs:{where:o.ACTIVE_CODEBASE_BLOCKING_JOB_WHERE,select:{id:!0},take:1}}}),s=[],l=[];for(let A of a){if(A.jobs.length>0){l.push({codebaseId:A.id,reason:"ACTIVE_OPERATION"});continue}if(!g(A.agent)){l.push({codebaseId:A.id,reason:"OFFLINE"});continue}if(!h(A.agent).includes(e)){l.push({codebaseId:A.id,reason:"UNSUPPORTED"});continue}if(e===r.CODEBASE_FETCH_JOB_KIND&&"AVAILABLE"!==A.availability){l.push({codebaseId:A.id,reason:A.availability});continue}try{s.push(await this.agentControl.createJob({agentId:A.agentId,codebaseId:A.id,kind:e,payload:{codebaseId:A.id,folder:A.folder,expectedOrigin:A.repository.canonicalOrigin,...e===r.CODEBASE_FETCH_JOB_KIND&&A.defaultBranch?{baseBranch:A.defaultBranch}:{},...e===r.CODEBASE_FETCH_JOB_KIND?{keepBaseBranchUpToDate:A.repository.keepBaseBranchUpToDate}:{}},idempotencyKey:`codebase:${e}:${t}:${A.id}`,timeoutSeconds:e===r.CODEBASE_FETCH_JOB_KIND?300:30}))}catch(e){if(!await i.agentJob.findFirst({where:{codebaseId:A.id,...o.ACTIVE_CODEBASE_BLOCKING_JOB_WHERE},select:{id:!0}}))throw e;l.push({codebaseId:A.id,reason:"ACTIVE_OPERATION"})}}return{jobs:s,skipped:l}}inspectGitState(e,A){if(!A.trim())return Promise.reject(Error("requestId is required"));let t=this.stateInspections.get(e);if(t)return t;let r=this.inspectGitStateOnce(e,A).finally(()=>{this.stateInspections.get(e)===r&&this.stateInspections.delete(e)});return this.stateInspections.set(e,r),r}async inspectGitStateOnce(e,A){if(!A.trim())throw Error("requestId is required");let t=await this.requireRunnableCodebase(e,r.CODEBASE_GIT_INSPECT_JOB_KIND),i=await this.agentControl.createJob({agentId:t.agentId,codebaseId:t.id,kind:r.CODEBASE_GIT_INSPECT_JOB_KIND,payload:{action:"STATE",codebaseId:t.id,folder:t.folder,expectedOrigin:t.repository.canonicalOrigin},idempotencyKey:`codebase:git:state:${A}:${t.id}`,timeoutSeconds:30,visibility:"SYSTEM"}),a=await (0,n.getPrismaClient)();try{let e=await this.waitForJob(i.id);return(0,r.parseCodebaseGitState)(c(e).state)}finally{await a.agentJob.deleteMany({where:{id:i.id,visibility:"SYSTEM"}})}}async inspectStash(e,A,t){if(!t.trim())throw Error("requestId is required");let i=await this.requireRunnableCodebase(e,r.CODEBASE_GIT_INSPECT_JOB_KIND),a=await this.agentControl.createJob({agentId:i.agentId,codebaseId:i.id,kind:r.CODEBASE_GIT_INSPECT_JOB_KIND,payload:{action:"STASH_DIFF",codebaseId:i.id,folder:i.folder,expectedOrigin:i.repository.canonicalOrigin,stashOid:A},idempotencyKey:`codebase:git:stash:${t}:${i.id}`,timeoutSeconds:30,visibility:"SYSTEM"}),o=await (0,n.getPrismaClient)();try{let e=await this.waitForJob(a.id);return(0,r.parseCodebaseStashDiff)(c(e).diff)}finally{await o.agentJob.deleteMany({where:{id:a.id,visibility:"SYSTEM"}})}}async runGitOperation(e){if(!e.requestId.trim())throw Error("requestId is required");let A=await this.requireRunnableCodebase(e.codebaseId,r.CODEBASE_GIT_OPERATION_JOB_KIND);return this.agentControl.createJob({agentId:A.agentId,codebaseId:A.id,kind:r.CODEBASE_GIT_OPERATION_JOB_KIND,payload:{codebaseId:A.id,folder:A.folder,expectedOrigin:A.repository.canonicalOrigin,defaultBranch:A.defaultBranch,operation:e.operation,...e.branch?{branch:e.branch}:{},...e.stashOid?{stashOid:e.stashOid}:{},..."SWITCH_BRANCH"===e.operation?{stashChanges:!!e.stashChanges}:{}},idempotencyKey:`codebase:git:${e.operation}:${e.requestId}:${A.id}`,timeoutSeconds:"PULL_BRANCH"===e.operation?300:60})}subscribe(e){let t=l.agentEventBus.iterate(l.CODEBASE_CHANGED_TOPIC);return e?(0,A.filterAsyncIterator)(t,async A=>{let t=A.codebaseOverviewChanged;if(t.agentId)return t.agentId===e;let r=await (0,n.getPrismaClient)();if(t.codebaseId){let A=await r.codebase.findUnique({where:{id:t.codebaseId},select:{agentId:!0}});return!A||A.agentId===e}return!t.repositoryId||!!await r.codebase.findFirst({where:{repositoryId:t.repositoryId,agentId:e},select:{id:!0}})}):t}async projectJob(e){if(!e.codebaseId||!e.resultJson)return;let A=JSON.parse(e.resultJson);if(!A||"object"!=typeof A||Array.isArray(A))return;let t=A.snapshot;if(!t)return;let i=await this.applySnapshot(e.agentId,e.codebaseId,(0,r.parseCodebaseSnapshot)(t));i.changed&&this.publish(i.codebase.id,i.codebase.repositoryId)}async projectGitOperation(e){if("SUCCEEDED"===e.status)try{await this.projectJob(e)}catch(e){console.error("Could not project codebase Git operation:",e instanceof Error?e.message:e)}try{await this.agentControl.requestCodebaseReconcile([e.agentId])}catch(e){console.error("Could not request codebase reconciliation:",e instanceof Error?e.message:e)}}async applySnapshot(e,A,t){let r=await (0,n.getPrismaClient)(),i=await r.codebase.findUnique({where:{id:A},include:{repository:!0}});if(!i||i.agentId!==e)throw Error("Codebase not found for this agent");let a=new Date(t.checkedAt),o=null!==t.canonicalOrigin&&t.canonicalOrigin!==i.repository.canonicalOrigin,s=t.fetchedAt?new Date(t.fetchedAt):null,l=await r.codebase.updateMany({where:{id:A,agentId:e,OR:[{lastCheckedAt:null},{lastCheckedAt:{lt:a}}]},data:{folder:t.folder,...null===t.observedOrigin?{}:{observedOrigin:t.observedOrigin},branch:t.branch,headSha:t.headSha,upstream:t.upstream,ahead:t.ahead,behind:t.behind,syncState:t.syncState,availability:o?"ORIGIN_MISMATCH":t.availability,statusError:o?`Origin changed to ${t.displayOrigin??"an unknown remote"}`:t.error,lastCheckedAt:a}});l.count>0&&s&&await r.codebase.updateMany({where:{id:A,agentId:e,OR:[{lastFetchedAt:null},{lastFetchedAt:{lt:s}}]},data:{lastFetchedAt:s}});let d=await r.codebase.findUnique({where:{id:A},include:{agent:!0,repository:!0,jobs:!0}});if(!d||d.agentId!==e)throw Error("Codebase not found for this agent");return{codebase:d,changed:l.count>0}}snapshotData(e,A){return{folder:e.folder,observedOrigin:e.observedOrigin??"",branch:e.branch,headSha:e.headSha,upstream:e.upstream,ahead:e.ahead,behind:e.behind,syncState:e.syncState,availability:e.availability,statusError:e.error,lastCheckedAt:new Date(e.checkedAt),lastFetchedAt:A}}async requireAgentCapability(e,A){let t=await this.agentControl.getAgent(e);if(!t)throw Error("Agent not found");if(!g(t))throw Error("Agent is offline");if(!h(t).includes(A))throw Error("Agent must be updated to use codebases")}async requireRunnableCodebase(e,A){await this.cleanupInternalJobs();let t=await (0,n.getPrismaClient)(),r=await t.codebase.findUnique({where:{id:e},include:{agent:!0,repository:!0,jobs:{where:o.ACTIVE_CODEBASE_BLOCKING_JOB_WHERE,select:{id:!0},take:1}}});if(!r)throw Error("Codebase not found");if(!g(r.agent))throw Error("Agent is offline");if(!h(r.agent).includes(A))throw Error("Agent must be updated to manage Git branches and stashes");if("AVAILABLE"!==r.availability)throw Error(r.statusError||"Codebase is unavailable");if(r.jobs.length)throw Error("Another codebase operation is already running");return r}async waitForJob(e){let A=l.agentEventBus.iterate((0,l.agentJobChangedTopic)(e)),t=Date.now()+3e4;try{for(;Date.now()<t;){let r=await this.agentControl.getJob(e);if(!r)throw Error("Agent job disappeared");if(["SUCCEEDED","FAILED","CANCELLED","TIMED_OUT"].includes(r.status))return r;await Promise.race([A.next(),new Promise(e=>setTimeout(e,t-Date.now()))])}throw await this.agentControl.cancelJob(e),Error("Agent did not respond in time")}finally{await A.return?.()}}publish(e,A,t){l.agentEventBus.publish(l.CODEBASE_CHANGED_TOPIC,{codebaseOverviewChanged:{codebaseId:e,repositoryId:A,agentId:t}})}async cleanupInternalJobs(){return this.cleanupInFlight?this.cleanupInFlight:Date.now()-this.lastCleanupAt<6e4?void 0:(this.cleanupInFlight=this.deleteExpiredInternalJobs().then(()=>{this.lastCleanupAt=Date.now()}).finally(()=>{this.cleanupInFlight=null}),this.cleanupInFlight)}async deleteExpiredInternalJobs(){let e=await (0,n.getPrismaClient)();await e.agentJob.deleteMany({where:{visibility:"SYSTEM",kind:{in:[...r.CODEBASE_JOB_KINDS]},finishedAt:{lt:new Date(Date.now()-9e5)}}})}}])},505228,e=>{"use strict";var A=e.i(749906);e.i(256554);var t=e.i(118387);let r=A.enum(["IN_SYNC","AHEAD","BEHIND","DIVERGED","NO_UPSTREAM","DETACHED","UNKNOWN"]),i=A.enum(["AVAILABLE","MISSING","NOT_REPOSITORY","ORIGIN_MISMATCH","ERROR"]),n=A.object({id:A.string(),path:A.string(),observedOrigin:A.string(),branch:A.string().nullable(),headSha:A.string().nullable(),upstream:A.string().nullable(),ahead:A.number().int().nullable(),behind:A.number().int().nullable(),syncState:r,availability:i,statusError:A.string().nullable(),lastCheckedAt:A.string().nullable(),lastFetchedAt:A.string().nullable(),lastFetchAttemptAt:A.string().nullable().optional(),lastFetchError:A.string().nullable().optional(),defaultBranch:A.string().nullable().optional(),localBranches:A.array(A.string()).optional(),remoteBranches:A.array(A.string()).optional(),createdAt:A.string().optional(),updatedAt:A.string().optional(),repository:A.object({id:A.string(),name:A.string(),description:A.string(),canonicalOrigin:A.string(),displayOrigin:A.string()}),agent:A.object({id:A.string(),name:A.string(),hostname:A.string(),connectionStatus:A.enum(["ONLINE","OFFLINE"])}),activeJob:A.object({id:A.string(),kind:A.string(),status:A.enum(["QUEUED","RUNNING"])}).nullable()}),a=A.object({codebases:A.array(n)}),o=A.object({}),s=A.union([A.object({id:A.string().min(1).describe("Registered codebase ID")}),A.object({path:A.string().min(1).describe("Exact absolute folder path of the codebase"),agentId:A.string().min(1).optional().describe("Agent ID used to disambiguate a shared folder path")})]),l=A.object({codebase:n}),d=A.object({query:A.string().min(1).optional(),agentId:A.string().min(1).optional(),repositoryId:A.string().min(1).optional(),branch:A.string().min(1).optional(),availability:i.optional(),syncState:r.optional(),limit:A.number().int().min(1).max(500).default(100)}).refine(({query:e,agentId:A,repositoryId:t,branch:r,availability:i,syncState:n})=>!!(e||A||t||r||i||n),{message:"At least one codebase search criterion is required"}),u=A.object({codebases:A.array(n),matchingCount:A.number().int().nonnegative()}),c=A.object({id:A.string(),name:A.string(),description:A.string(),canonicalOrigin:A.string(),displayOrigin:A.string(),jiraBranchRegex:A.string().nullable(),keepBaseBranchUpToDate:A.boolean(),codebaseCount:A.number().int().nonnegative(),agentIds:A.array(A.string()),createdAt:A.string(),updatedAt:A.string()}),h=A.object({repositories:A.array(c)}),g=A.object({id:A.string().min(1)}),p=A.object({repository:c.extend({codebases:A.array(n)})});class C extends Error{code;matches;constructor(e,A,t=[]){super(A),this.code=e,this.matches=t,this.name="CodebaseLookupError"}}e.s(["CodebaseToolRecordSchema",0,n,"CodebaseToolsService",0,class{codebasesService;constructor(e){this.codebasesService=e}stringArray(e){try{let A=JSON.parse(e);return Array.isArray(A)?A.filter(e=>"string"==typeof e):[]}catch{return[]}}record(e,A){var r;let i=A.jobs[0]??null;return n.parse({id:A.id,path:A.folder,observedOrigin:A.observedOrigin,branch:A.branch,headSha:A.headSha,upstream:A.upstream,ahead:A.ahead,behind:A.behind,syncState:A.syncState,availability:A.availability,statusError:A.statusError,lastCheckedAt:A.lastCheckedAt?.toISOString()??null,lastFetchedAt:A.lastFetchedAt?.toISOString()??null,lastFetchAttemptAt:A.lastFetchAttemptAt?.toISOString()??null,lastFetchError:A.lastFetchError,defaultBranch:A.defaultBranch,localBranches:this.stringArray(A.localBranchesJson),remoteBranches:this.stringArray(A.remoteBranchesJson),createdAt:A.createdAt.toISOString(),updatedAt:A.updatedAt.toISOString(),repository:{id:e.id,name:e.name,description:e.description,canonicalOrigin:e.canonicalOrigin,displayOrigin:e.displayOrigin},agent:{id:A.agent.id,name:A.agent.name,hostname:A.agent.hostname,connectionStatus:null!==(r=A.agent).lastSeenAt&&Date.now()-r.lastSeenAt.getTime()<=(0,t.agentOnlineWindowMs)(r)&&null===r.disconnectedAt?"ONLINE":"OFFLINE"},activeJob:i?{id:i.id,kind:i.kind,status:i.status}:null})}async list(){return(await this.codebasesService.overview()).flatMap(e=>e.codebases.map(A=>this.record(e,A)))}async getByPath(e,A){if("string"!=typeof e||0===e.trim().length)throw new C("INVALID_PATH","A non-empty codebase path is required");let t=(await this.list()).filter(t=>t.path===e&&(!A||t.agent.id===A));if(0===t.length)throw new C("CODEBASE_NOT_FOUND",`No codebase is registered at path ${e}`);if(t.length>1)throw new C("AMBIGUOUS_PATH",`More than one agent has a codebase registered at path ${e}`,t.map(({agent:e})=>({agentId:e.id,name:e.name,hostname:e.hostname})));return t[0]}async getById(e){let A=(await this.list()).find(A=>A.id===e);if(!A)throw new C("CODEBASE_NOT_FOUND",`No codebase is registered with id ${e}`);return A}async get(e){return"id"in e?this.getById(e.id):this.getByPath(e.path,e.agentId)}async search(e){let A=e.query?.toLocaleLowerCase(),t=(await this.list()).filter(t=>(!e.agentId||t.agent.id===e.agentId)&&(!e.repositoryId||t.repository.id===e.repositoryId)&&(!e.branch||t.branch===e.branch)&&(!e.availability||t.availability===e.availability)&&(!e.syncState||t.syncState===e.syncState)&&(!A||[t.id,t.path,t.observedOrigin,t.branch??"",t.repository.name,t.repository.description,t.repository.canonicalOrigin,t.agent.name,t.agent.hostname].some(e=>e.toLocaleLowerCase().includes(A))));return{codebases:t.slice(0,e.limit),matchingCount:t.length}}async repositories(){return(await this.codebasesService.overview()).map(e=>({id:e.id,name:e.name,description:e.description,canonicalOrigin:e.canonicalOrigin,displayOrigin:e.displayOrigin,jiraBranchRegex:e.jiraBranchRegex,keepBaseBranchUpToDate:e.keepBaseBranchUpToDate,codebaseCount:e.codebases.length,agentIds:[...new Set(e.codebases.map(e=>e.agentId))],createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}))}async repository(e){let A=(await this.codebasesService.overview()).find(A=>A.id===e);if(!A)throw Error("Codebase repository not found");return{...(await this.repositories()).find(A=>A.id===e),codebases:A.codebases.map(e=>this.record(A,e))}}},"GetCodebaseInputSchema",0,s,"GetCodebaseOutputSchema",0,l,"GetCodebaseRepositoriesOutputSchema",0,h,"GetCodebaseRepositoryInputSchema",0,g,"GetCodebaseRepositoryOutputSchema",0,p,"GetCodebasesInputSchema",0,o,"GetCodebasesOutputSchema",0,a,"SearchCodebasesInputSchema",0,d,"SearchCodebasesOutputSchema",0,u])},665537,e=>{"use strict";e.i(933653);var A=e.i(505228);e.i(404482).toJSONSchema(A.CodebaseToolRecordSchema),Object.fromEntries([["BadRequest","The path is missing or invalid"],["NotFound","No codebase uses the requested path"],["AmbiguousPath","Multiple agents use the requested path"],["Unauthorized","A Better Auth user session is required"],["InternalError","Unexpected server error"]].map(([e,A])=>[e,{description:A,content:{"application/json":{schema:{$ref:"#/components/schemas/ErrorResponse"}}}}])),e.s([],665537)},611377,e=>{"use strict";var A=e.i(404165),t=e.i(666680),r=e.i(591135),i=e.i(135475),n=e.i(532982);e.i(592299);var a=e.i(972425),o=e.i(863568),s=e.i(747461);e.i(256554);var l=e.i(848201);let d="default",u="gitlab:pipeline-status-changed",c={merge_requests_events:!0,note_events:!0,pipeline_events:!0,job_events:!0,push_events:!0,enable_ssl_verification:!0};class h extends Error{statusCode;requestId;constructor(e,A,t=null){super(e),this.statusCode=A,this.requestId=t,this.name="GitLabRequestError"}}function g(e){try{return JSON.parse(e)}catch{return null}}function p(e){return JSON.stringify(function e(A){return Array.isArray(A)?A.map(e):A&&"object"==typeof A?Object.fromEntries(Object.keys(A).sort().map(t=>[t,e(A[t])])):A}(e))}let C=/(?:authorization|password|private.?key|secret|signature|token)$/i;function f(e){return p(function e(A,t="",r=!1){if(C.test(t)||r&&"value"===t)return"[REDACTED]";let i=r||"variables"===t;return Array.isArray(A)?A.map(A=>e(A,"",i)):A&&"object"==typeof A?Object.fromEntries(Object.entries(A).map(([A,t])=>[A,e(t,A,i)])):A}(e??{})).slice(0,1e3)}function I(e,A){let t=e instanceof Error?e.message:String(e);return(A?t.replaceAll(A,"[REDACTED]"):t).slice(0,1e3)}function w(e){if(!e)return null;let A=Number(e);return Number.isSafeInteger(A)&&A>=0?A:null}function m(e){let A=w(e);return A&&A>0?A:null}function E(e){return{id:String(e.id),username:e.username,name:e.name,avatarUrl:e.avatar_url??null,webUrl:e.web_url}}function y(e){let A=e.toUpperCase();return new Set(["CREATED","WAITING_FOR_RESOURCE","PREPARING","PENDING","RUNNING","SUCCESS","FAILED","CANCELED","SKIPPED","MANUAL","SCHEDULED"]).has(A)?A:"UNKNOWN"}function B(e){return{id:String(e.id),projectId:String(e.project_id),iid:null==e.iid?null:String(e.iid),ref:e.ref,branch:e.ref,sha:e.sha,source:e.source,status:y(e.status),webUrl:e.web_url,mergeRequests:[],worktreeId:null,worktreeHighlightColor:null,startedAt:e.started_at??e.created_at??null,createdAt:e.created_at??null,updatedAt:e.updated_at??null,finishedAt:e.finished_at??null,duration:e.duration??null,queuedDuration:e.queued_duration??null}}function Q(e){return{id:String(e.id),pipelineId:String(e.pipeline.id),name:e.name,stage:e.stage,status:y(e.status),ref:e.ref,webUrl:e.web_url,allowFailure:e.allow_failure,createdAt:e.created_at??null,startedAt:e.started_at??null,finishedAt:e.finished_at??null,duration:e.duration??null,queuedDuration:e.queued_duration??null,retried:e.retried??!1}}function D(e){return{id:String(e.id),iid:e.iid,projectId:String(e.project_id),title:e.title,description:e.description??"",state:e.state.toUpperCase(),draft:e.draft??!1,webUrl:e.web_url,sourceBranch:e.source_branch,targetBranch:e.target_branch,sha:e.sha,author:E(e.author),reviewers:(e.reviewers??[]).map(E),labels:e.labels??[],detailedMergeStatus:e.detailed_merge_status??"unchecked",mergeWhenPipelineSucceeds:e.merge_when_pipeline_succeeds??!1,squashOnMerge:e.squash_on_merge??!1,hasConflicts:e.has_conflicts??!1,blockingDiscussionsResolved:e.blocking_discussions_resolved??!0,createdAt:e.created_at,updatedAt:e.updated_at,mergedAt:e.merged_at??null}}function b(e){return{id:e.id,individualNote:e.individual_note,notes:e.notes.map(e=>({id:String(e.id),body:e.body,author:E(e.author),createdAt:e.created_at,updatedAt:e.updated_at,system:e.system,resolvable:e.resolvable,resolved:e.resolved??!1,resolvedBy:e.resolved_by?E(e.resolved_by):null}))}}function S(e){return{...e,webhookConfiguredAt:e.webhookConfiguredAt?.toISOString()??null,webhookLastReceivedAt:e.webhookLastReceivedAt?.toISOString()??null}}function k(e){let A=new URLSearchParams;for(let t of Object.keys(e??{}).sort())for(let r of(Array.isArray(e?.[t])?e?.[t]:[e?.[t]])??[])null!=r&&A.append(t,String(r));return A}function R(e){return JSON.stringify(Object.fromEntries(e.entries()))}function v(e){if(!e)return new Headers;try{let A=JSON.parse(e);if(!A||"object"!=typeof A||Array.isArray(A))return new Headers;return new Headers(Object.fromEntries(Object.entries(A).filter(e=>"string"==typeof e[1])))}catch{return new Headers}}function G(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function T(e,A){return Object.prototype.hasOwnProperty.call(e,A)}e.s(["GitLabService",0,class{credentials;workflowEvents;polling;notifications;autoRetryTimer;cacheGeneration;getRequests;invalidatePendingGets(){this.cacheGeneration+=1,this.getRequests.clear()}constructor(e=new o.CredentialService,A,t,r){this.credentials=e,this.workflowEvents=A,this.polling=t,this.notifications=r,this.autoRetryTimer=null,this.cacheGeneration=0,this.getRequests=new Map,this.polling&&(this.polling.register({id:"server:gitlab-auto-retry",kind:"GITLAB_AUTO_RETRY",runtime:"SERVER",enabled:!0,cadenceSeconds:60,details:{}}),queueMicrotask(()=>void this.pollAutoRetry()))}subscribePipelineStatuses(){return l.agentEventBus.iterate(u)}publishPipeline(e){l.agentEventBus.publish(u,{gitlabPipelineStatusChanged:e})}scheduleAutoRetry(e){if(!this.polling)return;this.autoRetryTimer&&clearTimeout(this.autoRetryTimer);let A=1e3*Math.max(30,e);this.autoRetryTimer=setTimeout(()=>void this.pollAutoRetry(),A),this.autoRetryTimer.unref(),this.polling.schedule("server:gitlab-auto-retry",new Date(Date.now()+A))}async pollAutoRetry(){if(!this.polling)return;let e=60;try{let A=await this.getSettings();e=A.pipelinePollIntervalSeconds,this.polling.configure("server:gitlab-auto-retry",{enabled:A.configured,cadenceSeconds:e}),A.configured&&await this.polling.run("server:gitlab-auto-retry",()=>this.reconcileAutoRetries(),e=>({activeRules:e}))}catch{}finally{this.scheduleAutoRetry(e)}}async connection(){let[e,A]=await Promise.all([(0,s.readConnectionSettings)(this.credentials,a.CREDENTIALS.gitlabConnectionSettings,s.gitlabConnectionSettings),this.credentials.getText(a.CREDENTIALS.gitlabAccessToken)]);if(!e||!A)throw Error("GitLab credentials are not configured");return{baseUrl:e.value.baseUrl,token:A}}endpoint(e,A,t){let r;if(!A.startsWith("/"))throw Error("GitLab API paths must be relative");let i=((r=new URL(e)).pathname=`${r.pathname.replace(/\/+$/,"")}/api/v4/`,r),n=new URL(A.slice(1),i);if(n.origin!==i.origin||!n.pathname.startsWith(i.pathname))throw Error("GitLab API request escaped the configured instance root");return n.search=k(t).toString(),n}async fetchRaw(e){var A;let t,r=this.endpoint(e.baseUrl,e.path,e.query),i=await fetch(r,{method:e.method??"GET",headers:{Accept:"application/json","PRIVATE-TOKEN":e.token,...void 0===e.body?{}:{"Content-Type":"application/json"}},body:void 0===e.body?void 0:JSON.stringify(e.body),cache:"no-store",redirect:"manual"}),n=(t=w((A=i.headers).get("ratelimit-reset")),{limit:w(A.get("ratelimit-limit")),remaining:w(A.get("ratelimit-remaining")),resetAt:null===t?null:new Date(1e3*t),requestId:A.get("x-request-id")});if(i.status>=300&&i.status<400)throw new h("GitLab redirected the API request; configure the canonical instance URL",i.status,n.requestId);let a=await i.text(),o=a?g(a):null;if(!i.ok){let e=o&&"object"==typeof o&&"message"in o?JSON.stringify(o.message):a;throw new h(`GitLab API request failed (${i.status})${e?`: ${e.slice(0,500)}`:""}`,i.status,n.requestId)}return{data:o,status:i.status,headers:i.headers,endpoint:r.toString(),rateLimit:n}}async recordRateLimit(e){if(null===e.limit||null===e.remaining)return;let A=await (0,i.getPrismaClient)();await A.gitLabRateLimitSnapshot.upsert({where:{resource:"REST"},create:{id:(0,t.randomUUID)(),resource:"REST",limit:e.limit,remaining:e.remaining,resetAt:e.resetAt,observedAt:new Date},update:{limit:e.limit,remaining:e.remaining,resetAt:e.resetAt,observedAt:new Date}})}async logCall(e){let A=await (0,i.getPrismaClient)();await A.gitLabApiCallLog.create({data:{id:(0,t.randomUUID)(),method:e.method,endpoint:e.endpoint,operation:e.operation,requestSource:e.requestSource,requestSummary:e.requestSummary,source:e.source,durationMs:e.durationMs,statusCode:e.statusCode??null,error:e.error??null,servedStale:e.servedStale??!1,rateLimitLimit:e.rateLimit?.limit??null,rateLimitRemaining:e.rateLimit?.remaining??null,rateLimitResetAt:e.rateLimit?.resetAt??null,requestId:e.rateLimit?.requestId??null}})}async ttl(e){let A=await (0,i.getPrismaClient)(),[t,r]=await Promise.all([A.gitLabRestCacheTtlOverride.findUnique({where:{operation:e}}),A.gitLabSettings.upsert({where:{id:d},create:{id:d},update:{}})]);return t?.ttlSeconds??r.cacheTtlSeconds}async get(e){var A;let r=this.cacheGeneration,n=await this.connection(),a=this.endpoint(n.baseUrl,e.path,e.query).toString(),o={path:e.path,query:e.query??{}},s=(A={baseUrl:n.baseUrl,operation:e.operation,path:e.path,query:e.query},(0,t.createHash)("sha256").update(p({instance:(0,t.createHash)("sha256").update(A.baseUrl).digest("hex"),operation:A.operation,path:A.path,query:[...k(A.query).entries()].sort(([e,A],[t,r])=>e.localeCompare(t)||A.localeCompare(r))})).digest("hex")),l=await (0,i.getPrismaClient)(),d=await l.gitLabRestCacheEntry.findUnique({where:{cacheKey:s}}),u=await this.ttl(e.operation);if(d&&!0!==e.force&&Date.now()-d.fetchedAt.getTime()<1e3*u)return await this.logCall({method:"GET",endpoint:a,operation:e.operation,requestSource:e.source,requestSummary:p(o),source:"CACHE",durationMs:0,statusCode:200}),{data:g(d.responseJson),status:200,headers:v(d.responseHeadersJson),endpoint:a,rateLimit:{limit:null,remaining:null,resetAt:null,requestId:null}};let c=Date.now();try{let A=`${r}\0${(0,t.createHash)("sha256").update(n.token).digest("hex")}\0${s}`,i=this.getRequests.get(A);if(!i){i=(async()=>{let A=await this.fetchRaw({...n,path:e.path,query:e.query});return await Promise.all([r===this.cacheGeneration?l.gitLabRestCacheEntry.upsert({where:{cacheKey:s},create:{id:(0,t.randomUUID)(),cacheKey:s,endpoint:a,operation:e.operation,requestJson:p(o),responseJson:JSON.stringify(A.data),responseHeadersJson:R(A.headers),fetchedAt:new Date},update:{endpoint:a,operation:e.operation,requestJson:p(o),responseJson:JSON.stringify(A.data),responseHeadersJson:R(A.headers),fetchedAt:new Date}}):Promise.resolve(),this.recordRateLimit(A.rateLimit),this.logCall({method:"GET",endpoint:a,operation:e.operation,requestSource:e.source,requestSummary:p(o),source:"LIVE",durationMs:Date.now()-c,statusCode:A.status,rateLimit:A.rateLimit})]),A})(),this.getRequests.set(A,i);let d=()=>{this.getRequests.get(A)===i&&this.getRequests.delete(A)};i.then(d,d)}return await i}catch(t){let A=t instanceof h?t.statusCode:null;if(d&&!1!==e.allowStaleOnError)return await this.logCall({method:"GET",endpoint:a,operation:e.operation,requestSource:e.source,requestSummary:p(o),source:"CACHE",durationMs:Date.now()-c,statusCode:A,error:I(t,n.token),servedStale:!0}),{data:g(d.responseJson),status:200,headers:v(d.responseHeadersJson),endpoint:a,rateLimit:{limit:null,remaining:null,resetAt:null,requestId:null}};throw await this.logCall({method:"GET",endpoint:a,operation:e.operation,requestSource:e.source,requestSummary:p(o),source:"ERROR",durationMs:Date.now()-c,statusCode:A,error:I(t,n.token)}),t}}async mutate(e){this.invalidatePendingGets();let A=await this.connection(),t=this.endpoint(A.baseUrl,e.path).toString(),r=Date.now();try{let i=await this.fetchRaw({...A,path:e.path,method:e.method,body:e.body});return await Promise.all([this.recordRateLimit(i.rateLimit),this.logCall({method:e.method,endpoint:t,operation:e.operation,requestSource:e.source,requestSummary:f(e.body),source:"LIVE",durationMs:Date.now()-r,statusCode:i.status,rateLimit:i.rateLimit}),this.invalidateCache(e.invalidateProjectId)]),i.data}catch(i){throw await this.logCall({method:e.method,endpoint:t,operation:e.operation,requestSource:e.source,requestSummary:f(e.body),source:"ERROR",durationMs:Date.now()-r,statusCode:i instanceof h?i.statusCode:null,error:I(i,A.token)}),i}}async invalidateCache(e){this.invalidatePendingGets();let A=await (0,i.getPrismaClient)();await A.gitLabRestCacheEntry.deleteMany(e?{where:{endpoint:{contains:`/projects/${encodeURIComponent(e)}/`}}}:void 0)}async getSettings(){let e=await (0,i.getPrismaClient)(),[A,t,r]=await Promise.all([e.gitLabSettings.upsert({where:{id:d},create:{id:d},update:{}}),(0,s.readConnectionSettings)(this.credentials,a.CREDENTIALS.gitlabConnectionSettings,s.gitlabConnectionSettings),this.credentials.isConfigured(a.CREDENTIALS.gitlabAccessToken)]),n=A.currentUserId&&A.currentUsername&&A.currentUserName&&A.currentUserWebUrl?{id:A.currentUserId,username:A.currentUsername,name:A.currentUserName,avatarUrl:A.currentUserAvatarUrl,webUrl:A.currentUserWebUrl}:null;return{configured:!!(t&&r&&A.verifiedAt),tokenConfigured:r,baseUrl:t?.value.baseUrl??null,version:A.version,revision:A.revision,viewer:n,pipelinePollIntervalSeconds:A.pipelinePollIntervalSeconds,cacheTtlSeconds:A.cacheTtlSeconds,verifiedAt:A.verifiedAt?.toISOString()??null,updatedAt:A.updatedAt.toISOString()}}async verify(e,A){let[t,r]=await Promise.all([this.fetchRaw({baseUrl:e.baseUrl,token:A,path:"/user"}),this.fetchRaw({baseUrl:e.baseUrl,token:A,path:"/version"})]);if(!function(e){let A=e.match(/^(\d+)\.(\d+)/);if(!A)return!1;let t=Number(A[1]),r=Number(A[2]);return t>19||19===t&&r>=2}(r.data.version))throw Error(`GitLab 19.2 or later is required; the instance reported ${r.data.version}`);return{user:t.data,version:r.data}}async saveSettings(e){let A=function(e){let A;try{A=new URL(e.trim())}catch{throw Error("The GitLab instance URL is not a valid URL")}if("https:"!==A.protocol)throw Error("The GitLab instance URL must use HTTPS");if(A.username||A.password||A.search||A.hash)throw Error("The GitLab instance URL must not contain credentials, a query, or a fragment");return A.pathname=A.pathname.replace(/\/+$/,""),A.toString().replace(/\/$/,"")}(e.baseUrl),t=await this.credentials.getText(a.CREDENTIALS.gitlabAccessToken),r=e.accessToken?.trim()||t;if(!r)throw Error("A GitLab access token with api scope is required");let i=e.pipelinePollIntervalSeconds??60;if(!Number.isInteger(i)||i<30||i>3600)throw Error("GitLab pipeline polling interval must be from 30 to 3600 seconds");let n=await this.verify({baseUrl:A},r),o=[{descriptor:a.CREDENTIALS.gitlabConnectionSettings,value:(0,a.encodeJsonCredential)({baseUrl:A})},...e.accessToken?.trim()||!t?[{descriptor:a.CREDENTIALS.gitlabAccessToken,value:Buffer.from(r,"utf8")}]:[]];return await this.credentials.setMany(o,async e=>{await e.gitLabSettings.upsert({where:{id:d},create:{id:d,currentUserId:String(n.user.id),currentUsername:n.user.username,currentUserName:n.user.name,currentUserAvatarUrl:n.user.avatar_url??null,currentUserWebUrl:n.user.web_url,version:n.version.version,revision:n.version.revision??null,verifiedAt:new Date,pipelinePollIntervalSeconds:i},update:{currentUserId:String(n.user.id),currentUsername:n.user.username,currentUserName:n.user.name,currentUserAvatarUrl:n.user.avatar_url??null,currentUserWebUrl:n.user.web_url,version:n.version.version,revision:n.version.revision??null,verifiedAt:new Date,pipelinePollIntervalSeconds:i}})}),await this.invalidateCache(),this.getSettings()}async testConnection(){let e=await this.connection(),A=await this.verify({baseUrl:e.baseUrl},e.token),t=await (0,i.getPrismaClient)();return await t.gitLabSettings.upsert({where:{id:d},create:{id:d,currentUserId:String(A.user.id),currentUsername:A.user.username,currentUserName:A.user.name,currentUserAvatarUrl:A.user.avatar_url??null,currentUserWebUrl:A.user.web_url,version:A.version.version,revision:A.version.revision??null,verifiedAt:new Date},update:{currentUserId:String(A.user.id),currentUsername:A.user.username,currentUserName:A.user.name,currentUserAvatarUrl:A.user.avatar_url??null,currentUserWebUrl:A.user.web_url,version:A.version.version,revision:A.version.revision??null,verifiedAt:new Date}}),this.getSettings()}async clearCredentials(e=!1){let A=await this.projects(),t=[];for(let e of A.filter(e=>e.webhookId))try{await this.removeProjectWebhook(e.id)}catch{t.push(e.pathWithNamespace)}if(t.length&&!e)throw Error(`Could not remove AIDE-managed webhooks from: ${t.join(", ")}. Retry or force removal.`);await this.credentials.deleteMany([a.CREDENTIALS.gitlabConnectionSettings,a.CREDENTIALS.gitlabAccessToken,a.CREDENTIALS.gitlabWebhookSigningSecrets]),this.invalidatePendingGets();let r=await (0,i.getPrismaClient)();return await r.$transaction([r.gitLabProject.deleteMany(),r.gitLabRestCacheEntry.deleteMany(),r.gitLabSettings.upsert({where:{id:d},create:{id:d},update:{currentUserId:null,currentUsername:null,currentUserName:null,currentUserAvatarUrl:null,currentUserWebUrl:null,version:null,revision:null,verifiedAt:null}})]),this.getSettings()}async projects(){let e=await (0,i.getPrismaClient)();return(await e.gitLabProject.findMany({orderBy:{pathWithNamespace:"asc"}})).map(S)}async projectForCanonicalOrigin(e){let A=await this.getSettings();if(!A.configured||!A.baseUrl)return null;let t=new URL(A.baseUrl),r=`${t.host}${t.pathname}`.replace(/\/+$/,"").toLowerCase(),i=e.trim().replace(/^https?:\/\//i,"").replace(/\.git$/i,"").replace(/\/+$/,"").toLowerCase();return(await this.projects()).find(e=>i===`${r}/${e.pathWithNamespace}`.replace(/\/+/g,"/").toLowerCase())??null}async mergeRequestForBranch(e,A,t=!1){let r=await this.get({path:`/projects/${encodeURIComponent(e)}/merge_requests`,operation:"GitLabWorktreeMergeRequests",source:"WORKTREES",query:{state:"opened",source_branch:A,order_by:"updated_at",sort:"desc",per_page:1},force:t,allowStaleOnError:!t});return r.data[0]?D(r.data[0]):null}async availableProjects(e,A=1,t=50){let r=Math.max(1,Math.min(100,t)),n=await this.get({path:"/projects",operation:"GitLabAvailableProjects",source:"GITLAB_SETTINGS",query:{membership:!0,simple:!0,order_by:"path",sort:"asc",search:e?.trim()||void 0,page:A,per_page:r}}),a=await (0,i.getPrismaClient)(),o=new Set((await a.gitLabProject.findMany({select:{id:!0}})).map(e=>e.id));return{items:n.data.map(e=>({id:String(e.id),name:e.name,pathWithNamespace:e.path_with_namespace,webUrl:e.web_url,defaultBranch:e.default_branch??null,visibility:e.visibility,alreadyManaged:o.has(String(e.id))})),total:w(n.headers.get("x-total"))??n.data.length,page:A,perPage:r,nextPage:m(n.headers.get("x-next-page"))}}async addProject(e){let A=(await this.get({path:`/projects/${encodeURIComponent(e)}`,operation:"GitLabProject",source:"GITLAB_SETTINGS",force:!0})).data,t=await (0,i.getPrismaClient)();return await t.gitLabProject.upsert({where:{id:String(A.id)},create:{id:String(A.id),name:A.name,pathWithNamespace:A.path_with_namespace,webUrl:A.web_url,defaultBranch:A.default_branch??null,visibility:A.visibility},update:{name:A.name,pathWithNamespace:A.path_with_namespace,webUrl:A.web_url,defaultBranch:A.default_branch??null,visibility:A.visibility,enabled:!0}}),this.projects()}async webhookSecrets(){let e=await this.credentials.getJson(a.CREDENTIALS.gitlabWebhookSigningSecrets);return!e||"object"!=typeof e||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(e=>"string"==typeof e[1]))}signingToken(){return`whsec_${(0,t.randomBytes)(32).toString("base64")}`}normalizeWebhookUrl(e){let A=new URL(e.trim());if("https:"!==A.protocol||A.username||A.password||A.search||A.hash)throw Error("GitLab webhook URL must be a public HTTPS URL without credentials, query, or fragment");return A.toString()}async configureProjectWebhook(e,A){await this.credentials.assertWritable();let t=this.normalizeWebhookUrl(A),r=await this.webhookSecrets(),n=r[e]??this.signingToken(),o=await (0,i.getPrismaClient)(),s=await o.gitLabProject.findUnique({where:{id:e}});if(!s)throw Error("The GitLab project is not managed by AIDE");let l=s.webhookId,d=!1,u=null;try{let A={url:t,name:"AIDE",description:"AIDE merge request and pipeline events",signing_token:n,...c};if(l)await this.mutate({method:"PUT",path:`/projects/${encodeURIComponent(e)}/hooks/${encodeURIComponent(l)}`,operation:"GitLabUpdateProjectWebhook",source:"WEBHOOK_MANAGEMENT",body:A,invalidateProjectId:e});else{let t=await this.mutate({method:"POST",path:`/projects/${encodeURIComponent(e)}/hooks`,operation:"GitLabCreateProjectWebhook",source:"WEBHOOK_MANAGEMENT",body:A,invalidateProjectId:e});l=String(t.id)}}catch(e){if(e instanceof h&&[401,403,404].includes(e.statusCode??0))d=!0,l=null,u="Automatic setup requires the Maintainer or Owner role. Configure this project webhook manually.";else throw e}return await this.credentials.setJson(a.CREDENTIALS.gitlabWebhookSigningSecrets,{...r,[e]:n},async A=>{await A.gitLabProject.update({where:{id:e},data:{webhookId:l,webhookState:d?"MANUAL_REQUIRED":"CONFIGURED",webhookError:u,webhookConfiguredAt:d?null:new Date}})}),{project:S(await o.gitLabProject.findUniqueOrThrow({where:{id:e}})),callbackUrl:t,signingToken:d?n:null,manualConfigurationRequired:d}}async removeProjectWebhook(e){let A=await (0,i.getPrismaClient)(),t=await A.gitLabProject.findUnique({where:{id:e}});if(!t)throw Error("The GitLab project is not managed by AIDE");t.webhookId&&await this.mutate({method:"DELETE",path:`/projects/${encodeURIComponent(e)}/hooks/${encodeURIComponent(t.webhookId)}`,operation:"GitLabDeleteProjectWebhook",source:"WEBHOOK_MANAGEMENT",invalidateProjectId:e});let r=await this.webhookSecrets();return delete r[e],await this.credentials.setJson(a.CREDENTIALS.gitlabWebhookSigningSecrets,r,async A=>{await A.gitLabProject.update({where:{id:e},data:{webhookId:null,webhookState:"NOT_CONFIGURED",webhookError:null,webhookConfiguredAt:null}})}),S(await A.gitLabProject.findUniqueOrThrow({where:{id:e}}))}async removeProject(e,A=!1){let t=await (0,i.getPrismaClient)(),r=await t.gitLabProject.findUnique({where:{id:e}});if(!r)return this.projects();if(r.webhookId)try{await this.removeProjectWebhook(e)}catch(e){if(!A)throw e}let n=await this.webhookSecrets();return delete n[e],await this.credentials.setJson(a.CREDENTIALS.gitlabWebhookSigningSecrets,n,async A=>{await A.gitLabProject.delete({where:{id:e}})}),await this.invalidateCache(e),this.projects()}async webhooksEnabled(){let e=await (0,i.getPrismaClient)();return await e.gitLabProject.count({where:{webhookState:{in:["CONFIGURED","MANUAL_REQUIRED"]}}})>0}async mergeRequests(e){let A=Math.max(1,e.page??1),t=Math.max(1,Math.min(100,e.perPage??25));if("PROJECT"===e.scope&&!e.projectId)throw Error("A project is required for project-scoped merge requests");let r=e.projectId?`/projects/${encodeURIComponent(e.projectId)}/merge_requests`:"/merge_requests",i="MINE"===e.scope?"created_by_me":"REVIEW_REQUESTED"===e.scope?"reviews_for_me":"all",n=await this.get({path:r,operation:"GitLabMergeRequests",source:"MERGE_REQUESTS_PAGE",query:{scope:i,state:e.state&&"ALL"!==e.state?e.state.toLowerCase():"all",order_by:"updated_at",sort:"desc",page:A,per_page:t}});return{items:n.data.map(D),total:w(n.headers.get("x-total"))??n.data.length,page:A,perPage:t,nextPage:m(n.headers.get("x-next-page"))}}async mergeRequest(e,A){let t=`/projects/${encodeURIComponent(e)}/merge_requests/${A}`,[r,i,n,a]=await Promise.all([this.get({path:t,operation:"GitLabMergeRequest",source:"MERGE_REQUEST_DETAILS",query:{include_rebase_in_progress:!0}}),this.get({path:`${t}/commits`,operation:"GitLabMergeRequestCommits",source:"MERGE_REQUEST_DETAILS",query:{per_page:100}}),this.get({path:`${t}/discussions`,operation:"GitLabMergeRequestDiscussions",source:"MERGE_REQUEST_DETAILS",query:{per_page:100}}),this.get({path:`${t}/pipelines`,operation:"GitLabMergeRequestPipelines",source:"MERGE_REQUEST_DETAILS",query:{per_page:100}})]);return{...D(r.data),changesCount:r.data.changes_count??null,commitsCount:i.data.length,discussions:n.data.map(b),pipelines:a.data.map(B)}}async createMergeRequest(e){return D(await this.mutate({method:"POST",path:`/projects/${encodeURIComponent(e.projectId)}/merge_requests`,operation:"GitLabCreateMergeRequest",source:"MERGE_REQUESTS_PAGE",body:{source_branch:e.sourceBranch,target_branch:e.targetBranch,title:e.title,description:e.description??void 0,reviewer_ids:e.reviewerIds?.map(Number),labels:e.labels?.join(","),remove_source_branch:e.removeSourceBranch??void 0,squash:e.squash??void 0},invalidateProjectId:e.projectId}))}async updateMergeRequest(e){return D(await this.mutate({method:"PUT",path:`/projects/${encodeURIComponent(e.projectId)}/merge_requests/${e.iid}`,operation:"GitLabUpdateMergeRequest",source:"MERGE_REQUEST_DETAILS",body:{title:e.title??void 0,description:e.description??void 0,state_event:e.stateEvent?.toLowerCase(),reviewer_ids:e.reviewerIds?.map(Number),labels:e.labels?.join(",")},invalidateProjectId:e.projectId}))}async submitReview(e){let A="APPROVE"===e.outcome?"approve":"REQUEST_CHANGES"===e.outcome?"requested_changes":"reviewed";return await this.mutate({method:"POST",path:`/projects/${encodeURIComponent(e.projectId)}/merge_requests/${e.iid}/notes`,operation:"GitLabSubmitReview",source:"MERGE_REQUEST_DETAILS",body:{body:[e.body?.trim(),`/submit_review ${A}`].filter(Boolean).join("\n\n")},invalidateProjectId:e.projectId}),!0}async replyToDiscussion(e){return await this.mutate({method:"POST",path:`/projects/${encodeURIComponent(e.projectId)}/merge_requests/${e.iid}/discussions/${encodeURIComponent(e.discussionId)}/notes`,operation:"GitLabReplyToDiscussion",source:"COMMENTS_PAGE",body:{body:e.body},invalidateProjectId:e.projectId}),b((await this.get({path:`/projects/${encodeURIComponent(e.projectId)}/merge_requests/${e.iid}/discussions/${encodeURIComponent(e.discussionId)}`,operation:"GitLabDiscussion",source:"COMMENTS_PAGE",force:!0})).data)}async setDiscussionResolved(e){return b(await this.mutate({method:"PUT",path:`/projects/${encodeURIComponent(e.projectId)}/merge_requests/${e.iid}/discussions/${encodeURIComponent(e.discussionId)}`,operation:"GitLabResolveDiscussion",source:"COMMENTS_PAGE",body:{resolved:e.resolved},invalidateProjectId:e.projectId}))}async mergeMergeRequest(e){return D(await this.mutate({method:"PUT",path:`/projects/${encodeURIComponent(e.projectId)}/merge_requests/${e.iid}/merge`,operation:"GitLabMergeMergeRequest",source:"MERGE_REQUEST_DETAILS",body:{squash:e.squash??void 0,should_remove_source_branch:e.removeSourceBranch??void 0,auto_merge:e.autoMerge??void 0,sha:e.sha??void 0},invalidateProjectId:e.projectId}))}async pipelineMergeRequests(e,A){try{return(await this.get({path:`/projects/${encodeURIComponent(e)}/repository/commits/${encodeURIComponent(A)}/merge_requests`,operation:"GitLabPipelineMergeRequests",source:"PIPELINES_PAGE",query:{per_page:100}})).data.map(e=>({projectId:String(e.project_id),iid:e.iid,title:e.title,webUrl:e.web_url,sourceBranch:e.source_branch}))}catch{return[]}}async pipelineWorktrees(e,A){let t=new Map,n=[...new Set(A.filter(Boolean))];if(!n.length)return t;let a=await (0,i.getPrismaClient)(),o=await a.gitLabProject.findUnique({where:{id:e},select:{webUrl:!0}});if(!o)return t;let s=(0,r.normalizeGitOrigin)(o.webUrl).canonicalOrigin,l=await a.codebaseRepository.findUnique({where:{canonicalOrigin:s},select:{id:!0}});if(!l)return t;for(let e of(await a.worktree.findMany({where:{missingAt:null,branch:{in:n},codebase:{repositoryId:l.id}},orderBy:{updatedAt:"desc"},select:{id:!0,branch:!0,highlightColor:!0}})))!e.branch||t.has(e.branch)||t.set(e.branch,{id:e.id,highlightColor:e.highlightColor});return t}async enrichPipelines(e,A){if(!A.length)return A;let t=new Map(await (0,n.mapIntegrationRequests)([...new Set(A.map(e=>e.sha))],async A=>[A,await this.pipelineMergeRequests(e,A)])),r=A.map(e=>{var A;let r,i;return A=t.get(e.sha)??[],(i=(r=e.ref.match(/^refs\/merge-requests\/(\d+)\/(?:head|merge)$/))?A.find(e=>e.iid===Number(r[1])):A.find(A=>A.sourceBranch===e.ref))?i.sourceBranch:"merge_request_event"===e.source&&A[0]?A[0].sourceBranch:e.ref}),i=await this.pipelineWorktrees(e,r);return A.map((e,A)=>{let n=r[A]??e.ref,a=i.get(n);return{...e,branch:n,mergeRequests:t.get(e.sha)??[],worktreeId:a?.id??null,worktreeHighlightColor:a?.highlightColor??null}})}async observePipelines(e){if(!e.length)return;let A=await (0,i.getPrismaClient)();await A.$transaction(async A=>{for(let r of e){let e=await A.gitLabPipelineSnapshot.upsert({where:{projectId_headSha:{projectId:r.projectId,headSha:r.sha}},create:{id:(0,t.randomUUID)(),projectId:r.projectId,headSha:r.sha,status:r.status,lastObservedAt:new Date},update:{status:r.status,lastObservedAt:new Date}});await A.gitLabPipelineRecord.upsert({where:{snapshotId_pipelineId:{snapshotId:e.id,pipelineId:r.id}},create:{id:(0,t.randomUUID)(),snapshotId:e.id,pipelineId:r.id,ref:r.ref,status:r.status,webUrl:r.webUrl,source:r.source,gitlabUpdatedAt:r.updatedAt?new Date(r.updatedAt):null,lastObservedAt:new Date},update:{ref:r.ref,status:r.status,webUrl:r.webUrl,source:r.source,gitlabUpdatedAt:r.updatedAt?new Date(r.updatedAt):null,lastObservedAt:new Date}})}})}async pipelines(e,A=1,t=25){let r=Math.max(1,Math.min(100,t)),i=await this.get({path:`/projects/${encodeURIComponent(e)}/pipelines`,operation:"GitLabPipelines",source:"PIPELINES_PAGE",query:{page:A,per_page:r,order_by:"id",sort:"desc"}}),n=await this.enrichPipelines(e,i.data.map(B));return await this.observePipelines(n),{items:n,total:w(i.headers.get("x-total"))??i.data.length,page:A,perPage:r,nextPage:m(i.headers.get("x-next-page"))}}async pipelinesForCommit(e,A){let t=await this.get({path:`/projects/${encodeURIComponent(e)}/pipelines`,operation:"GitLabWorktreePipelines",source:"WORKTREES",query:{sha:A,per_page:100,order_by:"id",sort:"desc"},allowStaleOnError:!0}),r=await this.enrichPipelines(e,t.data.map(B));return await this.observePipelines(r),r}async pipeline(e,A){let t=B((await this.get({path:`/projects/${encodeURIComponent(e)}/pipelines/${encodeURIComponent(A)}`,operation:"GitLabPipeline",source:"PIPELINES_PAGE"})).data);return await this.observePipelines([t]),(await this.enrichPipelines(e,[t]))[0]??t}async pipelineJobs(e,A){let t=(await this.get({path:`/projects/${encodeURIComponent(e)}/pipelines/${encodeURIComponent(A)}/jobs`,operation:"GitLabPipelineJobs",source:"PIPELINES_PAGE",query:{include_retried:!0,per_page:100}})).data.map(Q),r=await (0,i.getPrismaClient)();return await r.gitLabPipelineRecord.updateMany({where:{pipelineId:A},data:{jobsJson:JSON.stringify(t),lastObservedAt:new Date}}),t}async createPipeline(e,A,t=[]){let r=B(await this.mutate({method:"POST",path:`/projects/${encodeURIComponent(e)}/pipeline`,operation:"GitLabCreatePipeline",source:"PIPELINES_PAGE",body:{ref:A,variables:t.map(e=>({...e,variable_type:"env_var"}))},invalidateProjectId:e}));return await this.observePipelines([r]),this.publishPipeline(r),r}async retryPipeline(e,A){let t=B(await this.mutate({method:"POST",path:`/projects/${encodeURIComponent(e)}/pipelines/${encodeURIComponent(A)}/retry`,operation:"GitLabRetryPipeline",source:"PIPELINES_PAGE",invalidateProjectId:e}));return await this.observePipelines([t]),this.publishPipeline(t),t}async cancelPipeline(e,A){let t=B(await this.mutate({method:"POST",path:`/projects/${encodeURIComponent(e)}/pipelines/${encodeURIComponent(A)}/cancel`,operation:"GitLabCancelPipeline",source:"PIPELINES_PAGE",invalidateProjectId:e}));return await this.observePipelines([t]),this.publishPipeline(t),t}async retryJob(e,A){return Q(await this.mutate({method:"POST",path:`/projects/${encodeURIComponent(e)}/jobs/${encodeURIComponent(A)}/retry`,operation:"GitLabRetryJob",source:"PIPELINES_PAGE",invalidateProjectId:e}))}async cachedEntries(e=50,A=0){let t=await (0,i.getPrismaClient)(),[r,n]=await Promise.all([t.gitLabRestCacheEntry.findMany({orderBy:{fetchedAt:"desc"},take:e,skip:A}),t.gitLabRestCacheEntry.count()]),a=Date.now();return{items:await Promise.all(r.map(async e=>({id:e.id,operation:e.operation,endpoint:e.endpoint,fetchedAt:e.fetchedAt.toISOString(),stale:a-e.fetchedAt.getTime()>=await this.ttl(e.operation)*1e3}))),total:n,limit:e,offset:A}}async cacheMetrics(){let e=await (0,i.getPrismaClient)(),[A,t]=await Promise.all([e.gitLabRestCacheEntry.count(),e.gitLabApiCallLog.findMany({select:{source:!0,servedStale:!0,durationMs:!0}})]),r=t.reduce((e,A)=>e+A.durationMs,0);return{entries:A,calls:t.length,liveCalls:t.filter(({source:e})=>"LIVE"===e).length,cacheHits:t.filter(({source:e})=>"CACHE"===e).length,errors:t.filter(({source:e})=>"ERROR"===e).length,staleFallbacks:t.filter(({servedStale:e})=>e).length,averageDurationMs:t.length?r/t.length:0}}async cachedEntry(e){let A=await (0,i.getPrismaClient)(),t=await A.gitLabRestCacheEntry.findUnique({where:{id:e}});return t?{id:t.id,operation:t.operation,endpoint:t.endpoint,fetchedAt:t.fetchedAt.toISOString(),stale:Date.now()-t.fetchedAt.getTime()>=await this.ttl(t.operation)*1e3,request:g(t.requestJson),response:g(t.responseJson)}:null}async clearCache(){return await this.invalidateCache(),!0}async deleteCachedEntry(e){this.invalidatePendingGets();let A=await (0,i.getPrismaClient)();return(await A.gitLabRestCacheEntry.deleteMany({where:{id:e}})).count>0}async updateCacheTtl(e){let A=60*e;if(!Number.isInteger(e)||A<1||A>86400)throw Error("GitLab cache TTL must be from 1 second to 24 hours");let t=await (0,i.getPrismaClient)();return await t.gitLabSettings.upsert({where:{id:d},create:{id:d,cacheTtlSeconds:A},update:{cacheTtlSeconds:A}}),this.getSettings()}async apiCalls(e=50,A=0){let t=await (0,i.getPrismaClient)(),[r,n]=await Promise.all([t.gitLabApiCallLog.findMany({orderBy:{createdAt:"desc"},take:e,skip:A}),t.gitLabApiCallLog.count()]);return{items:r.map(e=>({...e,source:e.source,rateLimitResetAt:e.rateLimitResetAt?.toISOString()??null,createdAt:e.createdAt.toISOString()})),total:n,limit:e,offset:A}}async webhookDeliveries(e=50,A=0){let t=await (0,i.getPrismaClient)(),[r,n]=await Promise.all([t.gitLabWebhookDelivery.findMany({orderBy:{receivedAt:"desc"},take:e,skip:A}),t.gitLabWebhookDelivery.count()]);return{items:r.map(e=>({id:e.id,webhookId:e.webhookId,eventType:e.eventType,projectId:e.projectId,objectKind:e.objectKind,action:e.action,outcome:e.outcome,error:e.error,receivedAt:e.receivedAt.toISOString(),processedAt:e.processedAt?.toISOString()??null})),total:n,limit:e,offset:A}}async rateLimitSnapshots(){let e=await (0,i.getPrismaClient)();return(await e.gitLabRateLimitSnapshot.findMany({orderBy:{observedAt:"desc"}})).map(e=>({...e,resetAt:e.resetAt?.toISOString()??null,observedAt:e.observedAt.toISOString(),createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}))}async cacheTtlOverrides(){let e=await (0,i.getPrismaClient)();return(await e.gitLabRestCacheTtlOverride.findMany({orderBy:{operation:"asc"}})).map(e=>({...e,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}))}async saveCacheTtlOverride(e,A){let t=e.trim();if(!t)throw Error("GitLab cache operation is required");if(!Number.isInteger(A)||A<1||A>86400)throw Error("GitLab cache TTL must be from 1 second to 24 hours");let r=await (0,i.getPrismaClient)();return await r.gitLabRestCacheTtlOverride.upsert({where:{operation:t},create:{operation:t,ttlSeconds:A},update:{ttlSeconds:A}}),this.cacheTtlOverrides()}async deleteCacheTtlOverride(e){let A=await (0,i.getPrismaClient)();return await A.gitLabRestCacheTtlOverride.deleteMany({where:{operation:e}}),this.cacheTtlOverrides()}async autoRetryRules(e){let A=await (0,i.getPrismaClient)();return(await A.gitLabAutoRetryRule.findMany({where:e?{projectId:e}:void 0,include:{executions:{orderBy:{createdAt:"desc"}}},orderBy:{updatedAt:"desc"}})).map(e=>({...e,lastAttemptAt:e.lastAttemptAt?.toISOString()??null,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString(),executions:e.executions.map(e=>({...e,createdAt:e.createdAt.toISOString(),updatedAt:e.updatedAt.toISOString()}))}))}async saveAutoRetryRule(e){if(!Number.isInteger(e.maxAttempts)||e.maxAttempts<1||e.maxAttempts>100)throw Error("GitLab auto-retry attempts must be from 1 to 100");let A=await (await (0,i.getPrismaClient)()).gitLabProject.findUnique({where:{id:e.projectId}});if(!A?.enabled)throw Error("A managed GitLab project is required");let r=await (0,i.getPrismaClient)(),n=e.id?null:await r.gitLabAutoRetryRule.findFirst({where:{projectId:e.projectId,pipelineId:e.pipelineId??null},select:{id:!0}}),a=e.id??n?.id??(0,t.randomUUID)();return await r.gitLabAutoRetryRule.upsert({where:{id:a},create:{id:a,projectId:e.projectId,pipelineId:e.pipelineId??null,enabled:e.enabled??!0,maxAttempts:e.maxAttempts},update:{projectId:e.projectId,pipelineId:e.pipelineId??null,enabled:e.enabled??!0,maxAttempts:e.maxAttempts}}),queueMicrotask(()=>void this.reconcileAutoRetries()),(await this.autoRetryRules()).find(e=>e.id===a)}async deleteAutoRetryRule(e){let A=await (0,i.getPrismaClient)();return(await A.gitLabAutoRetryRule.deleteMany({where:{id:e}})).count>0}async autoRetryFailedPipeline(e,A){let r=await (0,i.getPrismaClient)();for(let i of(await r.gitLabAutoRetryRule.findMany({where:{projectId:e,enabled:!0,OR:[{pipelineId:null},{pipelineId:A}]}}))){let n,a=await r.gitLabAutoRetryExecution.count({where:{ruleId:i.id,pipelineId:A}});if(a>=i.maxAttempts)continue;let o=a+1;try{n=await r.gitLabAutoRetryExecution.create({data:{id:(0,t.randomUUID)(),ruleId:i.id,pipelineId:A,attempt:o,status:"RUNNING"}})}catch{continue}try{await this.retryPipeline(e,A),await r.$transaction([r.gitLabAutoRetryExecution.update({where:{id:n.id},data:{status:"RETRIED"}}),r.gitLabAutoRetryRule.update({where:{id:i.id},data:{attempts:{increment:1},lastAttemptAt:new Date,lastError:null}})])}catch(A){let e=I(A);await r.$transaction([r.gitLabAutoRetryExecution.update({where:{id:n.id},data:{status:"FAILED",lastError:e}}),r.gitLabAutoRetryRule.update({where:{id:i.id},data:{lastAttemptAt:new Date,lastError:e}})])}}}async reconcileAutoRetries(){let e=await (0,i.getPrismaClient)(),A=await e.gitLabAutoRetryRule.findMany({where:{enabled:!0},select:{projectId:!0},distinct:["projectId"]});for(let{projectId:e}of A)for(let A of(await this.pipelines(e,1,100)).items)["FAILED","CANCELED"].includes(A.status)&&await this.autoRetryFailedPipeline(e,A.id);return A.length}async recordWebhookWorkflowEvents(e){if(!this.workflowEvents)return;let A=A=>{let t=e.payload[A];return t&&"object"==typeof t&&!Array.isArray(t)?t:{}},t=A("project"),r=A("object_attributes"),i=A("user"),n=String(e.payload.object_kind??"").toLowerCase(),a={repo:{provider:"GITLAB",gitlabProjectId:e.projectId,name:t.name??null,pathWithNamespace:t.path_with_namespace??null,webUrl:t.web_url??null},actor:{id:i.id??null,username:i.username??null,name:i.name??null}};if("merge_request"===n)a.pr={provider:"GITLAB",id:r.id??null,iid:r.iid??null,number:r.iid??null,title:r.title??null,description:r.description??null,state:r.state??null,action:r.action??null,isDraft:r.draft??!1,headRefName:r.source_branch??null,headRefOid:r.last_commit&&"object"==typeof r.last_commit?r.last_commit.id??null:null,targetBranch:r.target_branch??null,url:r.url??null,labels:e.payload.labels??r.labels??[]};else if("pipeline"===n)a.pipeline={id:r.id??null,status:r.status??null,ref:r.ref??null,sha:r.sha??null,source:r.source??null};else if("build"===n)a.job={id:e.payload.build_id??null,name:e.payload.build_name??null,stage:e.payload.build_stage??null,status:e.payload.build_status??null},a.pipeline={id:A("pipeline").id??null};else if("note"===n){let e=A("merge_request");a.pr={provider:"GITLAB",id:e.id??null,iid:e.iid??null,number:e.iid??null,title:e.title??null,state:e.state??null,headRefName:e.source_branch??null,targetBranch:e.target_branch??null,url:e.url??null},a.comment={id:r.id??null,body:r.note??null,url:r.url??null,author:{id:i.id??null,username:i.username??null,name:i.name??null}}}else"push"===n&&(a.push={ref:e.payload.ref??null,before:e.payload.before??null,after:e.payload.after??null,commits:e.payload.commits??[]});let o=function(e){let A=String(e.object_kind??"").toLowerCase(),t=G(e.object_attributes),r=G(e.changes),i=String(t.action??"").toLowerCase(),n=String(t.status??"").toLowerCase(),a=[];if("merge_request"===A){var o;let e="update"===i&&T(r,"draft")&&!1===(Array.isArray(o=r.draft)?o[1]:G(o).current);(["open","reopen"].includes(i)||e)&&a.push("GITLAB_MR_STATE"),["close","merge"].includes(i)&&a.push("GITLAB_MR_CLOSED"),"update"===i&&"string"==typeof t.oldrev&&t.oldrev.trim()&&a.push("GITLAB_MR_SYNCHRONIZED"),("approved"===i||"approval"===i)&&a.push("GITLAB_REVIEW_APPROVED"),"update"===i&&T(r,"labels")&&a.push("GITLAB_MR_LABEL")}else if("note"===A){if(!Object.keys(G(e.merge_request)).length)return[];a.push("GITLAB_REVIEW_COMMENT","GITLAB_NOTE_COMMAND");let A=String(t.note??"");A.includes("/submit_review requested_changes")&&a.push("GITLAB_REVIEW_CHANGES_REQUESTED"),A.includes("/submit_review approve")&&a.push("GITLAB_REVIEW_APPROVED")}else if("pipeline"===A)a.push("GITLAB_PIPELINE_STATUS_CHANGED"),["success","failed","canceled","skipped"].includes(n)&&a.push("GITLAB_PIPELINE_RESULT"),"failed"===n&&a.push("GITLAB_PIPELINE_FAILED"),"success"===n&&a.push("GITLAB_PIPELINE_SUCCEEDED");else if("build"===A)a.push("GITLAB_JOB_STATUS_CHANGED");else if("push"===A){let A=String(G(e.project).default_branch??""),t=String(e.ref??"");A&&t===`refs/heads/${A}`&&a.push("GITLAB_PUSH_DEFAULT")}return[...new Set(a)]}(e.payload);await Promise.all([...new Set(o)].map(A=>this.workflowEvents.record({kind:A,subjectKey:`${e.projectId}:${String(r.iid??r.id??e.messageId)}`,dedupeKey:`gitlab:${e.messageId}:${A}`,payload:{sessionData:a,providerEvent:e.payload}})))}async recordWebhookNotification(e){if(!this.notifications)return;let A=e.payload.object_attributes&&"object"==typeof e.payload.object_attributes?e.payload.object_attributes:{},t=String(e.payload.object_kind??"").toLowerCase(),r=null,n="/gitlab/merge-requests",a="GitLab update",o="GitLab reported an update.",s="GITLAB_MERGE_REQUEST",l=`${e.projectId}:${String(A.iid??A.id??e.messageId)}`;if("pipeline"===t){let t=String(A.status??"").toLowerCase();if("success"===t&&(r="GITLAB_PIPELINE_SUCCEEDED"),"failed"===t&&(r="GITLAB_PIPELINE_FAILED"),!r)return;let i=String(A.id??"");n=`/gitlab/pipelines?project=${encodeURIComponent(e.projectId)}&pipeline=${encodeURIComponent(i)}`,a="success"===t?"GitLab pipeline succeeded":"GitLab pipeline failed",o=`${String(A.ref??"Pipeline")} \xb7 #${i}`,s="GITLAB_PIPELINE",l=`${e.projectId}:${i}`}else if("merge_request"===t){let t=await (await (0,i.getPrismaClient)()).gitLabSettings.findUnique({where:{id:d},select:{currentUserId:!0,currentUsername:!0}});if(!function(e,A){var t;let r,i,n;if("merge_request"!==String(e.object_kind??"").toLowerCase()||!A.id&&!A.username)return!1;let a=String(G(e.object_attributes).action??"").toLowerCase(),o=e=>null!=A.id&&String(e.id??"")===A.id||null!=A.username&&String(e.username??"").toLowerCase()===A.username.toLowerCase();if(["open","reopen"].includes(a))return!!Array.isArray(e.reviewers)&&e.reviewers.map(G).some(o);if("update"!==a)return!1;let s=G(e.changes);if(!T(s,"reviewers"))return!1;let l=(r=G(t=s.reviewers),i=Array.isArray(t)?t:[r.previous,r.current],{previous:(n=e=>Array.isArray(e)?e.map(G).filter(e=>Object.keys(e).length):[])(i[0]),current:n(i[1])}),d=l.current.find(o);return!!d&&(!0===d.re_requested||!l.previous.some(o))}(e.payload,{id:t?.currentUserId??null,username:t?.currentUsername??null}))return;r="GITLAB_REVIEW_REQUESTED";let s=String(A.iid??"");n=`/gitlab/merge-requests/${encodeURIComponent(e.projectId)}/${encodeURIComponent(s)}`,a="GitLab review requested",o=String(A.title??`Merge request !${s}`)}if(!r)return;let u=await (0,i.getPrismaClient)(),c=await u.$transaction(A=>this.notifications.recordInTransaction(A,{dedupeKey:`gitlab:${e.messageId}:${r}`,typeKey:r,title:a,body:o,href:n,resourceKind:s,resourceId:l}));this.notifications.created(c)}async handleWebhook(e){let r,n=e.headers.get("webhook-id"),a=e.headers.get("webhook-timestamp"),o=e.headers.get("webhook-signature"),s=e.headers.get("x-gitlab-event")??"Unknown Hook";if(!n||!a||!o)throw Error("Missing GitLab Standard Webhook signature headers");let l=Number(a);if(!Number.isFinite(l)||Math.abs(Date.now()/1e3-l)>300)throw Error("GitLab webhook timestamp is outside the replay window");let d=g(e.rawBody);if(!d||"object"!=typeof d)throw Error("Invalid GitLab webhook JSON");let u=(r=d.project)&&"object"==typeof r&&"id"in r?String(r.id):"number"==typeof d.project_id?String(d.project_id):null;if(!u)throw Error("GitLab webhook payload does not identify a project");let c=(await this.webhookSecrets())[u];if(!c?.startsWith("whsec_"))throw Error("No signing token is configured for this GitLab project");!function(e){let A=Number(e.timestamp),r=e.now??Date.now();if(!Number.isFinite(A)||Math.abs(r/1e3-A)>300)throw Error("GitLab webhook timestamp is outside the replay window");if(!e.signingToken.startsWith("whsec_"))throw Error("Invalid GitLab webhook signing token");let i=Buffer.from(e.signingToken.slice(6),"base64"),n=(0,t.createHmac)("sha256",i).update(`${e.webhookId}.${e.timestamp}.${e.rawBody}`).digest();if(!e.signature.split(/\s+/).flatMap(e=>{let[A,t]=e.split(",",2);if("v1"!==A||!t)return[];try{return[Buffer.from(t,"base64")]}catch{return[]}}).some(e=>e.length===n.length&&(0,t.timingSafeEqual)(e,n)))throw Error("Invalid GitLab webhook signature")}({rawBody:e.rawBody,webhookId:n,timestamp:a,signature:o,signingToken:c});let h=await (0,i.getPrismaClient)(),p=d.object_attributes,C=p&&"object"==typeof p&&"action"in p?String(p.action):null,f={eventType:s,projectId:u,objectKind:"string"==typeof d.object_kind?d.object_kind:null,action:C,outcome:"RECEIVED",error:null,payloadJson:e.rawBody.slice(0,1e6),receivedAt:new Date(1e3*l),processedAt:null};try{await h.gitLabWebhookDelivery.create({data:{id:(0,t.randomUUID)(),webhookId:n,...f}})}catch(e){if(!("object"==typeof e&&null!==e&&"code"in e&&"P2002"===e.code))throw e;if(0===(await h.gitLabWebhookDelivery.updateMany({where:{webhookId:n,outcome:{notIn:["PROCESSED","IGNORED"]}},data:f})).count)return{duplicate:!0}}let w=async(e,A=null)=>{await h.gitLabWebhookDelivery.update({where:{webhookId:n},data:{outcome:e,error:A,processedAt:new Date}})};try{if(this.invalidatePendingGets(),await h.$transaction([h.gitLabProject.updateMany({where:{id:u},data:{webhookLastReceivedAt:new Date,webhookError:null}}),h.gitLabRestCacheEntry.deleteMany({where:{endpoint:{contains:`/projects/${encodeURIComponent(u)}/`}}})]),(0,A.publishIntegrationConfiguration)("gitlab"),await this.recordWebhookWorkflowEvents({messageId:n,eventType:s,projectId:u,payload:d}),await this.recordWebhookNotification({messageId:n,projectId:u,payload:d}),"pipeline"===String(d.object_kind??"").toLowerCase()&&["failed","canceled"].includes(String(d.object_attributes&&"object"==typeof d.object_attributes&&"status"in d.object_attributes?d.object_attributes.status:"").toLowerCase())){let e=d.object_attributes;null!=e.id&&await this.autoRetryFailedPipeline(u,String(e.id))}if("pipeline"===String(d.object_kind??"").toLowerCase()){let e=d.object_attributes;if(null!=e.id)try{this.publishPipeline(await this.pipeline(u,String(e.id)))}catch{}}return await w("PROCESSED"),{duplicate:!1}}catch(e){throw await w("ERROR",I(e,c)),e}}}])},375240,e=>{"use strict";e.i(611377),e.s([])},785730,e=>{"use strict";e.i(592299);var A=e.i(747461),t=e.i(972425),r=e.i(863568);let i={"exact-primary":"EXACT_PRIMARY","prefixed-primary":"PREFIXED_PRIMARY","exact-restore":"EXACT_RESTORE","prefixed-restore":"PREFIXED_RESTORE"};function n(e,A){return A?e.split(A).join("[REDACTED]"):e}function a(e){return{id:e.id,key:e.key,version:e.version,scope:e.scope,repoId:e.repoId,updatedAt:e.updatedAt,locationId:e.locationId}}e.s(["CacheServerService",0,class{credentials;constructor(e=new r.CredentialService){this.credentials=e}async storedSettings(){return(0,A.readConnectionSettings)(this.credentials,t.CREDENTIALS.cacheServerSettings,A.cacheServerConnectionSettings)}async getSettings(){let[e,A]=await Promise.all([this.storedSettings(),this.credentials.isConfigured(t.CREDENTIALS.cacheServerApiKey)]);return{configured:!!(e&&A),baseUrl:e?.value.baseUrl??null,apiKeyConfigured:A,headers:(e?.value.headers??[]).map(({name:e})=>({name:e,valueConfigured:!0})),updatedAt:(e?.updatedAt??new Date(0)).toISOString()}}async saveSettings(e){let A=function(e){let A,t=e.trim().replace(/\/+$/,"");if(!t)throw Error("A cache server base URL is required");try{A=new URL(t)}catch{throw Error("The cache server base URL is not a valid URL")}if("http:"!==A.protocol&&"https:"!==A.protocol)throw Error("The cache server base URL must use http or https");return t}(e.baseUrl),r=await this.credentials.isConfigured(t.CREDENTIALS.cacheServerApiKey),i=e.apiKey?.trim()||(r?await this.credentials.getText(t.CREDENTIALS.cacheServerApiKey):null);if(!i)throw Error("A cache server API key is required");let n=await this.storedSettings(),a=n?.value.headers??[],o={baseUrl:A,headers:function(e,A){if(!e)return[];let t=new Map(A.map(e=>[e.name.toLowerCase(),e.value])),r=new Set,i=[];for(let A of e){let e=A.name.trim();if(!e)continue;let n=e.toLowerCase();if(r.has(n))continue;r.add(n);let a=A.value||t.get(n);if(!a)throw Error(`A value is required for the ${e} header`);i.push({name:e,value:a})}return i}(e.headers,a)},s=[...e.apiKey?.trim()||!r?[{descriptor:t.CREDENTIALS.cacheServerApiKey,value:Buffer.from(i,"utf8")}]:[],...n&&JSON.stringify(o)===JSON.stringify(n.value)?[]:[{descriptor:t.CREDENTIALS.cacheServerSettings,value:(0,t.encodeJsonCredential)(o)}]];return s.length&&await this.credentials.setMany(s),this.getSettings()}async clearSettings(){return await this.credentials.deleteMany([t.CREDENTIALS.cacheServerApiKey,t.CREDENTIALS.cacheServerSettings]),this.getSettings()}async testConnection(){var e;if(!("object"==typeof(e=await this.request("GET","/cache-entries",{query:{itemsPerPage:1,page:1}}))&&null!==e&&"number"==typeof e.total&&Number.isInteger(e.total)&&e.total>=0&&Array.isArray(e.items)))throw Error("Cache server returned an invalid cache entry response");return this.getSettings()}async listCacheEntries(e){let A=await this.request("GET","/cache-entries",{query:{key:e.key?.trim()||void 0,version:e.version?.trim()||void 0,scope:e.scope?.trim()||void 0,repoId:e.repoId?.trim()||void 0,itemsPerPage:e.itemsPerPage??20,page:e.page??1}});return{total:A?.total??0,items:(A?.items??[]).map(a)}}async getCacheEntry(e){let A=await this.request("GET",`/cache-entries/${encodeURIComponent(e)}`,{allowNotFound:!0});return A?a(A):null}async getCacheEntryDetail(e){let A=await this.getCacheEntry(e);if(!A)return null;let t=A.locationId?await this.getStorageLocation(A.locationId):null;return{entry:A,location:t}}async getStorageLocation(e){let A=await this.request("GET",`/storage-locations/${encodeURIComponent(e)}`,{allowNotFound:!0});return A?{id:A.id,folderName:A.folderName,partCount:A.partCount,mergeStartedAt:A.mergeStartedAt??null,mergedAt:A.mergedAt??null,partsDeletedAt:A.partsDeletedAt??null,lastDownloadedAt:A.lastDownloadedAt??null,sizeBytes:A.sizeBytes??null}:null}async matchCacheEntry(e){let A=(e.restoreKeys??[]).map(e=>e.trim()).filter(Boolean),t=e.scopes.map(e=>e.trim()).filter(Boolean),r=await this.request("GET","/cache-entries/match",{query:{primaryKey:e.primaryKey,restoreKeys:A.length>0?A:void 0,scopes:t,repoId:e.repoId,version:e.version}});if(!r)return null;let n=i[r.type];if(!n)throw Error("Cache server returned an unknown match type");return{match:a(r.match),type:n}}async deleteCacheEntry(e){return await this.request("DELETE",`/cache-entries/${encodeURIComponent(e)}`,{allowNotFound:!0}),!0}async deleteCacheEntriesByIds(e){for(let A of e)await this.deleteCacheEntry(A);return!0}async deleteCacheEntries(e){let A=e.repoId?.trim();if(A){let t=new Set,r=1,i=0;do{let n=await this.listCacheEntries({...e,repoId:A,itemsPerPage:100,page:r});for(let e of(i=n.total,n.items))e.repoId===A&&t.add(e.id);r+=1}while((r-1)*100<i)return this.deleteCacheEntriesByIds([...t])}let t={};return e.key?.trim()&&(t.key=e.key.trim()),e.version?.trim()&&(t.version=e.version.trim()),e.scope?.trim()&&(t.scope=e.scope.trim()),await this.request("DELETE","/cache-entries",{body:t}),!0}async deleteStorageLocation(e){return await this.request("DELETE",`/storage-locations/${encodeURIComponent(e)}`,{allowNotFound:!0}),!0}async requireConfig(){let e=await this.storedSettings();if(!e)throw Error("The cache server is not configured");let A=await this.credentials.getText(t.CREDENTIALS.cacheServerApiKey);if(!A)throw Error("The cache server is not configured");return{baseUrl:e.value.baseUrl,apiKey:A,headers:e.value.headers}}buildUrl(e,A,t){let r=new URL(`${e}${A}`);if(t){for(let[e,A]of Object.entries(t))if(null!=A)if(Array.isArray(A))for(let t of A)r.searchParams.append(e,t);else r.searchParams.append(e,String(A))}return r.toString()}async request(e,A,t={}){let r,i,a=await this.requireConfig(),o=this.buildUrl(a.baseUrl,A,t.query),s={accept:"application/json"};for(let e of a.headers)s[e.name]=e.value;s["x-api-key"]=a.apiKey,void 0!==t.body&&(s["content-type"]="application/json");try{r=await fetch(o,{method:e,headers:s,body:void 0!==t.body?JSON.stringify(t.body):void 0,cache:"no-store"})}catch(e){throw Error(n(e instanceof Error?e.message:String(e),a.apiKey))}if(t.allowNotFound&&404===r.status)return null;let l=await r.text();if(l)try{i=JSON.parse(l)}catch{if(!r.ok)throw Error(`Cache server returned HTTP ${r.status}`);i=void 0}if(!r.ok)throw Error(n(i&&"object"==typeof i&&"message"in i&&"string"==typeof i.message?i.message:`Cache server returned HTTP ${r.status}`,a.apiKey));return i??null}}])},224354,e=>{"use strict";e.i(785730),e.s([])},76389,(e,A,t)=>{var r,i;i=r||(r={}),function(A){var t="object"==typeof globalThis?globalThis:e.g,r=n(i);function n(e,A){return function(t,r){Object.defineProperty(e,t,{configurable:!0,writable:!0,value:r}),A&&A(t,r)}}void 0!==t.Reflect&&(r=n(t.Reflect,r)),A(r,t),void 0===t.Reflect&&(t.Reflect=i)}(function(e,A){var t,r=Object.prototype.hasOwnProperty,i="function"==typeof Symbol,n=i&&void 0!==Symbol.toPrimitive?Symbol.toPrimitive:"@@toPrimitive",a=i&&void 0!==Symbol.iterator?Symbol.iterator:"@@iterator",o="function"==typeof Object.create,s=({__proto__:[]})instanceof Array,l=!o&&!s,d={create:o?function(){return U(Object.create(null))}:s?function(){return U({__proto__:null})}:function(){return U({})},has:l?function(e,A){return r.call(e,A)}:function(e,A){return A in e},get:l?function(e,A){return r.call(e,A)?e[A]:void 0}:function(e,A){return e[A]}},u=Object.getPrototypeOf(Function),c="function"==typeof Map&&"function"==typeof Map.prototype.entries?Map:function(){var e={},A=[],t=function(){function e(e,A,t){this._index=0,this._keys=e,this._values=A,this._selector=t}return e.prototype["@@iterator"]=function(){return this},e.prototype[a]=function(){return this},e.prototype.next=function(){var e=this._index;if(e>=0&&e<this._keys.length){var t=this._selector(this._keys[e],this._values[e]);return e+1>=this._keys.length?(this._index=-1,this._keys=A,this._values=A):this._index++,{value:t,done:!1}}return{value:void 0,done:!0}},e.prototype.throw=function(e){throw this._index>=0&&(this._index=-1,this._keys=A,this._values=A),e},e.prototype.return=function(e){return this._index>=0&&(this._index=-1,this._keys=A,this._values=A),{value:e,done:!0}},e}();function r(){this._keys=[],this._values=[],this._cacheKey=e,this._cacheIndex=-2}return Object.defineProperty(r.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),r.prototype.has=function(e){return this._find(e,!1)>=0},r.prototype.get=function(e){var A=this._find(e,!1);return A>=0?this._values[A]:void 0},r.prototype.set=function(e,A){var t=this._find(e,!0);return this._values[t]=A,this},r.prototype.delete=function(A){var t=this._find(A,!1);if(t>=0){for(var r=this._keys.length,i=t+1;i<r;i++)this._keys[i-1]=this._keys[i],this._values[i-1]=this._values[i];return this._keys.length--,this._values.length--,v(A,this._cacheKey)&&(this._cacheKey=e,this._cacheIndex=-2),!0}return!1},r.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=e,this._cacheIndex=-2},r.prototype.keys=function(){return new t(this._keys,this._values,i)},r.prototype.values=function(){return new t(this._keys,this._values,n)},r.prototype.entries=function(){return new t(this._keys,this._values,o)},r.prototype["@@iterator"]=function(){return this.entries()},r.prototype[a]=function(){return this.entries()},r.prototype._find=function(e,A){if(!v(this._cacheKey,e)){this._cacheIndex=-1;for(var t=0;t<this._keys.length;t++)if(v(this._keys[t],e)){this._cacheIndex=t;break}}return this._cacheIndex<0&&A&&(this._cacheIndex=this._keys.length,this._keys.push(e),this._values.push(void 0)),this._cacheIndex},r;function i(e,A){return e}function n(e,A){return A}function o(e,A){return[e,A]}}(),h="function"==typeof Set&&"function"==typeof Set.prototype.entries?Set:function(){function e(){this._map=new c}return Object.defineProperty(e.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),e.prototype.has=function(e){return this._map.has(e)},e.prototype.add=function(e){return this._map.set(e,e),this},e.prototype.delete=function(e){return this._map.delete(e)},e.prototype.clear=function(){this._map.clear()},e.prototype.keys=function(){return this._map.keys()},e.prototype.values=function(){return this._map.keys()},e.prototype.entries=function(){return this._map.entries()},e.prototype["@@iterator"]=function(){return this.keys()},e.prototype[a]=function(){return this.keys()},e}(),g="function"==typeof WeakMap?WeakMap:function(){var e=d.create(),A=i();function t(){this._key=i()}return t.prototype.has=function(e){var A=n(e,!1);return void 0!==A&&d.has(A,this._key)},t.prototype.get=function(e){var A=n(e,!1);return void 0!==A?d.get(A,this._key):void 0},t.prototype.set=function(e,A){return n(e,!0)[this._key]=A,this},t.prototype.delete=function(e){var A=n(e,!1);return void 0!==A&&delete A[this._key]},t.prototype.clear=function(){this._key=i()},t;function i(){var A;do A="@@WeakMap@@"+function(){var e=function(){if("function"==typeof Uint8Array){var e=new Uint8Array(16);return"u">typeof crypto?crypto.getRandomValues(e):"u">typeof msCrypto?msCrypto.getRandomValues(e):a(e,16),e}return a(Array(16),16)}();e[6]=79&e[6]|64,e[8]=191&e[8]|128;for(var A="",t=0;t<16;++t){var r=e[t];(4===t||6===t||8===t)&&(A+="-"),r<16&&(A+="0"),A+=r.toString(16).toLowerCase()}return A}();while(d.has(e,A))return e[A]=!0,A}function n(e,t){if(!r.call(e,A)){if(!t)return;Object.defineProperty(e,A,{value:d.create()})}return e[A]}function a(e,A){for(var t=0;t<A;++t)e[t]=255*Math.random()|0;return e}}(),p=i?Symbol.for("@reflect-metadata:registry"):void 0,C=(!B(p)&&D(A.Reflect)&&Object.isExtensible(A.Reflect)&&(t=A.Reflect[p]),B(t)&&(t=function(){B(p)||void 0===A.Reflect||p in A.Reflect||"function"!=typeof A.Reflect.defineMetadata||(t=(e=A.Reflect).defineMetadata,r=e.hasOwnMetadata,i=e.getOwnMetadata,n=e.getOwnMetadataKeys,a=e.deleteMetadata,o=new g,s={isProviderFor:function(e,A){var t=o.get(e);return!!(!B(t)&&t.has(A))||!!n(e,A).length&&(B(t)&&(t=new h,o.set(e,t)),t.add(A),!0)},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:r,OrdinaryGetOwnMetadata:i,OrdinaryOwnMetadataKeys:n,OrdinaryDeleteMetadata:a});var e,t,r,i,n,a,o,s,l,d,u,C=new g,f={registerProvider:function(e){if(!Object.isExtensible(f))throw Error("Cannot add provider to a frozen registry.");switch(!0){case s===e:break;case B(l):l=e;break;case l===e:break;case B(d):d=e;break;case d===e:break;default:void 0===u&&(u=new h),u.add(e)}},getProvider:I,setProvider:function(e,A,t){if(!function(e){if(B(e))throw TypeError();return l===e||d===e||!B(u)&&u.has(e)}(t))throw Error("Metadata provider not registered.");var r=I(e,A);if(r!==t){if(!B(r))return!1;var i=C.get(e);B(i)&&(i=new c,C.set(e,i)),i.set(A,t)}return!0}};return f;function I(e,A){var t,r=C.get(e);return B(r)||(t=r.get(A)),B(t)&&(t=function(e,A){if(!B(l)){if(l.isProviderFor(e,A))return l;if(!B(d)){if(d.isProviderFor(e,A))return l;if(!B(u))for(var t=T(u);;){var r=M(t);if(!r)return;var i=r.value;if(i.isProviderFor(e,A))return N(t),i}}}if(!B(s)&&s.isProviderFor(e,A))return s}(e,A),B(t)||(B(r)&&(r=new c,C.set(e,r)),r.set(A,t))),t}}()),!B(p)&&D(A.Reflect)&&Object.isExtensible(A.Reflect)&&Object.defineProperty(A.Reflect,p,{enumerable:!1,configurable:!1,writable:!1,value:t}),t),f=function(e){var A=new g,t={isProviderFor:function(e,t){var r=A.get(e);return!B(r)&&r.has(t)},OrdinaryDefineOwnMetadata:function(e,A,t,i){r(t,i,!0).set(e,A)},OrdinaryHasOwnMetadata:function(e,A,t){var i=r(A,t,!1);return!B(i)&&!!i.has(e)},OrdinaryGetOwnMetadata:function(e,A,t){var i=r(A,t,!1);if(!B(i))return i.get(e)},OrdinaryOwnMetadataKeys:function(e,A){var t=[],i=r(e,A,!1);if(B(i))return t;for(var n=T(i.keys()),a=0;;){var o=M(n);if(!o)return t.length=a,t;var s=o.value;try{t[a]=s}catch(e){try{N(n)}finally{throw e}}a++}},OrdinaryDeleteMetadata:function(e,t,i){var n=r(t,i,!1);if(B(n)||!n.delete(e))return!1;if(0===n.size){var a=A.get(t);B(a)||(a.delete(i),0===a.size&&A.delete(a))}return!0}};return C.registerProvider(t),t;function r(r,i,n){var a=A.get(r),o=!1;if(B(a)){if(!n)return;a=new c,A.set(r,a),o=!0}var s=a.get(i);if(B(s)){if(!n)return;if(s=new c,a.set(i,s),!e.setProvider(r,i,t))throw a.delete(i),o&&A.delete(r),Error("Wrong provider for target.")}return s}}(C);function I(e,A,t){var r=H(A,t,!1);return!B(r)&&!!r.OrdinaryHasOwnMetadata(e,A,t)}function w(e,A,t){var r=H(A,t,!1);if(!B(r))return r.OrdinaryGetOwnMetadata(e,A,t)}function m(e,A,t,r){H(t,r,!0).OrdinaryDefineOwnMetadata(e,A,t,r)}function E(e,A){var t=H(e,A,!1);return t?t.OrdinaryOwnMetadataKeys(e,A):[]}function y(e){if(null===e)return 1;switch(typeof e){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return null===e?1:6;default:return 6}}function B(e){return void 0===e}function Q(e){return null===e}function D(e){return"object"==typeof e?null!==e:"function"==typeof e}e("decorate",function(e,A,t,r){if(B(t)){if(!S(e)||!R(A))throw TypeError();for(var i=e,n=A,a=i.length-1;a>=0;--a){var o=(0,i[a])(n);if(!B(o)&&!Q(o)){if(!R(o))throw TypeError();n=o}}return n}if(!S(e)||!D(A)||!D(r)&&!B(r)&&!Q(r))throw TypeError();return Q(r)&&(r=void 0),function(e,A,t,r){for(var i=e.length-1;i>=0;--i){var n=(0,e[i])(A,t,r);if(!B(n)&&!Q(n)){if(!D(n))throw TypeError();r=n}}return r}(e,A,t=b(t),r)}),e("metadata",function(e,A){return function(t,r){if(!D(t)||!B(r)&&!function(e){switch(y(e)){case 3:case 4:return!0;default:return!1}}(r))throw TypeError();m(e,A,t,r)}}),e("defineMetadata",function(e,A,t,r){if(!D(t))throw TypeError();return B(r)||(r=b(r)),m(e,A,t,r)}),e("hasMetadata",function(e,A,t){if(!D(A))throw TypeError();return B(t)||(t=b(t)),function e(A,t,r){if(I(A,t,r))return!0;var i=O(t);return!Q(i)&&e(A,i,r)}(e,A,t)}),e("hasOwnMetadata",function(e,A,t){if(!D(A))throw TypeError();return B(t)||(t=b(t)),I(e,A,t)}),e("getMetadata",function(e,A,t){if(!D(A))throw TypeError();return B(t)||(t=b(t)),function e(A,t,r){if(I(A,t,r))return w(A,t,r);var i=O(t);if(!Q(i))return e(A,i,r)}(e,A,t)}),e("getOwnMetadata",function(e,A,t){if(!D(A))throw TypeError();return B(t)||(t=b(t)),w(e,A,t)}),e("getMetadataKeys",function(e,A){if(!D(e))throw TypeError();return B(A)||(A=b(A)),function e(A,t){var r=E(A,t),i=O(A);if(null===i)return r;var n=e(i,t);if(n.length<=0)return r;if(r.length<=0)return n;for(var a=new h,o=[],s=0;s<r.length;s++){var l=r[s],d=a.has(l);d||(a.add(l),o.push(l))}for(var u=0;u<n.length;u++){var l=n[u],d=a.has(l);d||(a.add(l),o.push(l))}return o}(e,A)}),e("getOwnMetadataKeys",function(e,A){if(!D(e))throw TypeError();return B(A)||(A=b(A)),E(e,A)}),e("deleteMetadata",function(e,A,t){if(!D(A)||(B(t)||(t=b(t)),!D(A)))throw TypeError();B(t)||(t=b(t));var r=H(A,t,!1);return!B(r)&&r.OrdinaryDeleteMetadata(e,A,t)});function b(e){var A=function(e){switch(y(e)){case 0:case 1:case 2:case 3:case 4:case 5:return e}var A="string",t=G(e,n);if(void 0!==t){var r=t.call(e,A);if(D(r))throw TypeError();return r}return function(e,A){if("string"===A){var t=e.toString;if(k(t)){var r=t.call(e);if(!D(r))return r}var i=e.valueOf;if(k(i)){var r=i.call(e);if(!D(r))return r}}else{var i=e.valueOf;if(k(i)){var r=i.call(e);if(!D(r))return r}var n=e.toString;if(k(n)){var r=n.call(e);if(!D(r))return r}}throw TypeError()}(e,A)}(e);return"symbol"==typeof A?A:""+A}function S(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:"[object Array]"===Object.prototype.toString.call(e)}function k(e){return"function"==typeof e}function R(e){return"function"==typeof e}function v(e,A){return e===A||e!=e&&A!=A}function G(e,A){var t=e[A];if(null!=t){if(!k(t))throw TypeError();return t}}function T(e){var A=G(e,a);if(!k(A))throw TypeError();var t=A.call(e);if(!D(t))throw TypeError();return t}function M(e){var A=e.next();return!A.done&&A}function N(e){var A=e.return;A&&A.call(e)}function O(e){var A=Object.getPrototypeOf(e);if("function"!=typeof e||e===u||A!==u)return A;var t=e.prototype,r=t&&Object.getPrototypeOf(t);if(null==r||r===Object.prototype)return A;var i=r.constructor;return"function"!=typeof i||i===e?A:i}function H(e,A,t){var r=C.getProvider(e,A);if(!B(r))return r;if(t){if(C.setProvider(e,A,f))return f;throw Error("Illegal state.")}}function U(e){return e.__=void 0,delete e.__,e}})},709932,456622,e=>{"use strict";var A=e.i(898912),t=e.i(969068);e.i(592299);var r=e.i(747461),i=e.i(972425),n=e.i(863568);class a extends Error{status;errors;constructor(e,A,t){super(e),this.status=A,this.errors=t,this.name="AppleDeveloperRequestError"}}async function o(e=new n.CredentialService){let A=await e.getJson(i.CREDENTIALS.appStoreConnectSettings);if(!A)throw Error("App Store Connect API credentials are not configured");let t=(0,r.appStoreConnectConnectionSettings)(A),a=await e.getText(i.CREDENTIALS.appStoreConnectPrivateKey);if(!a)throw Error("App Store Connect API credentials are not configured");return{issuerId:t.issuerId,keyId:t.keyId,privateKey:a}}e.s(["AppleDeveloperClient",0,class{credentials;fetcher;constructor(e,A=fetch){this.credentials=e,this.fetcher=A}async token(){let e;try{e=await (0,A.importPKCS8)(this.credentials.privateKey,"ES256")}catch{throw Error("The App Store Connect key must be an ES256 PKCS#8 private key")}return new t.SignJWT({}).setProtectedHeader({alg:"ES256",kid:this.credentials.keyId,typ:"JWT"}).setIssuer(this.credentials.issuerId).setAudience("appstoreconnect-v1").setIssuedAt().setExpirationTime("15m").sign(e)}async request(e,A={}){let t,r=await this.token(),i=e.startsWith("http")?e:`https://api.appstoreconnect.apple.com${e}`;try{t=await this.fetcher(i,{...A,signal:A.signal??AbortSignal.timeout(2e4),headers:{accept:"application/json",authorization:`Bearer ${r}`,...A.body?{"content-type":"application/json"}:{},...A.headers}})}catch(e){if(e instanceof Error&&("TimeoutError"===e.name||"AbortError"===e.name))throw Error("Apple Developer API timed out; retry the operation");throw Error("Could not connect to the Apple Developer API")}if(204===t.status)return;let n=await t.json().catch(()=>({}));if(!t.ok){let e=n.errors?.map(e=>e.detail||e.title||e.code).filter(Boolean).join("; ");throw new a(401===t.status||403===t.status?"Apple rejected the API key or it lacks Certificates, Identifiers & Profiles permission":e||`Apple Developer API returned HTTP ${t.status}`,t.status,n.errors??[])}return n}async list(e){let A=[],t=e;for(;t;){let e=await this.request(t);A.push(...e.data),t=e.links?.next??null}return A}listProfiles(){return this.list("/v1/profiles?limit=200&include=bundleId,certificates,devices")}listCertificates(){return this.list("/v1/certificates?limit=200")}listBundleIds(){return this.list("/v1/bundleIds?limit=200")}listDevices(){return this.list("/v1/devices?limit=200")}async createProfile(e){let A={bundleId:{data:{type:"bundleIds",id:e.bundleIdId}},certificates:{data:e.certificateIds.map(e=>({type:"certificates",id:e}))}};return e.deviceIds?.length&&(A.devices={data:e.deviceIds.map(e=>({type:"devices",id:e}))}),this.request("/v1/profiles",{method:"POST",body:JSON.stringify({data:{type:"profiles",attributes:{name:e.name,profileType:e.profileType},relationships:A}})})}deleteProfile(e){return this.request(`/v1/profiles/${encodeURIComponent(e)}`,{method:"DELETE"})}revokeCertificate(e){return this.request(`/v1/certificates/${encodeURIComponent(e)}`,{method:"DELETE"})}},"AppleDeveloperRequestError",0,a,"storedAppleDeveloperCredentials",0,o],456622),e.s([],709932)},587483,663084,e=>{"use strict";e.i(76389);var A,t,r,i,n,a,o,s,l,d,u,c,h,g,p,C,f,I,w,m,E,y,B,Q,D,b,S,k,R,v,G,T,M,N,O,H,U,_,x,L,P,q,K,J,F,j,z,Y,Z,V,W,$,X,ee,eA,et,er,ei,en,ea,eo,es,el,ed,eu,ec,eh,eg,ep,eC,ef,eI,ew,em,eE,ey,eB,eQ,eD,eb,eS,ek,eR,ev,eG,eT,eM,eN,eO,eH,eU,e_,ex,eL,eP,eq,eK,eJ,eF,ej,ez,eY,eZ=e.i(666680);class eV{static isArrayBuffer(e){return"[object ArrayBuffer]"===Object.prototype.toString.call(e)}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,A){if(e.constructor===A)return e;if(this.isArrayBuffer(e))return new A(e);if(this.isArrayBufferView(e))return new A(e.buffer,e.byteOffset,e.byteLength);throw TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(e,A){let t=eV.toUint8Array(e),r=eV.toUint8Array(A);if(t.length!==r.byteLength)return!1;for(let e=0;e<t.length;e++)if(t[e]!==r[e])return!1;return!0}static concat(...e){let A;A=!Array.isArray(e[0])||e[1]instanceof Function?Array.isArray(e[0])&&e[1]instanceof Function?e[0]:e[e.length-1]instanceof Function?e.slice(0,e.length-1):e:e[0];let t=0;for(let e of A)t+=e.byteLength;let r=new Uint8Array(t),i=0;for(let e of A){let A=this.toUint8Array(e);r.set(A,i),i+=A.length}return e[e.length-1]instanceof Function?this.toView(r,e[e.length-1]):r.buffer}}let eW="string",e$=/^[0-9a-f\s]+$/i,eX=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,e0=/^[a-zA-Z0-9-_]+$/;class e1{static fromString(e){let A=unescape(encodeURIComponent(e)),t=new Uint8Array(A.length);for(let e=0;e<A.length;e++)t[e]=A.charCodeAt(e);return t.buffer}static toString(e){let A=eV.toUint8Array(e),t="";for(let e=0;e<A.length;e++)t+=String.fromCharCode(A[e]);return decodeURIComponent(escape(t))}}class e8{static toString(e,A=!1){let t=eV.toArrayBuffer(e),r=new DataView(t),i="";for(let e=0;e<t.byteLength;e+=2)i+=String.fromCharCode(r.getUint16(e,A));return i}static fromString(e,A=!1){let t=new ArrayBuffer(2*e.length),r=new DataView(t);for(let t=0;t<e.length;t++)r.setUint16(2*t,e.charCodeAt(t),A);return t}}class e4{static isHex(e){return typeof e===eW&&e$.test(e)}static isBase64(e){return typeof e===eW&&eX.test(e)}static isBase64Url(e){return typeof e===eW&&e0.test(e)}static ToString(e,A="utf8"){let t=eV.toUint8Array(e);switch(A.toLowerCase()){case"utf8":return this.ToUtf8String(t);case"binary":return this.ToBinary(t);case"hex":return this.ToHex(t);case"base64":return this.ToBase64(t);case"base64url":return this.ToBase64Url(t);case"utf16le":return e8.toString(t,!0);case"utf16":case"utf16be":return e8.toString(t);default:throw Error(`Unknown type of encoding '${A}'`)}}static FromString(e,A="utf8"){if(!e)return new ArrayBuffer(0);switch(A.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return e8.fromString(e,!0);case"utf16":case"utf16be":return e8.fromString(e);default:throw Error(`Unknown type of encoding '${A}'`)}}static ToBase64(e){let A=eV.toUint8Array(e);return"u">typeof btoa?btoa(this.ToString(A,"binary")):Buffer.from(A).toString("base64")}static FromBase64(e){let A=this.formatString(e);if(!A)return new ArrayBuffer(0);if(!e4.isBase64(A))throw TypeError("Argument 'base64Text' is not Base64 encoded");return"u">typeof atob?this.FromBinary(atob(A)):new Uint8Array(Buffer.from(A,"base64")).buffer}static FromBase64Url(e){let A=this.formatString(e);if(!A)return new ArrayBuffer(0);if(!e4.isBase64Url(A))throw TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(A.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e,A=e4.DEFAULT_UTF8_ENCODING){switch(A){case"ascii":return this.FromBinary(e);case"utf8":return e1.fromString(e);case"utf16":case"utf16be":return e8.fromString(e);case"utf16le":case"usc2":return e8.fromString(e,!0);default:throw Error(`Unknown type of encoding '${A}'`)}}static ToUtf8String(e,A=e4.DEFAULT_UTF8_ENCODING){switch(A){case"ascii":return this.ToBinary(e);case"utf8":return e1.toString(e);case"utf16":case"utf16be":return e8.toString(e);case"utf16le":case"usc2":return e8.toString(e,!0);default:throw Error(`Unknown type of encoding '${A}'`)}}static FromBinary(e){let A=e.length,t=new Uint8Array(A);for(let r=0;r<A;r++)t[r]=e.charCodeAt(r);return t.buffer}static ToBinary(e){let A=eV.toUint8Array(e),t="";for(let e=0;e<A.length;e++)t+=String.fromCharCode(A[e]);return t}static ToHex(e){let A=eV.toUint8Array(e),t="",r=A.length;for(let e=0;e<r;e++){let r=A[e];r<16&&(t+="0"),t+=r.toString(16)}return t}static FromHex(e){let A=this.formatString(e);if(!A)return new ArrayBuffer(0);if(!e4.isHex(A))throw TypeError("Argument 'hexString' is not HEX encoded");A.length%2&&(A=`0${A}`);let t=new Uint8Array(A.length/2);for(let e=0;e<A.length;e+=2){let r=A.slice(e,e+2);t[e/2]=parseInt(r,16)}return t.buffer}static ToUtf16String(e,A=!1){return e8.toString(e,A)}static FromUtf16String(e,A=!1){return e8.fromString(e,A)}static Base64Padding(e){let A=4-e.length%4;if(A<4)for(let t=0;t<A;t++)e+="=";return e}static formatString(e){return(null==e?void 0:e.replace(/[\n\r\t ]/g,""))||""}}function e2(e,A,t){var r;return e instanceof Object==!1?t:null!=(r=e[A])?r:t}function e6(e,A=0,t=e.byteLength-A,r=!1){let i="";for(let n of new Uint8Array(e,A,t)){let e=n.toString(16).toUpperCase();1===e.length&&(i+="0"),i+=e,r&&(i+=" ")}return i.trim()}function e3(e,A){let t=0;if(1===e.length)return e[0];for(let r=e.length-1;r>=0;r--)t+=e[e.length-1-r]*Math.pow(2,A*r);return t}function e5(e,A,t=-1){let r=e,i=0,n=Math.pow(2,A);for(let a=1;a<8;a++){if(e<n){let e;if(t<0)e=new ArrayBuffer(a),i=a;else{if(t<a)return new ArrayBuffer(0);e=new ArrayBuffer(t),i=t}let n=new Uint8Array(e);for(let e=a-1;e>=0;e--){let t=Math.pow(2,e*A);n[i-e-1]=Math.floor(r/t),r-=n[i-e-1]*t}return e}n*=Math.pow(2,A)}return new ArrayBuffer(0)}function e9(...e){let A=0,t=0;for(let t of e)A+=t.byteLength;let r=new ArrayBuffer(A),i=new Uint8Array(r);for(let A of e)i.set(new Uint8Array(A),t),t+=A.byteLength;return r}function e7(...e){let A=0,t=0;for(let t of e)A+=t.length;let r=new Uint8Array(new ArrayBuffer(A));for(let A of e)r.set(A,t),t+=A.length;return r}function Ae(){let e=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){let A=255===e[0]&&128&e[1],t=0===e[0]&&(128&e[1])==0;(A||t)&&this.warnings.push("Needlessly long format")}let A=new Uint8Array(new ArrayBuffer(this.valueHex.byteLength));for(let e=0;e<this.valueHex.byteLength;e++)A[e]=0;A[0]=128&e[0];let t=e3(A,8),r=new Uint8Array(new ArrayBuffer(this.valueHex.byteLength));for(let A=0;A<this.valueHex.byteLength;A++)r[A]=e[A];return r[0]&=127,e3(r,8)-t}function AA(e,A){if(e.byteLength!==A.byteLength)return!1;let t=new Uint8Array(e),r=new Uint8Array(A);for(let e=0;e<t.length;e++)if(t[e]!==r[e])return!1;return!0}function At(e,A){let t=e.toString(10);if(A<t.length)return"";let r=A-t.length,i=Array.from({length:r});for(let e=0;e<r;e++)i[e]="0";return i.join("").concat(t)}e4.DEFAULT_UTF8_ENCODING="utf8";let Ar="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Ai="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=";function An(e,A=!1,t=!1,r=!1){let i=0,n=0,a=0,o="",s=A?Ai:Ar;if(r){let A=0;for(let t=0;t<e.length;t++)if(0!==e.charCodeAt(t)){A=t;break}e=e.slice(A)}for(;i<e.length;){let A=e.charCodeAt(i++);i>=e.length&&(n=1);let r=e.charCodeAt(i++);i>=e.length&&(a=1);let l=e.charCodeAt(i++),d=A>>2,u=(3&A)<<4|r>>4,c=(15&r)<<2|l>>6,h=63&l;1===n?c=h=64:1===a&&(h=64),t?64===c?o+=`${s.charAt(d)}${s.charAt(u)}`:64===h?o+=`${s.charAt(d)}${s.charAt(u)}${s.charAt(c)}`:o+=`${s.charAt(d)}${s.charAt(u)}${s.charAt(c)}${s.charAt(h)}`:o+=`${s.charAt(d)}${s.charAt(u)}${s.charAt(c)}${s.charAt(h)}`}return o}function Aa(e,A=!1,t=!1){let r=A?Ai:Ar;function i(e){for(let A=0;A<64;A++)if(r.charAt(A)===e)return A;return 64}function n(e){return 64===e?0:e}let a=0,o="";for(;a<e.length;){let A=i(e.charAt(a++)),t=a>=e.length?0:i(e.charAt(a++)),r=a>=e.length?0:i(e.charAt(a++)),s=a>=e.length?0:i(e.charAt(a++)),l=n(A)<<2|n(t)>>4,d=(15&n(t))<<4|n(r)>>2,u=(3&n(r))<<6|n(s);o+=String.fromCharCode(l),64!==r&&(o+=String.fromCharCode(d)),64!==s&&(o+=String.fromCharCode(u))}if(t){let e=o.length,A=-1;for(let t=e-1;t>=0;t--)if(0!==o.charCodeAt(t)){A=t;break}o=-1!==A?o.slice(0,A+1):""}return o}function Ao(e){let A="";for(let t of new Uint8Array(e))A+=String.fromCharCode(t);return A}function As(e){let A=e.length,t=new ArrayBuffer(A),r=new Uint8Array(t);for(let t=0;t<A;t++)r[t]=e.charCodeAt(t);return t}let Al=Math.log(2);function Ad(e,A){for(let t of A)delete e[t]}function Au(){if("u"<typeof BigInt)throw Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Ac(e){let A=0,t=0;for(let t=0;t<e.length;t++)A+=e[t].byteLength;let r=new Uint8Array(A);for(let A=0;A<e.length;A++){let i=e[A];r.set(new Uint8Array(i),t),t+=i.byteLength}return r.buffer}function Ah(e,A,t,r){return A instanceof Uint8Array?A.byteLength?t<0?(e.error="Wrong parameter: inputOffset less than zero",!1):r<0?(e.error="Wrong parameter: inputLength less than zero",!1):!(A.byteLength-t-r<0)||(e.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):(e.error="Wrong parameter: inputBuffer has zero length",!1):(e.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}class Ag{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Ac(this.items)}}let Ap=[new Uint8Array([1])],AC="0123456789",Af="name",AI="valueHexView",Aw=new ArrayBuffer(0),Am=new Uint8Array(0),AE="EndOfContent",Ay="OCTET STRING",AB="BIT STRING";function AQ(e){var A;return(A=class extends e{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(e){this.valueHexView=new Uint8Array(e)}constructor(...e){var A;super(...e);const t=e[0]||{};this.isHexOnly=null!=(A=t.isHexOnly)&&A,this.valueHexView=t.valueHex?eV.toUint8Array(t.valueHex):Am}fromBER(e,A,t,r){let i=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!Ah(this,i,A,t))return -1;let n=A+t;return(this.valueHexView=i.subarray(A,n),this.valueHexView.length)?(this.blockLength=t,n):(this.warnings.push("Zero buffer length"),A)}toBER(e=!1){return this.isHexOnly?e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",Aw)}toJSON(){return{...super.toJSON(),isHexOnly:this.isHexOnly,valueHex:e4.ToHex(this.valueHexView)}}}).NAME="hexBlock",A}class AD{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor({blockLength:e=0,error:A="",warnings:t=[],valueBeforeDecode:r=Am}={}){this.blockLength=e,this.error=A,this.warnings=t,this.valueBeforeDecodeView=eV.toUint8Array(r)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:e4.ToHex(this.valueBeforeDecodeView)}}}AD.NAME="baseBlock";class Ab extends AD{fromBER(e,A,t,r){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,A){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}}Ab.NAME="valueBlock";class AS extends AQ(AD){constructor({idBlock:e={}}={}){var A,t,r,i;super(),e?(this.isHexOnly=null!=(A=e.isHexOnly)&&A,this.valueHexView=e.valueHex?eV.toUint8Array(e.valueHex):Am,this.tagClass=null!=(t=e.tagClass)?t:-1,this.tagNumber=null!=(r=e.tagNumber)?r:-1,this.isConstructed=null!=(i=e.isConstructed)&&i):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(e=!1){let A=0;switch(this.tagClass){case 1:A|=0;break;case 2:A|=64;break;case 3:A|=128;break;case 4:A|=192;break;default:return this.error="Unknown tag class",Aw}if(this.isConstructed&&(A|=32),this.tagNumber<31&&!this.isHexOnly){let t=new Uint8Array(1);if(!e){let e=this.tagNumber;e&=31,A|=e,t[0]=A}return t.buffer}if(!this.isHexOnly){let t=e5(this.tagNumber,7),r=new Uint8Array(t),i=t.byteLength,n=new Uint8Array(i+1);if(n[0]=31|A,!e){for(let e=0;e<i-1;e++)n[e+1]=128|r[e];n[i]=r[i-1]}return n.buffer}let t=new Uint8Array(this.valueHexView.byteLength+1);if(t[0]=31|A,!e){let e=this.valueHexView;for(let A=0;A<e.length-1;A++)t[A+1]=128|e[A];t[this.valueHexView.byteLength]=e[e.length-1]}return t.buffer}fromBER(e,A,t){let r=eV.toUint8Array(e);if(!Ah(this,r,A,t))return -1;let i=r.subarray(A,A+t);if(0===i.length)return this.error="Zero buffer length",-1;switch(192&i[0]){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=(32&i[0])==32,this.isHexOnly=!1;let n=31&i[0];if(31!==n)this.tagNumber=n,this.blockLength=1;else{let e=0;for(;;){let A=e+1;if(A>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(e++,(128&i[A])==0)break}this.blockLength=e+1;let A=this.valueHexView=new Uint8Array(e);for(let t=0;t<e;t++)A[t]=127&i[t+1];this.blockLength<=9?this.tagNumber=e3(A,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(1===this.tagClass&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return A+this.blockLength}toJSON(){return{...super.toJSON(),tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed}}}AS.NAME="identificationBlock";class Ak extends AD{constructor({lenBlock:e={}}={}){var A,t,r;super(),this.isIndefiniteForm=null!=(A=e.isIndefiniteForm)&&A,this.longFormUsed=null!=(t=e.longFormUsed)&&t,this.length=null!=(r=e.length)?r:0}fromBER(e,A,t){let r=eV.toUint8Array(e);if(!Ah(this,r,A,t))return -1;let i=r.subarray(A,A+t);if(0===i.length)return this.error="Zero buffer length",-1;if(255===i[0])return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=128===i[0],this.isIndefiniteForm)return this.blockLength=1,A+this.blockLength;if(this.longFormUsed=!!(128&i[0]),!1===this.longFormUsed)return this.length=i[0],this.blockLength=1,A+this.blockLength;let n=127&i[0];if(n>8)return this.error="Too big integer",-1;if(n+1>i.length)return this.error="End of input reached before message was fully decoded",-1;let a=A+1,o=r.subarray(a,a+n);return 0===o[n-1]&&this.warnings.push("Needlessly long encoded length"),this.length=e3(o,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=n+1,A+this.blockLength}toBER(e=!1){let A,t;if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return A=new ArrayBuffer(1),!1===e&&((t=new Uint8Array(A))[0]=128),A;if(this.longFormUsed){let r=e5(this.length,8);if(r.byteLength>127)return this.error="Too big length",Aw;if(A=new ArrayBuffer(r.byteLength+1),e)return A;let i=new Uint8Array(r);(t=new Uint8Array(A))[0]=128|r.byteLength;for(let e=0;e<r.byteLength;e++)t[e+1]=i[e];return A}return A=new ArrayBuffer(1),!1===e&&((t=new Uint8Array(A))[0]=this.length),A}toJSON(){return{...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length}}}Ak.NAME="lengthBlock";let AR={};class Av extends AD{constructor({name:e="",optional:A=!1,primitiveSchema:t,...r}={},i){super(r),this.name=e,this.optional=A,t&&(this.primitiveSchema=t),this.idBlock=new AS(r),this.lenBlock=new Ak(r),this.valueBlock=i?new i(r):new Ab(r)}fromBER(e,A,t,r){let i=this.valueBlock.fromBER(e,A,this.lenBlock.isIndefiniteForm?t:this.lenBlock.length,r);return -1===i?this.error=this.valueBlock.error:(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength)),i}toBER(e,A){let t=A||new Ag;A||function e(A){var t;if(A instanceof AR.Constructed)for(let t of A.valueBlock.value)e(t)&&(A.lenBlock.isIndefiniteForm=!0);return!!(null==(t=A.lenBlock)?void 0:t.isIndefiniteForm)}(this);let r=this.idBlock.toBER(e);if(t.write(r),this.lenBlock.isIndefiniteForm)t.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,t),t.write(new ArrayBuffer(2));else{let A=this.valueBlock.toBER(e);this.lenBlock.length=A.byteLength;let r=this.lenBlock.toBER(e);t.write(r),t.write(A)}return A?Aw:t.final()}toJSON(){let e={...super.toJSON(),idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional};return this.primitiveSchema&&(e.primitiveSchema=this.primitiveSchema.toJSON()),e}toString(e="ascii"){return"ascii"===e?this.onAsciiEncoding():e4.ToHex(this.toBER())}onAsciiEncoding(){let e=this.constructor.NAME,A=e4.ToHex(this.valueBlock.valueBeforeDecodeView);return`${e} : ${A}`}isEqual(e){return this===e||e instanceof this.constructor&&AA(this.toBER(),e.toBER())}}Av.NAME="BaseBlock";class AG extends Av{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor({value:e="",...A}={},t){super(A,t),e&&this.fromString(e)}fromBER(e,A,t){let r=this.valueBlock.fromBER(e,A,this.lenBlock.isIndefiniteForm?t:this.lenBlock.length);return -1===r?this.error=this.valueBlock.error:(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength)),r}onAsciiEncoding(){return`${this.constructor.NAME} : '${this.valueBlock.value}'`}}AG.NAME="BaseStringBlock";class AT extends AQ(Ab){constructor({isHexOnly:e=!0,...A}={}){super(A),this.isHexOnly=e}}AT.NAME="PrimitiveValueBlock";class AM extends Av{constructor(e={}){super(e,AT),this.idBlock.isConstructed=!1}}function AN(e={}){var A,t,r;return{depth:0,maxDepth:null!=(A=e.maxDepth)?A:100,nodesCount:0,maxNodes:null!=(t=e.maxNodes)?t:1e4,maxContentLength:null!=(r=e.maxContentLength)?r:0x1000000}}function AO(e,A,t,r){let i=r.depth+1;if(i>r.maxDepth){let e;return(e=new Av({},Ab)).error="Maximum ASN.1 nesting depth exceeded",{offset:-1,result:e}}r.depth=i;try{return AH(e,A,t,r)}finally{r.depth-=1}}function AH(e,A=0,t=e.length,r=AN()){let i=A,n=new Av({},Ab),a=new AD;if(!Ah(a,e,A,t))return n.error=a.error,{offset:-1,result:n};if(!e.subarray(A,A+t).length)return n.error="Zero buffer length",{offset:-1,result:n};let o=function(e){if(e.nodesCount+=1,e.nodesCount>e.maxNodes)return"Maximum ASN.1 node count exceeded"}(r);if(o)return n.error=o,{offset:-1,result:n};let s=n.idBlock.fromBER(e,A,t);if(n.idBlock.warnings.length&&n.warnings.concat(n.idBlock.warnings),-1===s)return n.error=n.idBlock.error,{offset:-1,result:n};if(A=s,t-=n.idBlock.blockLength,s=n.lenBlock.fromBER(e,A,t),n.lenBlock.warnings.length&&n.warnings.concat(n.lenBlock.warnings),-1===s)return n.error=n.lenBlock.error,{offset:-1,result:n};A=s,t-=n.lenBlock.blockLength;let l=n.lenBlock.isIndefiniteForm?t:n.lenBlock.length,d=function(e,A){if(e>A.maxContentLength)return"Maximum ASN.1 content length exceeded"}(l,r);if(d)return n.error=d,{offset:-1,result:n};if(!n.idBlock.isConstructed&&n.lenBlock.isIndefiniteForm)return n.error="Indefinite length form used for primitive encoding form",{offset:-1,result:n};let u=Av;if(1===n.idBlock.tagClass){if(n.idBlock.tagNumber>=37&&!1===n.idBlock.isHexOnly)return n.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:n};switch(n.idBlock.tagNumber){case 0:if(n.idBlock.isConstructed&&n.lenBlock.length>0)return n.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:n};u=AR.EndOfContent;break;case 1:u=AR.Boolean;break;case 2:u=AR.Integer;break;case 3:u=AR.BitString;break;case 4:u=AR.OctetString;break;case 5:u=AR.Null;break;case 6:u=AR.ObjectIdentifier;break;case 10:u=AR.Enumerated;break;case 12:u=AR.Utf8String;break;case 13:u=AR.RelativeObjectIdentifier;break;case 14:u=AR.TIME;break;case 15:return n.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:n};case 16:u=AR.Sequence;break;case 17:u=AR.Set;break;case 18:u=AR.NumericString;break;case 19:u=AR.PrintableString;break;case 20:u=AR.TeletexString;break;case 21:u=AR.VideotexString;break;case 22:u=AR.IA5String;break;case 23:u=AR.UTCTime;break;case 24:u=AR.GeneralizedTime;break;case 25:u=AR.GraphicString;break;case 26:u=AR.VisibleString;break;case 27:u=AR.GeneralString;break;case 28:u=AR.UniversalString;break;case 29:u=AR.CharacterString;break;case 30:u=AR.BmpString;break;case 31:u=AR.DATE;break;case 32:u=AR.TimeOfDay;break;case 33:u=AR.DateTime;break;case 34:u=AR.Duration;break;default:{let e=n.idBlock.isConstructed?new AR.Constructed:new AR.Primitive;e.idBlock=n.idBlock,e.lenBlock=n.lenBlock,e.warnings=n.warnings,n=e}}}else u=n.idBlock.isConstructed?AR.Constructed:AR.Primitive;return s=(n=function(e,A){if(e instanceof A)return e;let t=new A;return t.idBlock=e.idBlock,t.lenBlock=e.lenBlock,t.warnings=e.warnings,t.valueBeforeDecodeView=e.valueBeforeDecodeView,t}(n,u)).fromBER(e,A,l,r),n.valueBeforeDecodeView=e.subarray(i,i+n.blockLength),{offset:s,result:n}}function AU(e,A={}){if(!e.byteLength){let e=new Av({},Ab);return e.error="Input buffer has zero length",{offset:-1,result:e}}return AH(eV.toUint8Array(e).slice(),0,e.byteLength,AN(A))}AR.Primitive=AM,AM.NAME="PRIMITIVE";class A_ extends Ab{constructor({value:e=[],isIndefiniteForm:A=!1,...t}={}){super(t),this.value=e,this.isIndefiniteForm=A}fromBER(e,A,t,r){var i,n;let a=eV.toUint8Array(e),o=null!=r?r:AN();if(!Ah(this,a,A,t))return -1;if(this.valueBeforeDecodeView=a.subarray(A,A+t),0===this.valueBeforeDecodeView.length)return this.warnings.push("Zero buffer length"),A;let s=A;for(;i=this.isIndefiniteForm,n=t,(i?1:n)>0;){let e=AO(a,s,t,o);if(-1===e.offset)return this.error=e.result.error,this.warnings.concat(e.result.warnings),-1;if(s=e.offset,this.blockLength+=e.result.blockLength,t-=e.result.blockLength,this.value.push(e.result),this.isIndefiniteForm&&e.result.constructor.NAME===AE)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===AE?this.value.pop():this.warnings.push("No EndOfContent block encoded")),s}toBER(e,A){let t=A||new Ag;for(let A=0;A<this.value.length;A++)this.value[A].toBER(e,t);return A?Aw:t.final()}toJSON(){let e={...super.toJSON(),isIndefiniteForm:this.isIndefiniteForm,value:[]};for(let A of this.value)e.value.push(A.toJSON());return e}}A_.NAME="ConstructedValueBlock";class Ax extends Av{constructor(e={}){super(e,A_),this.idBlock.isConstructed=!0}fromBER(e,A,t,r){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;let i=this.valueBlock.fromBER(e,A,this.lenBlock.isIndefiniteForm?t:this.lenBlock.length,r);return -1===i?this.error=this.valueBlock.error:(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength)),i}onAsciiEncoding(){let e=[];for(let A of this.valueBlock.value)e.push(A.toString("ascii").split("\n").map(e=>` ${e}`).join("\n"));let A=3===this.idBlock.tagClass?`[${this.idBlock.tagNumber}]`:this.constructor.NAME;return e.length?`${A} :
997
997
  ${e.join("\n")}`:`${A} :`}}AR.Constructed=Ax,Ax.NAME="CONSTRUCTED";class AL extends Ab{fromBER(e,A,t){return A}toBER(e){return Aw}}AL.override="EndOfContentValueBlock";class AP extends Av{constructor(e={}){super(e,AL),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}AR.EndOfContent=AP,AP.NAME=AE;class Aq extends Av{constructor(e={}){super(e,Ab),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,A,t){return(this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=t,A+t>e.byteLength)?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):A+t}toBER(e,A){let t=new ArrayBuffer(2);if(!e){let e=new Uint8Array(t);e[0]=5,e[1]=0}return A&&A.write(t),t}onAsciiEncoding(){return`${this.constructor.NAME}`}}AR.Null=Aq,Aq.NAME="NULL";class AK extends AQ(Ab){get value(){for(let e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=255*!!e}constructor({value:e,...A}={}){super(A),A.valueHex?this.valueHexView=eV.toUint8Array(A.valueHex):this.valueHexView=new Uint8Array(1),e&&(this.value=e)}fromBER(e,A,t){let r=eV.toUint8Array(e);return Ah(this,r,A,t)?(this.valueHexView=r.subarray(A,A+t),t>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,Ae.call(this),this.blockLength=t,A+t):-1}toBER(){return this.valueHexView.slice()}toJSON(){return{...super.toJSON(),value:this.value}}}AK.NAME="BooleanValueBlock";class AJ extends Av{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(e={}){super(e,AK),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.getValue}`}}AR.Boolean=AJ,AJ.NAME="BOOLEAN";class AF extends AQ(A_){constructor({isConstructed:e=!1,...A}={}){super(A),this.isConstructed=e}fromBER(e,A,t,r){let i=0;if(this.isConstructed){if(this.isHexOnly=!1,-1===(i=A_.prototype.fromBER.call(this,e,A,t,r)))return i;for(let e=0;e<this.value.length;e++){let A=this.value[e].constructor.NAME;if(A===AE)if(!this.isIndefiniteForm)return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1;else break;if(A!==Ay)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,i=super.fromBER(e,A,t),this.blockLength=t;return i}toBER(e,A){return this.isConstructed?A_.prototype.toBER.call(this,e,A):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),isConstructed:this.isConstructed}}}AF.NAME="OctetStringValueBlock";class Aj extends Av{constructor({idBlock:e={},lenBlock:A={},...t}={}){var r;null!=t.isConstructed||(t.isConstructed=!!(null==(r=t.value)?void 0:r.length)),super({idBlock:{isConstructed:t.isConstructed,...e},lenBlock:{...A,isIndefiniteForm:!!t.isIndefiniteForm},...t},AF),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,A,t,r){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,0===t)return 0===this.idBlock.error.length&&(this.blockLength+=this.idBlock.blockLength),0===this.lenBlock.error.length&&(this.blockLength+=this.lenBlock.blockLength),A;if(!this.valueBlock.isConstructed){let i=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(A,A+t);try{if(i.byteLength){let e=null!=r?r:AN(),A=AO(i,0,i.byteLength,e);-1!==A.offset&&A.offset===t&&(this.valueBlock.value=[A.result])}}catch{}}return super.fromBER(e,A,t,r)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Ax.prototype.onAsciiEncoding.call(this);let e=this.constructor.NAME,A=e4.ToHex(this.valueBlock.valueHexView);return`${e} : ${A}`}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;let e=[];for(let A of this.valueBlock.value)A instanceof y&&e.push(A.valueBlock.valueHexView);return eV.concat(e)}}AR.OctetString=y=Aj,Aj.NAME=Ay;class Az extends AQ(A_){constructor({unusedBits:e=0,isConstructed:A=!1,...t}={}){super(t),this.unusedBits=e,this.isConstructed=A,this.blockLength=this.valueHexView.byteLength}fromBER(e,A,t,r){if(!t)return A;let i=-1;if(this.isConstructed){if(-1===(i=A_.prototype.fromBER.call(this,e,A,t,r)))return i;for(let e of this.value){let A=e.constructor.NAME;if(A===AE)if(!this.isIndefiniteForm)return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1;else break;if(A!==AB)return this.error="BIT STRING may consists of BIT STRINGs only",-1;let t=e.valueBlock;if(this.unusedBits>0&&t.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=t.unusedBits}return i}let n=eV.toUint8Array(e);if(!Ah(this,n,A,t))return -1;let a=n.subarray(A,A+t);if(this.unusedBits=a[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){let e=a.subarray(1);try{if(e.byteLength){let A=null!=r?r:AN(),i=AO(e,0,e.byteLength,A);-1!==i.offset&&i.offset===t-1&&(this.value=[i.result])}}catch{}}return this.valueHexView=a.subarray(1),this.blockLength=a.length,A+t}toBER(e,A){if(this.isConstructed)return A_.prototype.toBER.call(this,e,A);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength){let e=new Uint8Array(1);return e[0]=0,e.buffer}let t=new Uint8Array(this.valueHexView.length+1);return t[0]=this.unusedBits,t.set(this.valueHexView,1),t.buffer}toJSON(){return{...super.toJSON(),unusedBits:this.unusedBits,isConstructed:this.isConstructed}}}Az.NAME="BitStringValueBlock";class AY extends Av{constructor({idBlock:e={},lenBlock:A={},...t}={}){var r;null!=t.isConstructed||(t.isConstructed=!!(null==(r=t.value)?void 0:r.length)),super({idBlock:{isConstructed:t.isConstructed,...e},lenBlock:{...A,isIndefiniteForm:!!t.isIndefiniteForm},...t},Az),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,A,t,r){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,A,t,r)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Ax.prototype.onAsciiEncoding.call(this);{let e=[];for(let A of this.valueBlock.valueHexView)e.push(A.toString(2).padStart(8,"0"));let A=e.join(""),t=this.constructor.NAME,r=A.substring(0,A.length-this.valueBlock.unusedBits);return`${t} : ${r}`}}}function AZ(e){if(e>=Ap.length)for(let A=Ap.length;A<=e;A++){let e=new Uint8Array([0]),t=Ap[A-1].slice(0);for(let A=t.length-1;A>=0;A--){let r=new Uint8Array([(t[A]<<1)+e[0]]);e[0]=r[0]/10,t[A]=r[0]%10}e[0]>0&&(t=e7(e,t)),Ap.push(t)}return Ap[e]}AR.BitString=AY,AY.NAME=AB;class AV extends AQ(Ab){setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=Ae.call(this)))}constructor({value:e,...A}={}){super(A),this._valueDec=0,A.valueHex&&this.setValueHex(),void 0!==e&&(this.valueDec=e)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(function(e){let A=e<0?-1*e:e,t=128;for(let r=1;r<8;r++){if(A<=t){if(e<0){let e=e5(t-A,8,r),i=new Uint8Array(e);return i[0]|=128,e}let i=e5(A,8,r),n=new Uint8Array(i);if(128&n[0]){let e=i.slice(0),A=new Uint8Array(e);n=new Uint8Array(i=new ArrayBuffer(i.byteLength+1));for(let t=0;t<e.byteLength;t++)n[t+1]=A[t];n[0]=0}return i}t*=256}return new ArrayBuffer(0)}(e))}get valueDec(){return this._valueDec}fromDER(e,A,t,r=0){let i=this.fromBER(e,A,t);if(-1===i)return i;let n=this.valueHexView;return 0===n[0]&&(128&n[1])!=0?this.valueHexView=n.subarray(1):0!==r&&n.length<r&&(r-n.length>1&&(r=n.length+1),this.valueHexView=n.subarray(r-n.length)),i}toDER(e=!1){let A=this.valueHexView;switch(!0){case(128&A[0])!=0:{let e=new Uint8Array(this.valueHexView.length+1);e[0]=0,e.set(A,1),this.valueHexView=e}break;case 0===A[0]&&(128&A[1])==0:this.valueHexView=this.valueHexView.subarray(1)}return this.toBER(e)}fromBER(e,A,t){let r=super.fromBER(e,A,t);return -1===r||this.setValueHex(),r}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}toString(){let e,A=8*this.valueHexView.length-1,t=new Uint8Array(8*this.valueHexView.length/3),r=0,i=this.valueHexView,n="",a=!1;for(let a=i.byteLength-1;a>=0;a--){e=i[a];for(let i=0;i<8;i++)(1&e)==1&&(r===A?(t=function(e,A){let t,r=0,i=new Uint8Array(e),n=new Uint8Array(A),a=i.slice(0),o=a.length-1,s=n.slice(0),l=s.length-1,d=0;for(let e=l;e>=0;e--,d++)!0==(t=a[o-d]-s[l-d]-r)<0?(r=1,a[o-d]=t+10):(r=0,a[o-d]=t);if(r>0)for(let e=o-l+1;e>=0;e--,d++)if((t=a[o-d]-r)<0)r=1,a[o-d]=t+10;else{r=0,a[o-d]=t;break}return a.slice()}(AZ(r),t),n="-"):t=function(e,A){let t=new Uint8Array([0]),r=new Uint8Array(e),i=new Uint8Array(A),n=r.slice(0),a=n.length-1,o=i.slice(0),s=o.length-1,l=0,d=s<a?a:s,u=0;for(let e=d;e>=0;e--,u++)l=!0==u<o.length?n[a-u]+o[s-u]+t[0]:n[a-u]+t[0],t[0]=l/10,!0==u>=n.length?n=e7(new Uint8Array([l%10]),n):n[a-u]=l%10;return t[0]>0&&(n=e7(t,n)),n}(t,AZ(r))),r++,e>>=1}for(let e=0;e<t.length;e++)t[e]&&(a=!0),a&&(n+=AC.charAt(t[e]));return!1===a&&(n+=AC.charAt(0)),n}}AV.NAME="IntegerValueBlock",Object.defineProperty(AV.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});class AW extends Av{constructor(e={}){super(e,AV),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return Au(),BigInt(this.valueBlock.toString())}static fromBigInt(e){Au();let A=BigInt(e),t=new Ag,r=A.toString(16).replace(/^-/,""),i=new Uint8Array(e4.FromHex(r));if(A<0){let e=new Uint8Array(i.length+(128&i[0]?1:0));e[0]|=128;let r=BigInt(`0x${e4.ToHex(e)}`)+A,n=eV.toUint8Array(e4.FromHex(r.toString(16)));n[0]|=128,t.write(n)}else 128&i[0]&&t.write(new Uint8Array([0])),t.write(i);return new B({valueHex:t.final()})}convertToDER(){let e=new B({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new B({valueHex:0===this.valueBlock.valueHexView[0]?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()}`}}AR.Integer=B=AW,AW.NAME="INTEGER";class A$ extends AW{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}AR.Enumerated=A$,A$.NAME="ENUMERATED";class AX extends AQ(Ab){constructor({valueDec:e=-1,isFirstSid:A=!1,...t}={}){super(t),this.valueDec=e,this.isFirstSid=A}fromBER(e,A,t){if(!t)return A;let r=eV.toUint8Array(e);if(!Ah(this,r,A,t))return -1;let i=r.subarray(A,A+t);this.valueHexView=new Uint8Array(t);for(let e=0;e<t&&(this.valueHexView[e]=127&i[e],this.blockLength++,(128&i[e])!=0);e++);let n=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)n[e]=this.valueHexView[e];return(this.valueHexView=n,(128&i[this.blockLength-1])!=0)?(this.error="End of input reached before message was fully decoded",-1):(0===this.valueHexView[0]&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=e3(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),A+this.blockLength)}set valueBigInt(e){Au();let A=BigInt(e).toString(2);for(;A.length%7;)A="0"+A;let t=new Uint8Array(A.length/7);for(let e=0;e<t.length;e++)t[e]=parseInt(A.slice(7*e,7*e+7),2)+128*(e+1<t.length);this.fromBER(t.buffer,0,t.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let A=this.valueHexView,t=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength-1;e++)t[e]=128|A[e];return t[this.blockLength-1]=A[this.blockLength-1],t.buffer}let A=e5(this.valueDec,7);if(0===A.byteLength)return this.error="Error during encoding SID value",Aw;let t=new Uint8Array(A.byteLength);if(!e){let e=new Uint8Array(A),r=A.byteLength-1;for(let A=0;A<r;A++)t[A]=128|e[A];t[r]=e[r]}return t}toString(){let e="";if(this.isHexOnly)e=e4.ToHex(this.valueHexView);else if(this.isFirstSid){let A=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",A-=40):(e="2.",A-=80),e+=A.toString()}else e=this.valueDec.toString();return e}toJSON(){return{...super.toJSON(),valueDec:this.valueDec,isFirstSid:this.isFirstSid}}}AX.NAME="sidBlock";class A0 extends Ab{constructor({value:e="",...A}={}){super(A),this.value=[],e&&this.fromString(e)}fromBER(e,A,t){let r=A;for(;t>0;){let A=new AX;if(-1===(r=A.fromBER(e,r,t))){this.blockLength=0,this.error=A.error;break}0===this.value.length&&(A.isFirstSid=!0),this.blockLength+=A.blockLength,t-=A.blockLength,this.value.push(A)}return r}toBER(e){let A=[];for(let t=0;t<this.value.length;t++){let r=this.value[t].toBER(e);if(0===r.byteLength)return this.error=this.value[t].error,Aw;A.push(r)}return Ac(A)}fromString(e){this.value=[];let A=0,t=0,r="",i=!1;do if(r=-1===(t=e.indexOf(".",A))?e.substring(A):e.substring(A,t),A=t+1,i){let e=this.value[0],A=0;switch(e.valueDec){case 0:break;case 1:A=40;break;case 2:A=80;break;default:this.value=[];return}let t=parseInt(r,10);if(isNaN(t))return;e.valueDec=t+A,i=!1}else{let e=new AX;if(r>Number.MAX_SAFE_INTEGER)Au(),e.valueBigInt=BigInt(r);else if(e.valueDec=parseInt(r,10),isNaN(e.valueDec))return;this.value.length||(e.isFirstSid=!0,i=!0),this.value.push(e)}while(-1!==t)}toString(){let e="",A=!1;for(let t=0;t<this.value.length;t++){A=this.value[t].isHexOnly;let r=this.value[t].toString();0!==t&&(e=`${e}.`),A?(r=`{${r}}`,this.value[t].isFirstSid?e=`2.{${r} - 80}`:e+=r):e+=r}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let A=0;A<this.value.length;A++)e.sidArray.push(this.value[A].toJSON());return e}}A0.NAME="ObjectIdentifierValueBlock";class A1 extends Av{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,A0),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}AR.ObjectIdentifier=A1,A1.NAME="OBJECT IDENTIFIER";class A8 extends AQ(AD){constructor({valueDec:e=0,...A}={}){super(A),this.valueDec=e}fromBER(e,A,t){if(0===t)return A;let r=eV.toUint8Array(e);if(!Ah(this,r,A,t))return -1;let i=r.subarray(A,A+t);this.valueHexView=new Uint8Array(t);for(let e=0;e<t&&(this.valueHexView[e]=127&i[e],this.blockLength++,(128&i[e])!=0);e++);let n=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength;e++)n[e]=this.valueHexView[e];return(this.valueHexView=n,(128&i[this.blockLength-1])!=0)?(this.error="End of input reached before message was fully decoded",-1):(0===this.valueHexView[0]&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=e3(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),A+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);let A=this.valueHexView,t=new Uint8Array(this.blockLength);for(let e=0;e<this.blockLength-1;e++)t[e]=128|A[e];return t[this.blockLength-1]=A[this.blockLength-1],t.buffer}let A=e5(this.valueDec,7);if(0===A.byteLength)return this.error="Error during encoding SID value",Aw;let t=new Uint8Array(A.byteLength);if(!e){let e=new Uint8Array(A),r=A.byteLength-1;for(let A=0;A<r;A++)t[A]=128|e[A];t[r]=e[r]}return t.buffer}toString(){return this.isHexOnly?e4.ToHex(this.valueHexView):this.valueDec.toString()}toJSON(){return{...super.toJSON(),valueDec:this.valueDec}}}A8.NAME="relativeSidBlock";class A4 extends Ab{constructor({value:e="",...A}={}){super(A),this.value=[],e&&this.fromString(e)}fromBER(e,A,t){let r=A;for(;t>0;){let A=new A8;if(-1===(r=A.fromBER(e,r,t))){this.blockLength=0,this.error=A.error;break}this.blockLength+=A.blockLength,t-=A.blockLength,this.value.push(A)}return r}toBER(e,A){let t=[];for(let A=0;A<this.value.length;A++){let r=this.value[A].toBER(e);if(0===r.byteLength)return this.error=this.value[A].error,Aw;t.push(r)}return Ac(t)}fromString(e){this.value=[];let A=0,t=0,r="";do{r=-1===(t=e.indexOf(".",A))?e.substring(A):e.substring(A,t),A=t+1;let i=new A8;if(i.valueDec=parseInt(r,10),isNaN(i.valueDec))break;this.value.push(i)}while(-1!==t)return!0}toString(){let e="",A=!1;for(let t=0;t<this.value.length;t++){A=this.value[t].isHexOnly;let r=this.value[t].toString();0!==t&&(e=`${e}.`),A?e+=r=`{${r}}`:e+=r}return e}toJSON(){let e={...super.toJSON(),value:this.toString(),sidArray:[]};for(let A=0;A<this.value.length;A++)e.sidArray.push(this.value[A].toJSON());return e}}A4.NAME="RelativeObjectIdentifierValueBlock";class A2 extends Av{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(e={}){super(e,A4),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.valueBlock.toString()||"empty"}`}toJSON(){return{...super.toJSON(),value:this.getValue()}}}AR.RelativeObjectIdentifier=A2,A2.NAME="RelativeObjectIdentifier";class A6 extends Ax{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}AR.Sequence=A6,A6.NAME="SEQUENCE";class A3 extends Ax{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}}AR.Set=A3,A3.NAME="SET";class A5 extends AQ(Ab){constructor({...e}={}){super(e),this.isHexOnly=!0,this.value=""}toJSON(){return{...super.toJSON(),value:this.value}}}A5.NAME="StringValueBlock";class A9 extends A5{}A9.NAME="SimpleStringValueBlock";class A7 extends AG{constructor({...e}={}){super(e,A9)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,eV.toUint8Array(e))}fromString(e){let A=e.length,t=this.valueBlock.valueHexView=new Uint8Array(A);for(let r=0;r<A;r++)t[r]=e.charCodeAt(r);this.valueBlock.value=e}}A7.NAME="SIMPLE STRING";class te extends A7{fromBuffer(e){this.valueBlock.valueHexView=eV.toUint8Array(e);try{this.valueBlock.value=e4.ToUtf8String(e)}catch(A){this.warnings.push(`Error during "decodeURIComponent": ${A}, using raw string`),this.valueBlock.value=e4.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(e4.FromUtf8String(e)),this.valueBlock.value=e}}te.NAME="Utf8StringValueBlock";class tA extends te{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}AR.Utf8String=tA,tA.NAME="UTF8String";class tt extends A7{fromBuffer(e){this.valueBlock.value=e4.ToUtf16String(e),this.valueBlock.valueHexView=eV.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(e4.FromUtf16String(e))}}tt.NAME="BmpStringValueBlock";class tr extends tt{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}AR.BmpString=tr,tr.NAME="BMPString";class ti extends A7{fromBuffer(e){let A=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),t=new Uint8Array(A);for(let e=0;e<t.length;e+=4)t[e]=t[e+3],t[e+1]=t[e+2],t[e+2]=0,t[e+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(A))}fromString(e){let A=e.length,t=this.valueBlock.valueHexView=new Uint8Array(4*A);for(let r=0;r<A;r++){let A=new Uint8Array(e5(e.charCodeAt(r),8));if(A.length>4)continue;let i=4-A.length;for(let e=A.length-1;e>=0;e--)t[4*r+e+i]=A[e]}this.valueBlock.value=e}}ti.NAME="UniversalStringValueBlock";class tn extends ti{constructor({...e}={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}AR.UniversalString=tn,tn.NAME="UniversalString";class ta extends A7{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}AR.NumericString=ta,ta.NAME="NumericString";class to extends A7{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}AR.PrintableString=to,to.NAME="PrintableString";class ts extends A7{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}AR.TeletexString=ts,ts.NAME="TeletexString";class tl extends A7{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}AR.VideotexString=tl,tl.NAME="VideotexString";class td extends A7{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}AR.IA5String=td,td.NAME="IA5String";class tu extends A7{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}AR.GraphicString=tu,tu.NAME="GraphicString";class tc extends A7{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}AR.VisibleString=tc,tc.NAME="VisibleString";class th extends A7{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}AR.GeneralString=th,th.NAME="GeneralString";class tg extends A7{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}AR.CharacterString=tg,tg.NAME="CharacterString";class tp extends tc{constructor({value:e,valueDate:A,...t}={}){if(super(t),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,e){this.fromString(e),this.valueBlock.valueHexView=new Uint8Array(e.length);for(let A=0;A<e.length;A++)this.valueBlock.valueHexView[A]=e.charCodeAt(A)}A&&(this.fromDate(A),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,eV.toUint8Array(e)))}toBuffer(){let e=this.toString(),A=new ArrayBuffer(e.length),t=new Uint8Array(A);for(let A=0;A<e.length;A++)t[A]=e.charCodeAt(A);return A}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){let A=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/ig.exec(e);if(null===A){this.error="Wrong input string for conversion";return}let t=parseInt(A[1],10);t>=50?this.year=1900+t:this.year=2e3+t,this.month=parseInt(A[2],10),this.day=parseInt(A[3],10),this.hour=parseInt(A[4],10),this.minute=parseInt(A[5],10),this.second=parseInt(A[6],10)}toString(e="iso"){if("iso"===e){let e=Array(7);return e[0]=At(this.year<2e3?this.year-1900:this.year-2e3,2),e[1]=At(this.month,2),e[2]=At(this.day,2),e[3]=At(this.hour,2),e[4]=At(this.minute,2),e[5]=At(this.second,2),e[6]="Z",e.join("")}return super.toString(e)}onAsciiEncoding(){return`${this.constructor.NAME} : ${this.toDate().toISOString()}`}toJSON(){return{...super.toJSON(),year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second}}}AR.UTCTime=tp,tp.NAME="UTCTime";class tC extends tp{constructor(e={}){super(e),null!=this.millisecond||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond))}fromString(e){let A,t=!1,r="",i="",n=0,a=0,o=0;if("Z"===e[e.length-1])r=e.substring(0,e.length-1),t=!0;else{if(isNaN(new Number(e[e.length-1]).valueOf()))throw Error("Wrong input string for conversion");r=e}if(t){if(-1!==r.indexOf("+")||-1!==r.indexOf("-"))throw Error("Wrong input string for conversion")}else{let e=1,A=r.indexOf("+"),t="";if(-1===A&&(A=r.indexOf("-"),e=-1),-1!==A){if(t=r.substring(A+1),r=r.substring(0,A),2!==t.length&&4!==t.length)throw Error("Wrong input string for conversion");let i=parseInt(t.substring(0,2),10);if(isNaN(i.valueOf()))throw Error("Wrong input string for conversion");if(a=e*i,4===t.length){if(isNaN((i=parseInt(t.substring(2,4),10)).valueOf()))throw Error("Wrong input string for conversion");o=e*i}}}let s=r.indexOf(".");if(-1===s&&(s=r.indexOf(",")),-1!==s){let e=new Number(`0${r.substring(s)}`);if(isNaN(e.valueOf()))throw Error("Wrong input string for conversion");n=e.valueOf(),i=r.substring(0,s)}else i=r;switch(!0){case 8===i.length:if(A=/(\d{4})(\d{2})(\d{2})/ig,-1!==s)throw Error("Wrong input string for conversion");break;case 10===i.length:if(A=/(\d{4})(\d{2})(\d{2})(\d{2})/ig,-1!==s){let e=60*n;this.minute=Math.floor(e),e=60*(e-this.minute),this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case 12===i.length:if(A=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/ig,-1!==s){let e=60*n;this.second=Math.floor(e),e=1e3*(e-this.second),this.millisecond=Math.floor(e)}break;case 14===i.length:if(A=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/ig,-1!==s){let e=1e3*n;this.millisecond=Math.floor(e)}break;default:throw Error("Wrong input string for conversion")}let l=A.exec(i);if(null===l)throw Error("Wrong input string for conversion");for(let e=1;e<l.length;e++)switch(e){case 1:this.year=parseInt(l[e],10);break;case 2:this.month=parseInt(l[e],10);break;case 3:this.day=parseInt(l[e],10);break;case 4:this.hour=parseInt(l[e],10)+a;break;case 5:this.minute=parseInt(l[e],10)+o;break;case 6:this.second=parseInt(l[e],10);break;default:throw Error("Wrong input string for conversion")}if(!1===t){let e=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=e.getUTCFullYear(),this.month=e.getUTCMonth(),this.day=e.getUTCDay(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds(),this.millisecond=e.getUTCMilliseconds()}}toString(e="iso"){if("iso"===e){let e=[];return e.push(At(this.year,4)),e.push(At(this.month,2)),e.push(At(this.day,2)),e.push(At(this.hour,2)),e.push(At(this.minute,2)),e.push(At(this.second,2)),0!==this.millisecond&&(e.push("."),e.push(At(this.millisecond,3))),e.push("Z"),e.join("")}return super.toString(e)}toJSON(){return{...super.toJSON(),millisecond:this.millisecond}}}AR.GeneralizedTime=tC,tC.NAME="GeneralizedTime";class tf extends tA{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}AR.DATE=tf,tf.NAME="DATE";class tI extends tA{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}AR.TimeOfDay=tI,tI.NAME="TimeOfDay";class tw extends tA{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}AR.DateTime=tw,tw.NAME="DateTime";class tm extends tA{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}AR.Duration=tm,tm.NAME="Duration";class tE extends tA{constructor(e={}){super(e),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}AR.TIME=tE,tE.NAME="TIME";class ty{constructor({name:e="",optional:A=!1}={}){this.name=e,this.optional=A}}class tB extends ty{constructor({value:e=[],...A}={}){super(A),this.value=e}}class tQ extends ty{constructor({value:e=new ty,local:A=!1,...t}={}){super(t),this.value=e,this.local=A}}class tD{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=eV.toUint8Array(e)}constructor({data:e=Am}={}){this.dataView=eV.toUint8Array(e)}fromBER(e,A,t){let r=A+t;return this.dataView=eV.toUint8Array(e).subarray(A,r),r}toBER(e){return this.dataView.slice().buffer}}function tb(e,A,t){if(t instanceof tB){for(let r of t.value)if(tb(e,A,r).verified)return{verified:!0,result:e};{let e={verified:!1,result:{error:"Wrong values for Choice type"}};return t.hasOwnProperty(Af)&&(e.name=t.name),e}}if(t instanceof ty)return t.hasOwnProperty(Af)&&(e[t.name]=A),{verified:!0,result:e};if(e instanceof Object==!1)return{verified:!1,result:{error:"Wrong root object"}};if(A instanceof Object==!1)return{verified:!1,result:{error:"Wrong ASN.1 data"}};if(t instanceof Object==!1||"idBlock"in t==!1||"fromBER"in t.idBlock==!1||"toBER"in t.idBlock==!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};let r=t.idBlock.toBER(!1);if(0===r.byteLength)return{verified:!1,result:{error:"Error encoding idBlock for ASN.1 schema"}};if(-1===t.idBlock.fromBER(r,0,r.byteLength))return{verified:!1,result:{error:"Error decoding idBlock for ASN.1 schema"}};if(!1===t.idBlock.hasOwnProperty("tagClass"))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(t.idBlock.tagClass!==A.idBlock.tagClass)return{verified:!1,result:e};if(!1===t.idBlock.hasOwnProperty("tagNumber"))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(t.idBlock.tagNumber!==A.idBlock.tagNumber)return{verified:!1,result:e};if(!1===t.idBlock.hasOwnProperty("isConstructed"))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(t.idBlock.isConstructed!==A.idBlock.isConstructed)return{verified:!1,result:e};if(!("isHexOnly"in t.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(t.idBlock.isHexOnly!==A.idBlock.isHexOnly)return{verified:!1,result:e};if(t.idBlock.isHexOnly){if(AI in t.idBlock==!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};let r=t.idBlock.valueHexView,i=A.idBlock.valueHexView;if(r.length!==i.length)return{verified:!1,result:e};for(let A=0;A<r.length;A++)if(r[A]!==i[1])return{verified:!1,result:e}}if(t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,""),t.name&&(e[t.name]=A)),t instanceof AR.Constructed){let r=0,i={verified:!1,result:{error:"Unknown error"}},n=t.valueBlock.value.length;if(n>0&&t.valueBlock.value[0]instanceof tQ&&(n=A.valueBlock.value.length),0===n)return{verified:!0,result:e};if(0===A.valueBlock.value.length&&0!==t.valueBlock.value.length){let A=!0;for(let e=0;e<t.valueBlock.value.length;e++)A=A&&(t.valueBlock.value[e].optional||!1);return A?{verified:!0,result:e}:(t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,""),t.name&&delete e[t.name]),e.error="Inconsistent object length",{verified:!1,result:e})}for(let a=0;a<n;a++)if(a-r>=A.valueBlock.value.length){if(!1===t.valueBlock.value[a].optional){let A={verified:!1,result:e};return e.error="Inconsistent length between ASN.1 data and schema",t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,""),t.name&&(delete e[t.name],A.name=t.name)),A}}else if(t.valueBlock.value[0]instanceof tQ){if(!1===(i=tb(e,A.valueBlock.value[a],t.valueBlock.value[0].value)).verified)if(!t.valueBlock.value[0].optional)return t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,""),t.name&&delete e[t.name]),i;else r++;if(Af in t.valueBlock.value[0]&&t.valueBlock.value[0].name.length>0){let r={};void 0===(r="local"in t.valueBlock.value[0]&&t.valueBlock.value[0].local?A:e)[t.valueBlock.value[0].name]&&(r[t.valueBlock.value[0].name]=[]),r[t.valueBlock.value[0].name].push(A.valueBlock.value[a])}}else if(!1===(i=tb(e,A.valueBlock.value[a-r],t.valueBlock.value[a])).verified)if(!t.valueBlock.value[a].optional)return t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,""),t.name&&delete e[t.name]),i;else r++;if(!1===i.verified){let A={verified:!1,result:e};return t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,""),t.name&&(delete e[t.name],A.name=t.name)),A}return{verified:!0,result:e}}if(t.primitiveSchema&&AI in A.valueBlock){let r=AH(A.valueBlock.valueHexView);if(-1===r.offset){let A={verified:!1,result:r.result};return t.name&&(t.name=t.name.replace(/^\s+|\s+$/g,""),t.name&&(delete e[t.name],A.name=t.name)),A}return tb(e,r.result,t.primitiveSchema)}return{verified:!0,result:e}}function tS(e){return Object.prototype.toString.call(e)}function tk(e){return"[object ArrayBuffer]"===tS(e)}function tR(e){return tk(e)||"u">typeof SharedArrayBuffer&&"[object SharedArrayBuffer]"===tS(e)}function tv(e){return tR(e)||!!ArrayBuffer.isView(e)||!!e&&"object"==typeof e&&"number"==typeof e.byteOffset&&"number"==typeof e.byteLength&&tR(e.buffer)}function tG(e){if(!tv(e))throw TypeError("Expected ArrayBuffer, SharedArrayBuffer, or ArrayBufferView")}function tT(e){return(tG(e),tR(e))?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function tM(e){if(tG(e),tk(e))return e;let A=new ArrayBuffer(e.byteLength);return new Uint8Array(A).set(tT(e)),A}e.s(["Any",0,ty,"BaseBlock",0,Av,"BaseStringBlock",0,AG,"BitString",0,AY,"BmpString",0,tr,"Boolean",0,AJ,"CharacterString",0,tg,"Choice",0,tB,"Constructed",0,Ax,"DATE",0,tf,"DEFAULT_MAX_CONTENT_LENGTH",0,0x1000000,"DEFAULT_MAX_DEPTH",0,100,"DEFAULT_MAX_NODES",0,1e4,"DateTime",0,tw,"Duration",0,tm,"EndOfContent",0,AP,"Enumerated",0,A$,"GeneralString",0,th,"GeneralizedTime",0,tC,"GraphicString",0,tu,"HexBlock",0,AQ,"IA5String",0,td,"Integer",0,AW,"Null",0,Aq,"NumericString",0,ta,"ObjectIdentifier",0,A1,"OctetString",0,Aj,"Primitive",0,AM,"PrintableString",0,to,"RawData",0,tD,"RelativeObjectIdentifier",0,A2,"Repeated",0,tQ,"Sequence",0,A6,"Set",0,A3,"TIME",0,tE,"TeletexString",0,ts,"TimeOfDay",0,tI,"UTCTime",0,tp,"UniversalString",0,tn,"Utf8String",0,tA,"ValueBlock",0,Ab,"VideotexString",0,tl,"ViewWriter",0,Ag,"VisibleString",0,tc,"compareSchema",0,tb,"fromBER",0,AU,"verifySchema",0,function(e,A){if(A instanceof Object==!1)return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};let t=AH(eV.toUint8Array(e));return -1===t.offset?{verified:!1,result:t.result}:tb(t.result,t.result,A)}],913230);let tN=/^[0-9a-f]$/i,tO=[" "," ","\n","\r",":","-","."];function tH(e){return e.replace(/[^0-9a-f]/gi,"")}function tU(e,A){if(!A)return e.join("");if(!Number.isInteger(A.size)||A.size<1)throw RangeError("Hex group size must be a positive integer");let t=[];for(let r=0;r<e.length;r+=A.size)t.push(e.slice(r,r+A.size).join(""));return t.join(A.separator)}function t_(e,A={}){return function(e,A){let t=A.allowPrefix??!0,r=[..."none"===A.separators?[]:!A.separators||"common"===A.separators?tO:A.separators].sort((e,A)=>A.length-e.length);for(let e of r)if(!e)throw TypeError("Hex separators must be non-empty strings");let i=e.trim();if(/^0x/i.test(i)){if(!t)throw TypeError("Hexadecimal text must not include a 0x prefix");i=i.slice(2)}let n="",a=!1;for(let e=0;e<i.length;){let t=i[e]??"";if(tN.test(t)){n+=t,a=!1,e+=1;continue}let o=function(e,A,t){for(let r of t)if(e.startsWith(r,A))return r}(i,e,r);if(!o)throw TypeError("Input is not valid hexadecimal text");if(A.strict&&(a||0===n.length))throw TypeError("Hexadecimal text contains misplaced separators");a=!0,e+=o.length}if(A.strict&&a&&n.length>0)throw TypeError("Hexadecimal text must not end with a separator");if(n.length%2!=0){if(!A.allowOddLength)throw TypeError("Hexadecimal text must contain an even number of characters");n=`0${n}`}return n.toLowerCase()}(e,A)}function tx(e,A={}){if("string"!=typeof e)return!1;try{return t_(e,A),!0}catch{return!1}}function tL(e,A={}){let t=tT(e),r=A.case??"lower",i=Array.from(t,e=>{let A=e.toString(16).padStart(2,"0");return"upper"===r?A.toUpperCase():A}),n="";if(A.line){let e=A.line.bytesPerLine;if(!Number.isInteger(e)||e<1)throw RangeError("Hex bytesPerLine must be a positive integer");let t=A.line.separator??"\n",r=[];for(let t=0;t<i.length;t+=e)r.push(tU(i.slice(t,t+e),A.group));n=r.join(t)}else n=tU(i,A.group);return`${A.prefix??""}${n}`}function tP(e,A={}){let t=t_(e,A),r=new Uint8Array(t.length/2);for(let e=0;e<t.length;e+=2)r[e/2]=Number.parseInt(t.slice(e,e+2),16);return r}function tq(e,A={}){let t=t_(e,A);return{bytes:tP(t),format:function(e){let A,t,r=e.trim(),i=/^0x/i.test(r)?"0x":"",n=i?r.slice(2):r,a=function(e){let A=/\r\n|\n/.exec(e);if(A)return"\r\n"===A[0]?"\r\n":"\n"}(n),o=n.split(/\r\n|\n/).filter(e=>e.length>0),s=function(e){let A=e.match(/[0-9A-Fa-f]+|[^0-9A-Fa-f]+/g)??[];if(A.length<3)return;let t=A.filter((e,A)=>A%2==0),r=A.filter((e,A)=>A%2==1),i=r[0];if(!i||r.some(e=>e!==i)||t.some(e=>0===e.length||e.length%2!=0))return;let n=t[0]?.length??0;if(!(!n||t.slice(0,-1).some(e=>e.length!==n))&&!((t[t.length-1]?.length??0)>n))return{size:n/2,separator:i}}(o[0]?.trim()??""),l={case:(A=/[A-F]/.test(r),t=/[a-f]/.test(r),A&&!t?"upper":"lower"),prefix:i};if(s&&(l.group=s),a&&o.length>1){let e=tH(o[0]??"").length/2;e>0&&o.slice(0,-1).every(A=>tH(A).length/2===e)&&(l.line={bytesPerLine:e,separator:a})}return l}(e),normalized:t}}function tK(e,A){return tL(e,A)}let tJ={compact:Object.freeze({}),upper:Object.freeze({case:"upper"}),colon:Object.freeze({group:{size:1,separator:":"}}),colonUpper:Object.freeze({case:"upper",group:{size:1,separator:":"}}),groupsOf4:Object.freeze({group:{size:4,separator:" "}}),prefixed:Object.freeze({prefix:"0x"})};function tF(e){let A=tT(e),t="";for(let e of A)t+=String.fromCharCode(e);return t}function tj(e){let A=new Uint8Array(e.length);for(let t=0;t<e.length;t++)A[t]=255&e.charCodeAt(t);return A}function tz(e){return"string"==typeof e}e.s(["decode",0,tP,"encode",0,tL,"format",0,tK,"formats",0,tJ,"hex",0,{encode:tL,decode:tP,format:tK,formats:tJ,is:tx,normalize:t_,parse:tq},"is",0,tx,"normalize",0,t_,"parse",0,tq],904257),e.s(["binary",0,{encode:tF,decode:tj,is:tz},"decode",0,tj,"encode",0,tF,"is",0,tz],954001);let tY=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;function tZ(){return globalThis.Buffer}function tV(e){return e.replace(/[\n\r\t ]/g,"")}function tW(e){let A=e.length%4;return A?e+"=".repeat(4-A):e}function t$(e){if("string"!=typeof e)return!1;let A=tV(e);return""===A||tY.test(A)}function tX(e,A){let t=tT(e),r=tZ();return r?r.from(t).toString("base64"):btoa(tF(t))}function t0(e,A){let t=tV(e);if(!t$(t))throw TypeError("Input is not valid Base64 text");let r=tZ();return r?new Uint8Array(r.from(t,"base64")):tj(atob(t))}let t1={encode:tX,decode:t0,is:t$,normalize:tV,pad:tW};e.s(["base64",0,t1,"decode",0,t0,"encode",0,tX,"is",0,t$,"normalize",0,tV,"pad",0,tW],702216);var t8=e.i(702216),t8=t8;let t4=/^[A-Za-z0-9_-]*$/;function t2(e){return e.replace(/[\n\r\t ]/g,"")}function t6(e){return"string"==typeof e&&t4.test(t2(e))}function t3(e,A){return t1.encode(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function t5(e,A){let t=t2(e);if(!t6(t))throw TypeError("Input is not valid Base64Url text");return t1.decode(t1.pad(t.replace(/-/g,"+").replace(/_/g,"/")))}e.s(["base64url",0,{encode:t3,decode:t5,is:t6,normalize:t2},"decode",0,t5,"encode",0,t3,"is",0,t6,"normalize",0,t2],57434);var t9=e.i(57434),t9=t9,t7=e.i(954001),t7=t7,re=e.i(904257),re=re;function rA(e){return new TextEncoder().encode(e)}function rt(e){return new TextDecoder("utf-8",{fatal:!1}).decode(tT(e))}e.s(["decode",0,rt,"encode",0,rA,"utf8",0,{encode:rA,decode:rt}],832708);var rr=e.i(832708),rr=rr;function ri(e,A={}){let t=new ArrayBuffer(2*e.length),r=new DataView(t);for(let t=0;t<e.length;t++)r.setUint16(2*t,e.charCodeAt(t),A.littleEndian??!1);return new Uint8Array(t)}function rn(e,A={}){let t=tM(e),r=new DataView(t),i="";for(let e=0;e<t.byteLength;e+=2)i+=String.fromCharCode(r.getUint16(e,A.littleEndian??!1));return i}e.s(["decode",0,rn,"encode",0,ri,"utf16",0,{encode:ri,decode:rn}],505292);var ra=e.i(505292),ra=ra;let ro=/^[A-Z0-9][A-Z0-9 ._-]*[A-Z0-9]$/i,rs=/-----BEGIN ([^-]+)-----([\s\S]*?)-----END \1-----/g;function rl(e){if(!ro.test(e))throw TypeError(`Invalid PEM label '${e}'`)}function rd(e,A={}){let t,r=[],i=A.label;for(rs.lastIndex=0;t=rs.exec(e);){var n;let e=t[1].trim();if(i&&e!==i)continue;rl(e);let A=function(e){let A=e.trim().replace(/\r\n/g,"\n").split("\n").map(e=>e.trim()).filter(Boolean),t={},r=0;for(;r<A.length;r++){let e=A[r],i=e.indexOf(":");if(i<=0)break;t[e.slice(0,i).trim()]=e.slice(i+1).trim()}return{headers:Object.keys(t).length?t:void 0,base64Lines:A.slice(r),base64Text:A.slice(r).join("")}}(t[2]);r.push({label:e,data:t1.decode(A.base64Text),headers:A.headers,lineLength:A.base64Lines[0]?.length??64,newline:(n=t[0],/\r\n/.test(n)?"\r\n":"\n")})}if(A.strict&&0===r.length)throw TypeError(i?`No PEM block with label '${i}' was found`:"No PEM blocks were found");return r}function ru(e,A,t={}){rl(e);let r=t.lineLength??64;if(!Number.isInteger(r)||r<1)throw RangeError("PEM lineLength must be a positive integer");let i=t.newline??"\n",n=[`-----BEGIN ${e}-----`];if(t.headers){for(let[e,A]of Object.entries(t.headers))n.push(`${e}: ${A}`);n.push("")}return n.push(...function(e,A){let t=[];for(let r=0;r<e.length;r+=A)t.push(e.slice(r,r+A));return t}(t1.encode(A),r)),n.push(`-----END ${e}-----`),`${n.join(i)}${i}`}function rc(e){return e.trim().toLowerCase()}function rh(e,A,t){for(let A of[t.name,...t.aliases??[]])e.delete(rc(A));A.delete(rc(t.name))}function rg(e,A,t){let r=e[t];if("function"!=typeof r)throw Error(`Converter '${A}' does not support ${t}()`);return r}(function(e=[]){let A=new Map,t=new Set,r={register(e,r={}){if(!e.name||!rc(e.name))throw TypeError("Converter name is required");let i=[...new Set([e.name,...e.aliases??[]].map(rc))],n=new Set;for(let e of i){let t=A.get(e);if(t){if(!r.override)throw Error(`Converter '${e}' is already registered`);n.add(t)}}for(let e of n)rh(A,t,e);for(let t of i)A.set(t,e);return t.add(rc(e.name)),this},unregister(e){let r=A.get(rc(e));return!!r&&(rh(A,t,r),!0)},has:e=>A.has(rc(e)),get(e){let t=A.get(rc(e));if(!t)throw Error(`Converter '${e}' is not registered`);return t},list(){return[...t].map(e=>this.get(e))},encode(e,A,t){return this.get(e).encode(A,t)},decode(e,A,t){return this.get(e).decode(A,t)},tryDecode(e,A,t){try{return{ok:!0,bytes:this.decode(e,A,t)}}catch(e){return{ok:!1,error:e instanceof Error?e:Error(String(e))}}},normalize(e,A,t){let r=this.get(e);return rg(r,e,"normalize").call(r,A,t)},parse(e,A,t){let r=this.get(e);return rg(r,e,"parse").call(r,A,t)},format(e,A,t){let r=this.get(e);return rg(r,e,"format").call(r,A,t)},transcode(e,A){let t=this.decode(A.from,e,A.fromOptions);return this.encode(A.to,t,A.toOptions)},detect(e,A={}){let t=A.formats?.length?A.formats.map(e=>String(e)):this.list().map(e=>e.name).filter(e=>!["binary","utf8","utf16be","utf16le"].includes(rc(e))),r=new Map;for(let A of t){let t=this.get(A),i=function(e,A,t){let r=rc(t.name||e),i=A.trim();if(!i)return 0;let n=!1;t.is&&(n=t.is(A));let a=!1;try{t.decode(A),a=!0}catch{a=!1}if(!n&&!a)return 0;switch(r){case"pem":return+!!/-----BEGIN [^-]+-----/.test(A);case"hex":{let e=i.replace(/^0x/i,"").replace(/[\s:.-]/g,"");if(!e||/[^0-9a-f]/i.test(e)||e.length%2!=0)return 0;if(/^0x/i.test(i)||/[:\s.-]/.test(i))return .95;if(/[a-f]/.test(i)||/[A-F]/.test(i))return .8;return .45}case"base64url":if(/[-_]/.test(i))return .95;if(/=/.test(i))return .1;return .6;case"base64":if(/[+/=]/.test(i))return .9;return .55;case"binary":case"utf8":case"utf16be":case"utf16le":return 0;default:return n&&a?.75:.5}}(A,e,t);if(i<=0)continue;let n=t.name,a=r.get(n);(!a||i>a.confidence)&&r.set(n,{format:n,confidence:i})}return[...r.values()].sort((e,A)=>A.confidence-e.confidence)}};for(let A of e)r.register(A);})([{name:"binary",aliases:["latin1"],encode:t7.encode,decode:t7.decode,is:t7.is},{name:"hex",encode:re.encode,decode:re.decode,format:re.format,is:re.is,normalize:re.normalize,parse:re.parse},{name:"base64",aliases:["b64"],encode:t8.encode,decode:t8.decode,is:t8.is,normalize:t8.normalize},{name:"base64url",aliases:["base64-url","b64url"],encode:t9.encode,decode:t9.decode,is:t9.is,normalize:t9.normalize},{name:"utf8",aliases:["utf-8"],encode:e=>rr.decode(e),decode:e=>rr.encode(e),is:e=>"string"==typeof e},{name:"utf16be",aliases:["utf16","utf-16","utf-16be"],encode:e=>ra.decode(e),decode:e=>ra.encode(e),is:e=>"string"==typeof e},{name:"utf16le",aliases:["utf-16le","ucs2","usc2"],encode:e=>ra.decode(e,{littleEndian:!0}),decode:e=>ra.encode(e,{littleEndian:!0}),is:e=>"string"==typeof e},{name:"pem",encode:(e,A)=>{if(!A?.label)throw TypeError("PEM label is required");return ru(A.label,e,A)},decode:(e,A)=>(function(e,A){let[t]=function(e,A={}){return rd(e,A).map(({lineLength:e,newline:A,...t})=>t)}(e,{label:A,strict:!0});return t.data})(e,A?.label),format:function(e,A){return ru(A.label,e,A)},is:e=>"string"==typeof e&&/-----BEGIN [^-]+-----/.test(e),parse:function(e,A={}){let[t]=rd(e,{...A,strict:!0}),r={label:t.label,headers:t.headers,lineLength:t.lineLength,newline:t.newline};return{bytes:t.data,format:r,normalized:ru(t.label,t.data,r)}}}]);var t8=t8,t9=t9,t7=t7,re=re,rr=rr,ra=ra;t8.encode,t9.encode,re.encode,t7.encode,rr.decode,re.is,t8.is,t9.is,t8.normalize,(A=Q||(Q={}))[A.Sequence=0]="Sequence",A[A.Set=1]="Set",A[A.Choice=2]="Choice",(t=D||(D={}))[t.Any=1]="Any",t[t.Boolean=2]="Boolean",t[t.OctetString=3]="OctetString",t[t.BitString=4]="BitString",t[t.Integer=5]="Integer",t[t.Enumerated=6]="Enumerated",t[t.ObjectIdentifier=7]="ObjectIdentifier",t[t.Utf8String=8]="Utf8String",t[t.BmpString=9]="BmpString",t[t.UniversalString=10]="UniversalString",t[t.NumericString=11]="NumericString",t[t.PrintableString=12]="PrintableString",t[t.TeletexString=13]="TeletexString",t[t.VideotexString=14]="VideotexString",t[t.IA5String=15]="IA5String",t[t.GraphicString=16]="GraphicString",t[t.VisibleString=17]="VisibleString",t[t.GeneralString=18]="GeneralString",t[t.CharacterString=19]="CharacterString",t[t.UTCTime=20]="UTCTime",t[t.GeneralizedTime=21]="GeneralizedTime",t[t.DATE=22]="DATE",t[t.TimeOfDay=23]="TimeOfDay",t[t.DateTime=24]="DateTime",t[t.Duration=25]="Duration",t[t.TIME=26]="TIME",t[t.Null=27]="Null",t[t.RelativeObjectIdentifier=28]="RelativeObjectIdentifier";class rp{unusedBits=0;value=new ArrayBuffer(0);constructor(e,A=0){if(e)if("number"==typeof e)this.fromNumber(e);else if(tv(e))this.unusedBits=A,this.value=tM(e);else throw TypeError("Unsupported type of 'params' argument for BitString")}fromASN(e){if(!(e instanceof AY))throw TypeError("Argument 'asn' is not instance of ASN.1 BitString");return this.unusedBits=e.valueBlock.unusedBits,this.value=tM(e.valueBlock.valueHex),this}toASN(){return new AY({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new AY({name:e})}toNumber(){let e="";for(let A of new Uint8Array(this.value))e+=A.toString(2).padStart(8,"0");return e=e.split("").reverse().join(""),this.unusedBits&&(e=e.slice(this.unusedBits).padStart(this.unusedBits,"0")),parseInt(e,2)}fromNumber(e){let A=e.toString(2),t=A.length+7>>3;this.unusedBits=(t<<3)-A.length;let r=new Uint8Array(t);A=A.padStart(t<<3,"0").split("").reverse().join("");let i=0;for(;i<t;)r[i]=parseInt(A.slice(i<<3,(i<<3)+8),2),i++;this.value=r.buffer}}class rC{buffer;get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){"number"==typeof e?this.buffer=new ArrayBuffer(e):tv(e)?this.buffer=tM(e):Array.isArray(e)?this.buffer=new Uint8Array(e).buffer:this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof Aj))throw TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=tM(e.valueBlock.valueHex),this}toASN(){return new Aj({valueHex:this.buffer})}toSchema(e){return new Aj({name:e})}}let rf={fromASN:e=>e instanceof Aq?null:tM(e.valueBeforeDecodeView),toASN:e=>{if(null===e)return new Aq;let A=AU(e);if(A.result.error)throw Error(A.result.error);return A.result}},rI={fromASN:e=>e.valueBlock.valueHexView.byteLength>=4?e.valueBlock.toString():e.valueBlock.valueDec,toASN:e=>new AW({value:+e})},rw={fromASN:e=>e.valueBlock.valueDec,toASN:e=>new A$({value:e})},rm={fromASN:e=>tM(e.valueBlock.valueHexView),toASN:e=>new AW({valueHex:e})},rE={fromASN:e=>tM(e.valueBlock.valueHexView),toASN:e=>new AY({valueHex:e})},ry={fromASN:e=>e.valueBlock.toString(),toASN:e=>new A1({value:e})},rB={fromASN:e=>e.valueBlock.toString(),toASN:e=>new A2({value:e})},rQ={fromASN:e=>e.valueBlock.value,toASN:e=>new AJ({value:e})},rD={fromASN:e=>tM(e.valueBlock.valueHexView),toASN:e=>new Aj({valueHex:e})};function rb(e){return{fromASN:e=>e.valueBlock.value,toASN:A=>new e({value:A})}}let rS=rb(tA),rk=rb(tr),rR=rb(tn),rv=rb(ta),rG=rb(to),rT=rb(ts),rM=rb(tl),rN=rb(td),rO=rb(tu),rH=rb(tc),rU=rb(th),r_=rb(tg),rx={fromASN:e=>e.toDate(),toASN:e=>new tp({valueDate:e})},rL={fromASN:e=>e.toDate(),toASN:e=>new tC({valueDate:e})},rP={fromASN:()=>null,toASN:()=>new Aq};function rq(e){switch(e){case D.Any:return rf;case D.BitString:return rE;case D.BmpString:return rk;case D.Boolean:return rQ;case D.CharacterString:return r_;case D.Enumerated:return rw;case D.GeneralString:return rU;case D.GeneralizedTime:return rL;case D.GraphicString:return rO;case D.IA5String:return rN;case D.Integer:return rI;case D.Null:return rP;case D.NumericString:return rv;case D.ObjectIdentifier:return ry;case D.RelativeObjectIdentifier:return rB;case D.OctetString:return rD;case D.PrintableString:return rG;case D.TeletexString:return rT;case D.UTCTime:return rx;case D.UniversalString:return rR;case D.Utf8String:return rS;case D.VideotexString:return rM;case D.VisibleString:return rH;default:return null}}var rK=e.i(913230);function rJ(e){return"function"==typeof e&&e.prototype?!!e.prototype.toASN&&!!e.prototype.fromASN||rJ(e.prototype):!!(e&&"object"==typeof e&&"toASN"in e&&"fromASN"in e)}class rF{items=new WeakMap;has(e){return this.items.has(e)}get(e,A=!1){let t=this.items.get(e);if(!t)throw Error(`Cannot get schema for '${e.prototype.constructor.name}' target`);if(A&&!t.schema)throw Error(`Schema '${e.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);return t}cache(e){let A=this.get(e);A.schema||(A.schema=this.create(e,!0))}createDefault(e){let A={type:Q.Sequence,items:{}},t=this.findParentSchema(e);return t&&(Object.assign(A,t),A.items=Object.assign({},A.items,t.items)),A}create(e,A){let t=this.items.get(e)||this.createDefault(e),r=[];for(let e in t.items){let i,n=t.items[e],a=A?e:"";if("number"==typeof n.type){let e=D[n.type],A=rK[e];if(!A)throw Error(`Cannot get ASN1 class by name '${e}'`);i=new A({name:a})}else rJ(n.type)?i=new n.type().toSchema(a):n.optional?this.get(n.type).type===Q.Choice?i=new rK.Any({name:a}):(i=this.create(n.type,!1)).name=a:i=new rK.Any({name:a});let o=!!n.optional||void 0!==n.defaultValue;if(n.repeated&&(i.name="",i=new("set"===n.repeated?rK.Set:rK.Sequence)({name:"",value:[new rK.Repeated({name:a,value:i})]})),null!==n.context&&void 0!==n.context)if(n.implicit)if("number"==typeof n.type||rJ(n.type)){let e=n.repeated?rK.Constructed:rK.Primitive;r.push(new e({name:a,optional:o,idBlock:{tagClass:3,tagNumber:n.context}}))}else{this.cache(n.type);let e=!!n.repeated,A=e?i:this.get(n.type,!0).schema;A="valueBlock"in A?A.valueBlock.value:A.value,r.push(new rK.Constructed({name:e?"":a,optional:o,idBlock:{tagClass:3,tagNumber:n.context},value:A}))}else r.push(new rK.Constructed({optional:o,idBlock:{tagClass:3,tagNumber:n.context},value:[i]}));else i.optional=o,r.push(i)}switch(t.type){case Q.Sequence:return new rK.Sequence({value:r,name:""});case Q.Set:return new rK.Set({value:r,name:""});case Q.Choice:return new rK.Choice({value:r,name:""});default:throw Error("Unsupported ASN1 type in use")}}set(e,A){return this.items.set(e,A),this}findParentSchema(e){let A=Object.getPrototypeOf(e);return A?this.items.get(A)||this.findParentSchema(A):null}}let rj=new rF,rz=e=>A=>{let t;rj.has(A)?t=rj.get(A):(t=rj.createDefault(A),rj.set(A,t)),Object.assign(t,e)},rY=e=>(A,t)=>{let r;rj.has(A.constructor)?r=rj.get(A.constructor):(r=rj.createDefault(A.constructor),rj.set(A.constructor,r));let i=Object.assign({},e);if("number"==typeof i.type&&!i.converter){let r=rq(e.type);if(!r)throw Error(`Cannot get default converter for property '${t}' of ${A.constructor.name}`);i.converter=r}i.raw=e.raw,r.items[t]=i};class rZ extends Error{schemas=[]}class rV{static parse(e,A,t){let r=rK.fromBER(tM(e),t?.berOptions);if(r.result.error)throw Error(r.result.error);return this.fromASN(r.result,A,t)}static fromASN(e,A,t){try{if(rJ(A))return new A().fromASN(e);let r=rj.get(A);rj.cache(A);let i=r.schema,n=this.handleChoiceTypes(e,r,A,i,t);if(n?.result)return n.result;n?.targetSchema&&(i=n.targetSchema);let a=this.handleSequenceTypes(e,r,A,i),o=new A;if(function e(A){if(A){let t=Object.getPrototypeOf(A);return t?.prototype?.constructor===Array||e(t)}return!1}(A))return this.handleArrayTypes(e,r,A,t);return this.processSchemaItems(r,a,o,t),o}catch(e){throw e instanceof rZ&&e.schemas.push(A.name),e}}static handleChoiceTypes(e,A,t,r,i){if(e.constructor===rK.Constructed&&A.type===Q.Choice&&3===e.idBlock.tagClass)for(let r in A.items){let n=A.items[r];if(n.context===e.idBlock.tagNumber&&n.implicit&&"function"==typeof n.type&&rj.has(n.type)){let A=rj.get(n.type);if(A&&A.type===Q.Sequence){let A=new rK.Sequence;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in A.valueBlock){A.valueBlock.value=e.valueBlock.value;let a=this.fromASN(A,n.type,i),o=new t;return o[r]=a,{result:o}}}}}else if(e.constructor===rK.Constructed&&A.type!==Q.Choice){let t=new rK.Constructed({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:A.schema.valueBlock.value});for(let t in A.items)delete e[t];return{targetSchema:t}}return null}static handleSequenceTypes(e,A,t,r){if(A.type===Q.Sequence){let A=rK.compareSchema({},e,r);if(!A.verified)throw new rZ(`Data does not match to ${t.name} ASN1 schema.${A.result.error?` ${A.result.error}`:""}`);return A}{let A=rK.compareSchema({},e,r);if(!A.verified)throw new rZ(`Data does not match to ${t.name} ASN1 schema.${A.result.error?` ${A.result.error}`:""}`);return A}}static processRepeatedField(e,A,t){let r=e.slice(A);if(1===r.length&&"Sequence"===r[0].constructor.name){let e=r[0];e.valueBlock&&e.valueBlock.value&&Array.isArray(e.valueBlock.value)&&(r=e.valueBlock.value)}if("number"!=typeof t.type)return r.filter(e=>e&&e.valueBlock).map(e=>{try{return this.fromASN(e,t.type)}catch{return}}).filter(e=>void 0!==e);{let e=rq(t.type);if(!e)throw Error(`No converter for ASN.1 type ${t.type}`);return r.filter(e=>e&&e.valueBlock).map(A=>{try{return e.fromASN(A)}catch{return}}).filter(e=>void 0!==e)}}static processPrimitiveField(e,A){let t=rq(A.type);if(!t)throw Error(`No converter for ASN.1 type ${A.type}`);return t.fromASN(e)}static isOptionalChoiceField(e){return e.optional&&"function"==typeof e.type&&rj.has(e.type)&&rj.get(e.type).type===Q.Choice}static processOptionalChoiceField(e,A){try{let t=this.fromASN(e,A.type);return{processed:!0,value:t}}catch(e){if(e instanceof rZ&&/Wrong values for Choice type/.test(e.message))return{processed:!1};throw e}}static handleArrayTypes(e,A,t,r){if(!("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)))throw Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");let i=A.itemType;if("number"!=typeof i)return t.from(e.valueBlock.value,e=>this.fromASN(e,i,r));{let A=rq(i);if(!A)throw Error(`Cannot get default converter for array item of ${t.name} ASN1 schema`);return t.from(e.valueBlock.value,e=>A.fromASN(e))}}static processSchemaItems(e,A,t,r){for(let i in e.items){let n,a=A.result[i];if(!a)continue;let o=e.items[i],s=o.type;(n="number"==typeof s||rJ(s)?this.processPrimitiveSchemaItem(a,o,s,r):this.processComplexSchemaItem(a,o,s,r))&&"object"==typeof n&&"value"in n&&"raw"in n?(t[i]=n.value,t[`${i}Raw`]=n.raw):t[i]=n}}static processPrimitiveSchemaItem(e,A,t,r){let i=A.converter??(rJ(t)?new t:null);if(!i)throw Error("Converter is empty");return A.repeated?this.processRepeatedPrimitiveItem(e,A,i,r):this.processSinglePrimitiveItem(e,A,t,i,r)}static processRepeatedPrimitiveItem(e,A,t,r){if(!A.implicit)return Array.from(e,e=>t.fromASN(e));{let i=new("sequence"===A.repeated?rK.Sequence:rK.Set);i.valueBlock=e.valueBlock;let n=rK.fromBER(i.toBER(!1),r?.berOptions);if(-1===n.offset)throw Error(`Cannot parse the child item. ${n.result.error}`);if(!("value"in n.result.valueBlock&&Array.isArray(n.result.valueBlock.value)))throw Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");return Array.from(n.result.valueBlock.value,e=>t.fromASN(e))}}static processSinglePrimitiveItem(e,A,t,r,i){let n=e;if(A.implicit){let e;if(rJ(t))e=new t().toSchema("");else{let A=D[t],r=rK[A];if(!r)throw Error(`Cannot get '${A}' class from asn1js module`);e=new r}e.valueBlock=n.valueBlock,n=rK.fromBER(e.toBER(!1),i?.berOptions).result}return r.fromASN(n)}static processComplexSchemaItem(e,A,t,r){if(A.repeated){if(!Array.isArray(e))throw Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");return Array.from(e,e=>this.fromASN(e,t,r))}{let i=this.handleImplicitTagging(e,A,t);if(this.isOptionalChoiceField(A))try{return this.fromASN(i,t,r)}catch(e){if(e instanceof rZ&&/Wrong values for Choice type/.test(e.message))return;throw e}{let n=this.fromASN(i,t,r);return A.raw?{value:n,raw:e.valueBeforeDecodeView}:n}}}static handleImplicitTagging(e,A,t){if(A.implicit&&"number"==typeof A.context){let A=rj.get(t);if(A.type===Q.Sequence){let A=new rK.Sequence;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in A.valueBlock)return A.valueBlock.value=e.valueBlock.value,A}else if(A.type===Q.Set){let A=new rK.Set;if("value"in e.valueBlock&&Array.isArray(e.valueBlock.value)&&"value"in A.valueBlock)return A.valueBlock.value=e.valueBlock.value,A}}return e}}class rW{static serialize(e){return e instanceof Av?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(e){let A;if(e&&"object"==typeof e&&rJ(e))return e.toASN();if(!(e&&"object"==typeof e))throw TypeError("Parameter 1 should be type of Object.");let t=e.constructor,r=rj.get(t);rj.cache(t);let i=[];if(r.itemType){if(!Array.isArray(e))throw TypeError("Parameter 1 should be type of Array.");if("number"==typeof r.itemType){let A=rq(r.itemType);if(!A)throw Error(`Cannot get default converter for array item of ${t.name} ASN1 schema`);i=e.map(e=>A.toASN(e))}else i=e.map(e=>this.toAsnItem({type:r.itemType},"[]",t,e))}else for(let A in r.items){let n=r.items[A],a=e[A];if(void 0===a||n.defaultValue===a||"object"==typeof n.defaultValue&&"object"==typeof a&&function(e,A){if(!(e&&A)||e.byteLength!==A.byteLength)return!1;let t=new Uint8Array(e),r=new Uint8Array(A);for(let A=0;A<e.byteLength;A++)if(t[A]!==r[A])return!1;return!0}(this.serialize(n.defaultValue),this.serialize(a)))continue;let o=rW.toAsnItem(n,A,t,a);if("number"==typeof n.context)if(n.implicit)if(!n.repeated&&("number"==typeof n.type||rJ(n.type))){let e={};e.valueHex=o instanceof Aq?tM(o.valueBeforeDecodeView):o.valueBlock.toBER(),i.push(new AM({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},...e}))}else i.push(new Ax({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},value:o.valueBlock.value}));else i.push(new Ax({optional:n.optional,idBlock:{tagClass:3,tagNumber:n.context},value:[o]}));else n.repeated?i=i.concat(o):i.push(o)}switch(r.type){case Q.Sequence:A=new A6({value:i});break;case Q.Set:A=new A3({value:i});break;case Q.Choice:if(!i[0])throw Error(`Schema '${t.name}' has wrong data. Choice cannot be empty.`);A=i[0]}return A}static toAsnItem(e,A,t,r){let i;if("number"==typeof e.type){let n=e.converter;if(!n)throw Error(`Property '${A}' doesn't have converter for type ${D[e.type]} in schema '${t.name}'`);if(e.repeated){if(!Array.isArray(r))throw TypeError("Parameter 'objProp' should be type of Array.");let A=Array.from(r,e=>n.toASN(e));i=new("sequence"===e.repeated?A6:A3)({value:A})}else i=n.toASN(r)}else if(e.repeated){if(!Array.isArray(r))throw TypeError("Parameter 'objProp' should be type of Array.");let A=Array.from(r,e=>this.toASN(e));i=new("sequence"===e.repeated?A6:A3)({value:A})}else i=this.toASN(r);return i}}class r${static serialize(e){return rW.serialize(e)}static parse(e,A,t){return rV.parse(e,A,t)}static toString(e,A){let t=AU(tv(e)?tM(e):r$.serialize(e),A?.berOptions);if(-1===t.offset)throw Error(`Cannot decode ASN.1 data. ${t.result.error}`);return t.result.toString()}}var rX=e.i(329736);class r0 extends Array{constructor(e=[]){if("number"==typeof e)super(e);else for(const A of(super(),e))this.push(A)}}var re=re;class r1{static isIPv4(e){return/^(\d{1,3}\.){3}\d{1,3}$/.test(e)}static parseIPv4(e){let A=e.split(".");if(4!==A.length)throw Error("Invalid IPv4 address");return A.map(e=>{let A=parseInt(e,10);if(isNaN(A)||A<0||A>255)throw Error("Invalid IPv4 address part");return A})}static parseIPv6(e){let A=this.expandIPv6(e).split(":");if(8!==A.length)throw Error("Invalid IPv6 address");return A.reduce((e,A)=>{let t=parseInt(A,16);if(isNaN(t)||t<0||t>65535)throw Error("Invalid IPv6 address part");return e.push(t>>8&255),e.push(255&t),e},[])}static expandIPv6(e){if(!e.includes("::"))return e;let A=e.split("::");if(A.length>2)throw Error("Invalid IPv6 address");let t=A[0]?A[0].split(":"):[],r=A[1]?A[1].split(":"):[],i=8-(t.length+r.length);if(i<0)throw Error("Invalid IPv6 address");return[...t,...Array(i).fill("0"),...r].join(":")}static formatIPv6(e){let A=[];for(let t=0;t<16;t+=2)A.push((e[t]<<8|e[t+1]).toString(16));return this.compressIPv6(A.join(":"))}static compressIPv6(e){let A=e.split(":"),t=-1,r=0,i=-1,n=0;for(let e=0;e<A.length;e++)"0"===A[e]?(-1===i&&(i=e),n++):(n>r&&(t=i,r=n),i=-1,n=0);if(n>r&&(t=i,r=n),r>1){let e=A.slice(0,t).join(":"),i=A.slice(t+r).join(":");return`${e}::${i}`}return e}static parseCIDR(e){let[A,t]=e.split("/"),r=parseInt(t,10);if(this.isIPv4(A)){if(r<0||r>32)throw Error("Invalid IPv4 prefix length");return[this.parseIPv4(A),r]}if(r<0||r>128)throw Error("Invalid IPv6 prefix length");return[this.parseIPv6(A),r]}static decodeIP(e){if(64===e.length&&0===parseInt(e,16))return"::/0";if(16!==e.length)return e;let A=parseInt(e.slice(8),16).toString(2).split("").reduce((e,A)=>e+ +A,0),t=e.slice(0,8).replace(/(.{2})/g,e=>`${parseInt(e,16)}.`);return t=t.slice(0,-1),`${t}/${A}`}static toString(e){let A=new Uint8Array(e);if(4===A.length)return Array.from(A).join(".");if(16===A.length)return this.formatIPv6(A);if(8===A.length||32===A.length){let e=A.length/2,t=A.slice(0,e),r=A.slice(e);if(A.every(e=>0===e))return 8===A.length?"0.0.0.0/0":"::/0";let i=r.reduce((e,A)=>e+(A.toString(2).match(/1/g)||[]).length,0);if(8===A.length){let e=Array.from(t).join(".");return`${e}/${i}`}{let e=this.formatIPv6(t);return`${e}/${i}`}}return this.decodeIP(re.encode(e))}static fromString(e){if(e.includes("/")){let[A,t]=this.parseCIDR(e),r=new Uint8Array(A.length),i=t;for(let e=0;e<r.length;e++)i>=8?(r[e]=255,i-=8):i>0&&(r[e]=255<<8-i,i=0);let n=new Uint8Array(2*A.length);return n.set(A,0),n.set(r,A.length),n.buffer}return new Uint8Array(this.isIPv4(e)?this.parseIPv4(e):this.parseIPv6(e)).buffer}}var re=re;let r8=class{teletexString;printableString;universalString;utf8String;bmpString;constructor(e={}){Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};(0,rX.__decorate)([rY({type:D.TeletexString})],r8.prototype,"teletexString",void 0),(0,rX.__decorate)([rY({type:D.PrintableString})],r8.prototype,"printableString",void 0),(0,rX.__decorate)([rY({type:D.UniversalString})],r8.prototype,"universalString",void 0),(0,rX.__decorate)([rY({type:D.Utf8String})],r8.prototype,"utf8String",void 0),(0,rX.__decorate)([rY({type:D.BmpString})],r8.prototype,"bmpString",void 0),r8=(0,rX.__decorate)([rz({type:Q.Choice})],r8);let r4=class extends r8{ia5String;anyValue;constructor(e={}){super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?re.encode(this.anyValue):super.toString())}};(0,rX.__decorate)([rY({type:D.IA5String})],r4.prototype,"ia5String",void 0),(0,rX.__decorate)([rY({type:D.Any})],r4.prototype,"anyValue",void 0),r4=(0,rX.__decorate)([rz({type:Q.Choice})],r4);class r2{type="";value=new r4;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],r2.prototype,"type",void 0),(0,rX.__decorate)([rY({type:r4})],r2.prototype,"value",void 0);let r6=b=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,b.prototype)}};r6=b=(0,rX.__decorate)([rz({type:Q.Set,itemType:r2})],r6);let r3=S=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,S.prototype)}};r3=S=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:r6})],r3);let r5=k=class extends r3{constructor(e){super(e),Object.setPrototypeOf(this,k.prototype)}};r5=k=(0,rX.__decorate)([rz({type:Q.Sequence})],r5);class r9{typeId="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],r9.prototype,"typeId",void 0),(0,rX.__decorate)([rY({type:D.Any,context:0})],r9.prototype,"value",void 0);class r7{nameAssigner;partyName=new r8;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:r8,optional:!0,context:0,implicit:!0})],r7.prototype,"nameAssigner",void 0),(0,rX.__decorate)([rY({type:r8,context:1,implicit:!0})],r7.prototype,"partyName",void 0);let ie=class{otherName;rfc822Name;dNSName;x400Address;directoryName;ediPartyName;uniformResourceIdentifier;iPAddress;registeredID;constructor(e={}){Object.assign(this,e)}};(0,rX.__decorate)([rY({type:r9,context:0,implicit:!0})],ie.prototype,"otherName",void 0),(0,rX.__decorate)([rY({type:D.IA5String,context:1,implicit:!0})],ie.prototype,"rfc822Name",void 0),(0,rX.__decorate)([rY({type:D.IA5String,context:2,implicit:!0})],ie.prototype,"dNSName",void 0),(0,rX.__decorate)([rY({type:D.Any,context:3,implicit:!0})],ie.prototype,"x400Address",void 0),(0,rX.__decorate)([rY({type:r5,context:4,implicit:!1})],ie.prototype,"directoryName",void 0),(0,rX.__decorate)([rY({type:r7,context:5})],ie.prototype,"ediPartyName",void 0),(0,rX.__decorate)([rY({type:D.IA5String,context:6,implicit:!0})],ie.prototype,"uniformResourceIdentifier",void 0),(0,rX.__decorate)([rY({type:D.OctetString,context:7,implicit:!0,converter:{fromASN:e=>r1.toString(rD.fromASN(e)),toASN:e=>rD.toASN(r1.fromString(e))}})],ie.prototype,"iPAddress",void 0),(0,rX.__decorate)([rY({type:D.ObjectIdentifier,context:8,implicit:!0})],ie.prototype,"registeredID",void 0),ie=(0,rX.__decorate)([rz({type:Q.Choice})],ie);let iA="1.3.6.1.5.5.7",it=`${iA}.1`,ir=`${iA}.3`,ii=`${iA}.48`,ia=`${ii}.1`,io=`${ii}.2`,is=`${ii}.3`,il=`${ii}.5`,id="2.5.29",iu=`${it}.1`;class ic{accessMethod="";accessLocation=new ie;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],ic.prototype,"accessMethod",void 0),(0,rX.__decorate)([rY({type:ie})],ic.prototype,"accessLocation",void 0);let ih=R=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,R.prototype)}};ih=R=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:ic})],ih);let ig=`${id}.35`;class ip extends rC{}class iC{keyIdentifier;authorityCertIssuer;authorityCertSerialNumber;constructor(e={}){e&&Object.assign(this,e)}}(0,rX.__decorate)([rY({type:ip,context:0,optional:!0,implicit:!0})],iC.prototype,"keyIdentifier",void 0),(0,rX.__decorate)([rY({type:ie,context:1,optional:!0,implicit:!0,repeated:"sequence"})],iC.prototype,"authorityCertIssuer",void 0),(0,rX.__decorate)([rY({type:D.Integer,context:2,optional:!0,implicit:!0,converter:rm})],iC.prototype,"authorityCertSerialNumber",void 0);let iI=`${id}.19`;class iw{cA=!1;pathLenConstraint;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.Boolean,defaultValue:!1})],iw.prototype,"cA",void 0),(0,rX.__decorate)([rY({type:D.Integer,optional:!0})],iw.prototype,"pathLenConstraint",void 0);let im=v=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,v.prototype)}};im=v=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:ie})],im);let iE=G=class extends im{constructor(e){super(e),Object.setPrototypeOf(this,G.prototype)}};iE=G=(0,rX.__decorate)([rz({type:Q.Sequence})],iE);let iy=`${id}.32`,iB=class{ia5String;visibleString;bmpString;utf8String;constructor(e={}){Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};(0,rX.__decorate)([rY({type:D.IA5String})],iB.prototype,"ia5String",void 0),(0,rX.__decorate)([rY({type:D.VisibleString})],iB.prototype,"visibleString",void 0),(0,rX.__decorate)([rY({type:D.BmpString})],iB.prototype,"bmpString",void 0),(0,rX.__decorate)([rY({type:D.Utf8String})],iB.prototype,"utf8String",void 0),iB=(0,rX.__decorate)([rz({type:Q.Choice})],iB);class iQ{organization=new iB;noticeNumbers=[];constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:iB})],iQ.prototype,"organization",void 0),(0,rX.__decorate)([rY({type:D.Integer,repeated:"sequence"})],iQ.prototype,"noticeNumbers",void 0);class iD{noticeRef;explicitText;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:iQ,optional:!0})],iD.prototype,"noticeRef",void 0),(0,rX.__decorate)([rY({type:iB,optional:!0})],iD.prototype,"explicitText",void 0);let ib=class{cPSuri;userNotice;constructor(e={}){Object.assign(this,e)}};(0,rX.__decorate)([rY({type:D.IA5String})],ib.prototype,"cPSuri",void 0),(0,rX.__decorate)([rY({type:iD})],ib.prototype,"userNotice",void 0),ib=(0,rX.__decorate)([rz({type:Q.Choice})],ib);class iS{policyQualifierId="";qualifier=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],iS.prototype,"policyQualifierId",void 0),(0,rX.__decorate)([rY({type:D.Any})],iS.prototype,"qualifier",void 0);class ik{policyIdentifier="";policyQualifiers;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],ik.prototype,"policyIdentifier",void 0),(0,rX.__decorate)([rY({type:iS,repeated:"sequence",optional:!0})],ik.prototype,"policyQualifiers",void 0);let iR=T=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,T.prototype)}};iR=T=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:ik})],iR);let iv=class{value;constructor(e=0){this.value=e}};(0,rX.__decorate)([rY({type:D.Integer})],iv.prototype,"value",void 0),iv=(0,rX.__decorate)([rz({type:Q.Choice})],iv);let iG=class extends iv{};iG=(0,rX.__decorate)([rz({type:Q.Choice})],iG);let iT=`${id}.31`;(r=N||(N={}))[r.unused=1]="unused",r[r.keyCompromise=2]="keyCompromise",r[r.cACompromise=4]="cACompromise",r[r.affiliationChanged=8]="affiliationChanged",r[r.superseded=16]="superseded",r[r.cessationOfOperation=32]="cessationOfOperation",r[r.certificateHold=64]="certificateHold",r[r.privilegeWithdrawn=128]="privilegeWithdrawn",r[r.aACompromise=256]="aACompromise";class iM extends rp{toJSON(){let e=[],A=this.toNumber();return A&N.aACompromise&&e.push("aACompromise"),A&N.affiliationChanged&&e.push("affiliationChanged"),A&N.cACompromise&&e.push("cACompromise"),A&N.certificateHold&&e.push("certificateHold"),A&N.cessationOfOperation&&e.push("cessationOfOperation"),A&N.keyCompromise&&e.push("keyCompromise"),A&N.privilegeWithdrawn&&e.push("privilegeWithdrawn"),A&N.superseded&&e.push("superseded"),A&N.unused&&e.push("unused"),e}toString(){return`[${this.toJSON().join(", ")}]`}}let iN=class{fullName;nameRelativeToCRLIssuer;constructor(e={}){Object.assign(this,e)}};(0,rX.__decorate)([rY({type:ie,context:0,repeated:"sequence",implicit:!0})],iN.prototype,"fullName",void 0),(0,rX.__decorate)([rY({type:r6,context:1,implicit:!0})],iN.prototype,"nameRelativeToCRLIssuer",void 0),iN=(0,rX.__decorate)([rz({type:Q.Choice})],iN);class iO{distributionPoint;reasons;cRLIssuer;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:iN,context:0,optional:!0})],iO.prototype,"distributionPoint",void 0),(0,rX.__decorate)([rY({type:iM,context:1,optional:!0,implicit:!0})],iO.prototype,"reasons",void 0),(0,rX.__decorate)([rY({type:ie,context:2,optional:!0,repeated:"sequence",implicit:!0})],iO.prototype,"cRLIssuer",void 0);let iH=M=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,M.prototype)}};iH=M=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:iO})],iH);let iU=O=class extends iH{constructor(e){super(e),Object.setPrototypeOf(this,O.prototype)}};iU=O=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:iO})],iU);class i_{static ONLY=!1;distributionPoint;onlyContainsUserCerts=i_.ONLY;onlyContainsCACerts=i_.ONLY;onlySomeReasons;indirectCRL=i_.ONLY;onlyContainsAttributeCerts=i_.ONLY;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:iN,context:0,optional:!0})],i_.prototype,"distributionPoint",void 0),(0,rX.__decorate)([rY({type:D.Boolean,context:1,defaultValue:i_.ONLY,implicit:!0})],i_.prototype,"onlyContainsUserCerts",void 0),(0,rX.__decorate)([rY({type:D.Boolean,context:2,defaultValue:i_.ONLY,implicit:!0})],i_.prototype,"onlyContainsCACerts",void 0),(0,rX.__decorate)([rY({type:iM,context:3,optional:!0,implicit:!0})],i_.prototype,"onlySomeReasons",void 0),(0,rX.__decorate)([rY({type:D.Boolean,context:4,defaultValue:i_.ONLY,implicit:!0})],i_.prototype,"indirectCRL",void 0),(0,rX.__decorate)([rY({type:D.Boolean,context:5,defaultValue:i_.ONLY,implicit:!0})],i_.prototype,"onlyContainsAttributeCerts",void 0),(i=H||(H={}))[i.unspecified=0]="unspecified",i[i.keyCompromise=1]="keyCompromise",i[i.cACompromise=2]="cACompromise",i[i.affiliationChanged=3]="affiliationChanged",i[i.superseded=4]="superseded",i[i.cessationOfOperation=5]="cessationOfOperation",i[i.certificateHold=6]="certificateHold",i[i.removeFromCRL=8]="removeFromCRL",i[i.privilegeWithdrawn=9]="privilegeWithdrawn",i[i.aACompromise=10]="aACompromise";let ix=class{reason=H.unspecified;constructor(e=H.unspecified){this.reason=e}toJSON(){return H[this.reason]}toString(){return this.toJSON()}};(0,rX.__decorate)([rY({type:D.Enumerated})],ix.prototype,"reason",void 0),ix=(0,rX.__decorate)([rz({type:Q.Choice})],ix);let iL=`${id}.37`,iP=U=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,U.prototype)}};iP=U=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:D.ObjectIdentifier})],iP);let iq=`${ir}.1`,iK=`${ir}.2`,iJ=`${ir}.3`,iF=`${ir}.4`,ij=`${ir}.8`,iz=`${ir}.9`,iY=class{value;constructor(e=new ArrayBuffer(0)){this.value=e}};(0,rX.__decorate)([rY({type:D.Integer,converter:rm})],iY.prototype,"value",void 0),iY=(0,rX.__decorate)([rz({type:Q.Choice})],iY);let iZ=class{value=new Date;constructor(e){e&&(this.value=e)}};(0,rX.__decorate)([rY({type:D.GeneralizedTime})],iZ.prototype,"value",void 0),iZ=(0,rX.__decorate)([rz({type:Q.Choice})],iZ);let iV=`${id}.18`,iW=_=class extends im{constructor(e){super(e),Object.setPrototypeOf(this,_.prototype)}};iW=_=(0,rX.__decorate)([rz({type:Q.Sequence})],iW);let i$=`${id}.15`;(n=x||(x={}))[n.digitalSignature=1]="digitalSignature",n[n.nonRepudiation=2]="nonRepudiation",n[n.keyEncipherment=4]="keyEncipherment",n[n.dataEncipherment=8]="dataEncipherment",n[n.keyAgreement=16]="keyAgreement",n[n.keyCertSign=32]="keyCertSign",n[n.cRLSign=64]="cRLSign",n[n.encipherOnly=128]="encipherOnly",n[n.decipherOnly=256]="decipherOnly";class iX extends rp{toJSON(){let e=this.toNumber(),A=[];return e&x.cRLSign&&A.push("crlSign"),e&x.dataEncipherment&&A.push("dataEncipherment"),e&x.decipherOnly&&A.push("decipherOnly"),e&x.digitalSignature&&A.push("digitalSignature"),e&x.encipherOnly&&A.push("encipherOnly"),e&x.keyAgreement&&A.push("keyAgreement"),e&x.keyCertSign&&A.push("keyCertSign"),e&x.keyEncipherment&&A.push("keyEncipherment"),e&x.nonRepudiation&&A.push("nonRepudiation"),A}toString(){return`[${this.toJSON().join(", ")}]`}}class i0{base=new ie;minimum=0;maximum;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:ie})],i0.prototype,"base",void 0),(0,rX.__decorate)([rY({type:D.Integer,context:0,defaultValue:0,implicit:!0})],i0.prototype,"minimum",void 0),(0,rX.__decorate)([rY({type:D.Integer,context:1,optional:!0,implicit:!0})],i0.prototype,"maximum",void 0);let i1=L=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,L.prototype)}};i1=L=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:i0})],i1);class i8{permittedSubtrees;excludedSubtrees;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:i1,context:0,optional:!0,implicit:!0})],i8.prototype,"permittedSubtrees",void 0),(0,rX.__decorate)([rY({type:i1,context:1,optional:!0,implicit:!0})],i8.prototype,"excludedSubtrees",void 0);class i4{requireExplicitPolicy;inhibitPolicyMapping;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.Integer,context:0,implicit:!0,optional:!0,converter:rm})],i4.prototype,"requireExplicitPolicy",void 0),(0,rX.__decorate)([rY({type:D.Integer,context:1,implicit:!0,optional:!0,converter:rm})],i4.prototype,"inhibitPolicyMapping",void 0);class i2{issuerDomainPolicy="";subjectDomainPolicy="";constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],i2.prototype,"issuerDomainPolicy",void 0),(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],i2.prototype,"subjectDomainPolicy",void 0);let i6=P=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,P.prototype)}};i6=P=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:i2})],i6);let i3=`${id}.17`,i5=q=class extends im{constructor(e){super(e),Object.setPrototypeOf(this,q.prototype)}};i5=q=(0,rX.__decorate)([rz({type:Q.Sequence})],i5);class i9{type="";values=[];constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],i9.prototype,"type",void 0),(0,rX.__decorate)([rY({type:D.Any,repeated:"set"})],i9.prototype,"values",void 0);let i7=K=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,K.prototype)}};i7=K=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:i9})],i7);let ne=`${id}.14`;class nA extends ip{}class nt{notBefore;notAfter;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.GeneralizedTime,context:0,implicit:!0,optional:!0})],nt.prototype,"notBefore",void 0),(0,rX.__decorate)([rY({type:D.GeneralizedTime,context:1,implicit:!0,optional:!0})],nt.prototype,"notAfter",void 0),(a=J||(J={}))[a.keyUpdateAllowed=1]="keyUpdateAllowed",a[a.newExtensions=2]="newExtensions",a[a.pKIXCertificate=4]="pKIXCertificate";class nr extends rp{toJSON(){let e=[],A=this.toNumber();return A&J.pKIXCertificate&&e.push("pKIXCertificate"),A&J.newExtensions&&e.push("newExtensions"),A&J.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return`[${this.toJSON().join(", ")}]`}}class ni{entrustVers="";entrustInfoFlags=new nr;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.GeneralString})],ni.prototype,"entrustVers",void 0),(0,rX.__decorate)([rY({type:nr})],ni.prototype,"entrustInfoFlags",void 0);let nn=F=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,F.prototype)}};nn=F=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:ic})],nn);class na{algorithm="";parameters;constructor(e={}){Object.assign(this,e)}isEqual(e){return e instanceof na&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&function(e,A,t={}){let r=tT(e),i=tT(A);if(!t.constantTime&&r.byteLength!==i.byteLength)return!1;let n=Math.max(r.byteLength,i.byteLength),a=r.byteLength^i.byteLength;for(let e=0;e<n;e++)a|=(r[e]??0)^(i[e]??0);return 0===a}(e.parameters,this.parameters)||e.parameters===this.parameters)}}(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],na.prototype,"algorithm",void 0),(0,rX.__decorate)([rY({type:D.Any,optional:!0})],na.prototype,"parameters",void 0);class no{algorithm=new na;subjectPublicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:na})],no.prototype,"algorithm",void 0),(0,rX.__decorate)([rY({type:D.BitString})],no.prototype,"subjectPublicKey",void 0);let ns=class{utcTime;generalTime;constructor(e){if(e)if("string"==typeof e||"number"==typeof e||e instanceof Date){const A=new Date(e);A.setMilliseconds(0),A.getUTCFullYear()>2049?this.generalTime=A:this.utcTime=A}else Object.assign(this,e)}getTime(){let e=this.utcTime||this.generalTime;if(!e)throw Error("Cannot get time from CHOICE object");return e}};(0,rX.__decorate)([rY({type:D.UTCTime})],ns.prototype,"utcTime",void 0),(0,rX.__decorate)([rY({type:D.GeneralizedTime})],ns.prototype,"generalTime",void 0),ns=(0,rX.__decorate)([rz({type:Q.Choice})],ns);class nl{notBefore=new ns(new Date);notAfter=new ns(new Date);constructor(e){e&&(this.notBefore=new ns(e.notBefore),this.notAfter=new ns(e.notAfter))}}(0,rX.__decorate)([rY({type:ns})],nl.prototype,"notBefore",void 0),(0,rX.__decorate)([rY({type:ns})],nl.prototype,"notAfter",void 0);class nd{static CRITICAL=!1;extnID="";critical=nd.CRITICAL;extnValue=new rC;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],nd.prototype,"extnID",void 0),(0,rX.__decorate)([rY({type:D.Boolean,defaultValue:nd.CRITICAL})],nd.prototype,"critical",void 0),(0,rX.__decorate)([rY({type:rC})],nd.prototype,"extnValue",void 0);let nu=j=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,j.prototype)}};nu=j=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:nd})],nu),(o=z||(z={}))[o.v1=0]="v1",o[o.v2=1]="v2",o[o.v3=2]="v3";class nc{version=z.v1;serialNumber=new ArrayBuffer(0);signature=new na;issuer=new r5;validity=new nl;subject=new r5;subjectPublicKeyInfo=new no;issuerUniqueID;subjectUniqueID;extensions;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.Integer,context:0,defaultValue:z.v1})],nc.prototype,"version",void 0),(0,rX.__decorate)([rY({type:D.Integer,converter:rm})],nc.prototype,"serialNumber",void 0),(0,rX.__decorate)([rY({type:na})],nc.prototype,"signature",void 0),(0,rX.__decorate)([rY({type:r5})],nc.prototype,"issuer",void 0),(0,rX.__decorate)([rY({type:nl})],nc.prototype,"validity",void 0),(0,rX.__decorate)([rY({type:r5})],nc.prototype,"subject",void 0),(0,rX.__decorate)([rY({type:no})],nc.prototype,"subjectPublicKeyInfo",void 0),(0,rX.__decorate)([rY({type:D.BitString,context:1,implicit:!0,optional:!0})],nc.prototype,"issuerUniqueID",void 0),(0,rX.__decorate)([rY({type:D.BitString,context:2,implicit:!0,optional:!0})],nc.prototype,"subjectUniqueID",void 0),(0,rX.__decorate)([rY({type:nu,context:3,optional:!0})],nc.prototype,"extensions",void 0);class nh{tbsCertificate=new nc;tbsCertificateRaw;signatureAlgorithm=new na;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:nc,raw:!0})],nh.prototype,"tbsCertificate",void 0),(0,rX.__decorate)([rY({type:na})],nh.prototype,"signatureAlgorithm",void 0),(0,rX.__decorate)([rY({type:D.BitString})],nh.prototype,"signatureValue",void 0);class ng{userCertificate=new ArrayBuffer(0);revocationDate=new ns;crlEntryExtensions;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.Integer,converter:rm})],ng.prototype,"userCertificate",void 0),(0,rX.__decorate)([rY({type:ns})],ng.prototype,"revocationDate",void 0),(0,rX.__decorate)([rY({type:nd,optional:!0,repeated:"sequence"})],ng.prototype,"crlEntryExtensions",void 0);class np{version;signature=new na;issuer=new r5;thisUpdate=new ns;nextUpdate;revokedCertificates;crlExtensions;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.Integer,optional:!0})],np.prototype,"version",void 0),(0,rX.__decorate)([rY({type:na})],np.prototype,"signature",void 0),(0,rX.__decorate)([rY({type:r5})],np.prototype,"issuer",void 0),(0,rX.__decorate)([rY({type:ns})],np.prototype,"thisUpdate",void 0),(0,rX.__decorate)([rY({type:ns,optional:!0})],np.prototype,"nextUpdate",void 0),(0,rX.__decorate)([rY({type:ng,repeated:"sequence",optional:!0})],np.prototype,"revokedCertificates",void 0),(0,rX.__decorate)([rY({type:nd,optional:!0,context:0,repeated:"sequence"})],np.prototype,"crlExtensions",void 0);class nC{tbsCertList=new np;tbsCertListRaw;signatureAlgorithm=new na;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:np,raw:!0})],nC.prototype,"tbsCertList",void 0),(0,rX.__decorate)([rY({type:na})],nC.prototype,"signatureAlgorithm",void 0),(0,rX.__decorate)([rY({type:D.BitString})],nC.prototype,"signature",void 0);class nf{issuer=new r5;serialNumber=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:r5})],nf.prototype,"issuer",void 0),(0,rX.__decorate)([rY({type:D.Integer,converter:rm})],nf.prototype,"serialNumber",void 0);let nI=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};(0,rX.__decorate)([rY({type:nA,context:0,implicit:!0})],nI.prototype,"subjectKeyIdentifier",void 0),(0,rX.__decorate)([rY({type:nf})],nI.prototype,"issuerAndSerialNumber",void 0),nI=(0,rX.__decorate)([rz({type:Q.Choice})],nI),(s=Y||(Y={}))[s.v0=0]="v0",s[s.v1=1]="v1",s[s.v2=2]="v2",s[s.v3=3]="v3",s[s.v4=4]="v4",s[s.v5=5]="v5";let nw=class extends na{};nw=(0,rX.__decorate)([rz({type:Q.Sequence})],nw);let nm=class extends na{};nm=(0,rX.__decorate)([rz({type:Q.Sequence})],nm);let nE=class extends na{};nE=(0,rX.__decorate)([rz({type:Q.Sequence})],nE);let ny=class extends na{};ny=(0,rX.__decorate)([rz({type:Q.Sequence})],ny);let nB=class extends na{};nB=(0,rX.__decorate)([rz({type:Q.Sequence})],nB);let nQ=class extends na{};nQ=(0,rX.__decorate)([rz({type:Q.Sequence})],nQ);class nD{attrType="";attrValues=[];constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],nD.prototype,"attrType",void 0),(0,rX.__decorate)([rY({type:D.Any,repeated:"set"})],nD.prototype,"attrValues",void 0);class nb{version=Y.v0;sid=new nI;digestAlgorithm=new nw;signedAttrs;signedAttrsRaw;signatureAlgorithm=new nm;signature=new rC;unsignedAttrs;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.Integer})],nb.prototype,"version",void 0),(0,rX.__decorate)([rY({type:nI})],nb.prototype,"sid",void 0),(0,rX.__decorate)([rY({type:nw})],nb.prototype,"digestAlgorithm",void 0),(0,rX.__decorate)([rY({type:nD,repeated:"set",context:0,implicit:!0,optional:!0,raw:!0})],nb.prototype,"signedAttrs",void 0),(0,rX.__decorate)([rY({type:nm})],nb.prototype,"signatureAlgorithm",void 0),(0,rX.__decorate)([rY({type:rC})],nb.prototype,"signature",void 0),(0,rX.__decorate)([rY({type:nD,repeated:"set",context:1,implicit:!0,optional:!0})],nb.prototype,"unsignedAttrs",void 0);let nS=Z=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,Z.prototype)}};nS=Z=(0,rX.__decorate)([rz({type:Q.Set,itemType:nb})],nS);let nk=class extends nb{};nk=(0,rX.__decorate)([rz({type:Q.Sequence})],nk);let nR=class extends ns{};nR=(0,rX.__decorate)([rz({type:Q.Choice})],nR);class nv{acIssuer=new ie;acSerial=0;attrs=[];constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:ie})],nv.prototype,"acIssuer",void 0),(0,rX.__decorate)([rY({type:D.Integer})],nv.prototype,"acSerial",void 0),(0,rX.__decorate)([rY({type:i9,repeated:"sequence"})],nv.prototype,"attrs",void 0);let nG=V=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,V.prototype)}};nG=V=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:D.ObjectIdentifier})],nG);class nT{pathLenConstraint;permittedAttrs;excludedAttrs;permitUnSpecified=!0;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.Integer,optional:!0})],nT.prototype,"pathLenConstraint",void 0),(0,rX.__decorate)([rY({type:nG,implicit:!0,context:0,optional:!0})],nT.prototype,"permittedAttrs",void 0),(0,rX.__decorate)([rY({type:nG,implicit:!0,context:1,optional:!0})],nT.prototype,"excludedAttrs",void 0),(0,rX.__decorate)([rY({type:D.Boolean,defaultValue:!0})],nT.prototype,"permitUnSpecified",void 0);class nM{issuer=new im;serial=new ArrayBuffer(0);issuerUID=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:im})],nM.prototype,"issuer",void 0),(0,rX.__decorate)([rY({type:D.Integer,converter:rm})],nM.prototype,"serial",void 0),(0,rX.__decorate)([rY({type:D.BitString,optional:!0})],nM.prototype,"issuerUID",void 0),(l=W||(W={}))[l.publicKey=0]="publicKey",l[l.publicKeyCert=1]="publicKeyCert",l[l.otherObjectTypes=2]="otherObjectTypes";class nN{digestedObjectType=W.publicKey;otherObjectTypeID;digestAlgorithm=new na;objectDigest=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.Enumerated})],nN.prototype,"digestedObjectType",void 0),(0,rX.__decorate)([rY({type:D.ObjectIdentifier,optional:!0})],nN.prototype,"otherObjectTypeID",void 0),(0,rX.__decorate)([rY({type:na})],nN.prototype,"digestAlgorithm",void 0),(0,rX.__decorate)([rY({type:D.BitString})],nN.prototype,"objectDigest",void 0);class nO{issuerName;baseCertificateID;objectDigestInfo;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:im,optional:!0})],nO.prototype,"issuerName",void 0),(0,rX.__decorate)([rY({type:nM,context:0,implicit:!0,optional:!0})],nO.prototype,"baseCertificateID",void 0),(0,rX.__decorate)([rY({type:nN,context:1,implicit:!0,optional:!0})],nO.prototype,"objectDigestInfo",void 0);let nH=class{v1Form;v2Form;constructor(e={}){Object.assign(this,e)}};(0,rX.__decorate)([rY({type:ie,repeated:"sequence"})],nH.prototype,"v1Form",void 0),(0,rX.__decorate)([rY({type:nO,context:0,implicit:!0})],nH.prototype,"v2Form",void 0),nH=(0,rX.__decorate)([rz({type:Q.Choice})],nH);class nU{notBeforeTime=new Date;notAfterTime=new Date;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.GeneralizedTime})],nU.prototype,"notBeforeTime",void 0),(0,rX.__decorate)([rY({type:D.GeneralizedTime})],nU.prototype,"notAfterTime",void 0);class n_{baseCertificateID;entityName;objectDigestInfo;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:nM,implicit:!0,context:0,optional:!0})],n_.prototype,"baseCertificateID",void 0),(0,rX.__decorate)([rY({type:im,implicit:!0,context:1,optional:!0})],n_.prototype,"entityName",void 0),(0,rX.__decorate)([rY({type:nN,implicit:!0,context:2,optional:!0})],n_.prototype,"objectDigestInfo",void 0),(d=$||($={}))[d.v2=1]="v2";class nx{version=$.v2;holder=new n_;issuer=new nH;signature=new na;serialNumber=new ArrayBuffer(0);attrCertValidityPeriod=new nU;attributes=[];issuerUniqueID;extensions;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.Integer})],nx.prototype,"version",void 0),(0,rX.__decorate)([rY({type:n_})],nx.prototype,"holder",void 0),(0,rX.__decorate)([rY({type:nH})],nx.prototype,"issuer",void 0),(0,rX.__decorate)([rY({type:na})],nx.prototype,"signature",void 0),(0,rX.__decorate)([rY({type:D.Integer,converter:rm})],nx.prototype,"serialNumber",void 0),(0,rX.__decorate)([rY({type:nU})],nx.prototype,"attrCertValidityPeriod",void 0),(0,rX.__decorate)([rY({type:i9,repeated:"sequence"})],nx.prototype,"attributes",void 0),(0,rX.__decorate)([rY({type:D.BitString,optional:!0})],nx.prototype,"issuerUniqueID",void 0),(0,rX.__decorate)([rY({type:nu,optional:!0})],nx.prototype,"extensions",void 0);class nL{acinfo=new nx;signatureAlgorithm=new na;signatureValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:nx})],nL.prototype,"acinfo",void 0),(0,rX.__decorate)([rY({type:na})],nL.prototype,"signatureAlgorithm",void 0),(0,rX.__decorate)([rY({type:D.BitString})],nL.prototype,"signatureValue",void 0),(u=X||(X={}))[u.unmarked=1]="unmarked",u[u.unclassified=2]="unclassified",u[u.restricted=4]="restricted",u[u.confidential=8]="confidential",u[u.secret=16]="secret",u[u.topSecret=32]="topSecret";class nP extends rp{}class nq{type="";value=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.ObjectIdentifier,implicit:!0,context:0})],nq.prototype,"type",void 0),(0,rX.__decorate)([rY({type:D.Any,implicit:!0,context:1})],nq.prototype,"value",void 0);class nK{policyId="";classList=new nP(X.unclassified);securityCategories;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],nK.prototype,"policyId",void 0),(0,rX.__decorate)([rY({type:nP,defaultValue:new nP(X.unclassified)})],nK.prototype,"classList",void 0),(0,rX.__decorate)([rY({type:nq,repeated:"set"})],nK.prototype,"securityCategories",void 0);class nJ{cotets;oid;string;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:rC})],nJ.prototype,"cotets",void 0),(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],nJ.prototype,"oid",void 0),(0,rX.__decorate)([rY({type:D.Utf8String})],nJ.prototype,"string",void 0);class nF{policyAuthority;values=[];constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:im,implicit:!0,context:0,optional:!0})],nF.prototype,"policyAuthority",void 0),(0,rX.__decorate)([rY({type:nJ,repeated:"sequence"})],nF.prototype,"values",void 0);class nj{targetCertificate=new nM;targetName;certDigestInfo;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:nM})],nj.prototype,"targetCertificate",void 0),(0,rX.__decorate)([rY({type:ie,optional:!0})],nj.prototype,"targetName",void 0),(0,rX.__decorate)([rY({type:nN,optional:!0})],nj.prototype,"certDigestInfo",void 0);let nz=class{targetName;targetGroup;targetCert;constructor(e={}){Object.assign(this,e)}};(0,rX.__decorate)([rY({type:ie,context:0,implicit:!0})],nz.prototype,"targetName",void 0),(0,rX.__decorate)([rY({type:ie,context:1,implicit:!0})],nz.prototype,"targetGroup",void 0),(0,rX.__decorate)([rY({type:nj,context:2,implicit:!0})],nz.prototype,"targetCert",void 0),nz=(0,rX.__decorate)([rz({type:Q.Choice})],nz);let nY=ee=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,ee.prototype)}};nY=ee=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:nz})],nY);let nZ=eA=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,eA.prototype)}};nZ=eA=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:nY})],nZ);class nV{roleAuthority;roleName;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:im,implicit:!0,context:0,optional:!0})],nV.prototype,"roleAuthority",void 0),(0,rX.__decorate)([rY({type:ie,implicit:!0,context:1})],nV.prototype,"roleName",void 0);class nW{service=new ie;ident=new ie;authInfo;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:ie})],nW.prototype,"service",void 0),(0,rX.__decorate)([rY({type:ie})],nW.prototype,"ident",void 0),(0,rX.__decorate)([rY({type:rC,optional:!0})],nW.prototype,"authInfo",void 0);class n${otherCertFormat="";otherCert=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],n$.prototype,"otherCertFormat",void 0),(0,rX.__decorate)([rY({type:D.Any})],n$.prototype,"otherCert",void 0);let nX=class{certificate;v2AttrCert;other;constructor(e={}){Object.assign(this,e)}};(0,rX.__decorate)([rY({type:nh})],nX.prototype,"certificate",void 0),(0,rX.__decorate)([rY({type:nL,context:2,implicit:!0})],nX.prototype,"v2AttrCert",void 0),(0,rX.__decorate)([rY({type:n$,context:3,implicit:!0})],nX.prototype,"other",void 0),nX=(0,rX.__decorate)([rz({type:Q.Choice})],nX);let n0=et=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,et.prototype)}};n0=et=(0,rX.__decorate)([rz({type:Q.Set,itemType:nX})],n0);class n1{contentType="";content=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],n1.prototype,"contentType",void 0),(0,rX.__decorate)([rY({type:D.Any,context:0})],n1.prototype,"content",void 0);let n8=class{single;any;constructor(e={}){Object.assign(this,e)}};(0,rX.__decorate)([rY({type:rC})],n8.prototype,"single",void 0),(0,rX.__decorate)([rY({type:D.Any})],n8.prototype,"any",void 0),n8=(0,rX.__decorate)([rz({type:Q.Choice})],n8);class n4{eContentType="";eContent;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],n4.prototype,"eContentType",void 0),(0,rX.__decorate)([rY({type:n8,context:0,optional:!0})],n4.prototype,"eContent",void 0);let n2=class{value;constructedValue;constructor(e={}){Object.assign(this,e)}};(0,rX.__decorate)([rY({type:rC,context:0,implicit:!0,optional:!0})],n2.prototype,"value",void 0),(0,rX.__decorate)([rY({type:rC,converter:{fromASN:e=>new rC(e.getValue()),toASN:e=>e.toASN()},context:0,implicit:!0,optional:!0,repeated:"sequence"})],n2.prototype,"constructedValue",void 0),n2=(0,rX.__decorate)([rz({type:Q.Choice})],n2);class n6{contentType="";contentEncryptionAlgorithm=new ny;encryptedContent;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],n6.prototype,"contentType",void 0),(0,rX.__decorate)([rY({type:ny})],n6.prototype,"contentEncryptionAlgorithm",void 0),(0,rX.__decorate)([rY({type:n2,optional:!0})],n6.prototype,"encryptedContent",void 0);class n3{keyAttrId="";keyAttr;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],n3.prototype,"keyAttrId",void 0),(0,rX.__decorate)([rY({type:D.Any,optional:!0})],n3.prototype,"keyAttr",void 0);class n5{subjectKeyIdentifier=new nA;date;other;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:nA})],n5.prototype,"subjectKeyIdentifier",void 0),(0,rX.__decorate)([rY({type:D.GeneralizedTime,optional:!0})],n5.prototype,"date",void 0),(0,rX.__decorate)([rY({type:n3,optional:!0})],n5.prototype,"other",void 0);let n9=class{rKeyId;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};(0,rX.__decorate)([rY({type:n5,context:0,implicit:!0,optional:!0})],n9.prototype,"rKeyId",void 0),(0,rX.__decorate)([rY({type:nf,optional:!0})],n9.prototype,"issuerAndSerialNumber",void 0),n9=(0,rX.__decorate)([rz({type:Q.Choice})],n9);class n7{rid=new n9;encryptedKey=new rC;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:n9})],n7.prototype,"rid",void 0),(0,rX.__decorate)([rY({type:rC})],n7.prototype,"encryptedKey",void 0);let ae=er=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,er.prototype)}};ae=er=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:n7})],ae);class aA{algorithm=new na;publicKey=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:na})],aA.prototype,"algorithm",void 0),(0,rX.__decorate)([rY({type:D.BitString})],aA.prototype,"publicKey",void 0);let at=class{subjectKeyIdentifier;originatorKey;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};(0,rX.__decorate)([rY({type:nA,context:0,implicit:!0,optional:!0})],at.prototype,"subjectKeyIdentifier",void 0),(0,rX.__decorate)([rY({type:aA,context:1,implicit:!0,optional:!0})],at.prototype,"originatorKey",void 0),(0,rX.__decorate)([rY({type:nf,optional:!0})],at.prototype,"issuerAndSerialNumber",void 0),at=(0,rX.__decorate)([rz({type:Q.Choice})],at);class ar{version=Y.v3;originator=new at;ukm;keyEncryptionAlgorithm=new nE;recipientEncryptedKeys=new ae;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.Integer})],ar.prototype,"version",void 0),(0,rX.__decorate)([rY({type:at,context:0})],ar.prototype,"originator",void 0),(0,rX.__decorate)([rY({type:rC,context:1,optional:!0})],ar.prototype,"ukm",void 0),(0,rX.__decorate)([rY({type:nE})],ar.prototype,"keyEncryptionAlgorithm",void 0),(0,rX.__decorate)([rY({type:ae})],ar.prototype,"recipientEncryptedKeys",void 0);let ai=class{subjectKeyIdentifier;issuerAndSerialNumber;constructor(e={}){Object.assign(this,e)}};(0,rX.__decorate)([rY({type:nA,context:0,implicit:!0})],ai.prototype,"subjectKeyIdentifier",void 0),(0,rX.__decorate)([rY({type:nf})],ai.prototype,"issuerAndSerialNumber",void 0),ai=(0,rX.__decorate)([rz({type:Q.Choice})],ai);class an{version=Y.v0;rid=new ai;keyEncryptionAlgorithm=new nE;encryptedKey=new rC;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.Integer})],an.prototype,"version",void 0),(0,rX.__decorate)([rY({type:ai})],an.prototype,"rid",void 0),(0,rX.__decorate)([rY({type:nE})],an.prototype,"keyEncryptionAlgorithm",void 0),(0,rX.__decorate)([rY({type:rC})],an.prototype,"encryptedKey",void 0);class aa{keyIdentifier=new rC;date;other;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:rC})],aa.prototype,"keyIdentifier",void 0),(0,rX.__decorate)([rY({type:D.GeneralizedTime,optional:!0})],aa.prototype,"date",void 0),(0,rX.__decorate)([rY({type:n3,optional:!0})],aa.prototype,"other",void 0);class ao{version=Y.v4;kekid=new aa;keyEncryptionAlgorithm=new nE;encryptedKey=new rC;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.Integer})],ao.prototype,"version",void 0),(0,rX.__decorate)([rY({type:aa})],ao.prototype,"kekid",void 0),(0,rX.__decorate)([rY({type:nE})],ao.prototype,"keyEncryptionAlgorithm",void 0),(0,rX.__decorate)([rY({type:rC})],ao.prototype,"encryptedKey",void 0);class as{version=Y.v0;keyDerivationAlgorithm;keyEncryptionAlgorithm=new nE;encryptedKey=new rC;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.Integer})],as.prototype,"version",void 0),(0,rX.__decorate)([rY({type:nQ,context:0,optional:!0})],as.prototype,"keyDerivationAlgorithm",void 0),(0,rX.__decorate)([rY({type:nE})],as.prototype,"keyEncryptionAlgorithm",void 0),(0,rX.__decorate)([rY({type:rC})],as.prototype,"encryptedKey",void 0);class al{oriType="";oriValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],al.prototype,"oriType",void 0),(0,rX.__decorate)([rY({type:D.Any})],al.prototype,"oriValue",void 0);let ad=class{ktri;kari;kekri;pwri;ori;constructor(e={}){Object.assign(this,e)}};(0,rX.__decorate)([rY({type:an,optional:!0})],ad.prototype,"ktri",void 0),(0,rX.__decorate)([rY({type:ar,context:1,implicit:!0,optional:!0})],ad.prototype,"kari",void 0),(0,rX.__decorate)([rY({type:ao,context:2,implicit:!0,optional:!0})],ad.prototype,"kekri",void 0),(0,rX.__decorate)([rY({type:as,context:3,implicit:!0,optional:!0})],ad.prototype,"pwri",void 0),(0,rX.__decorate)([rY({type:al,context:4,implicit:!0,optional:!0})],ad.prototype,"ori",void 0),ad=(0,rX.__decorate)([rz({type:Q.Choice})],ad);let au=ei=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,ei.prototype)}};au=ei=(0,rX.__decorate)([rz({type:Q.Set,itemType:ad})],au);class ac{otherRevInfoFormat="";otherRevInfo=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],ac.prototype,"otherRevInfoFormat",void 0),(0,rX.__decorate)([rY({type:D.Any})],ac.prototype,"otherRevInfo",void 0);let ah=class{other=new ac;constructor(e={}){Object.assign(this,e)}};(0,rX.__decorate)([rY({type:ac,context:1,implicit:!0})],ah.prototype,"other",void 0),ah=(0,rX.__decorate)([rz({type:Q.Choice})],ah);let ag=en=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,en.prototype)}};ag=en=(0,rX.__decorate)([rz({type:Q.Set,itemType:ah})],ag);class ap{certs;crls;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:n0,context:0,implicit:!0,optional:!0})],ap.prototype,"certs",void 0),(0,rX.__decorate)([rY({type:ag,context:1,implicit:!0,optional:!0})],ap.prototype,"crls",void 0);let aC=ea=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,ea.prototype)}};aC=ea=(0,rX.__decorate)([rz({type:Q.Set,itemType:nD})],aC);class af{version=Y.v0;originatorInfo;recipientInfos=new au;encryptedContentInfo=new n6;unprotectedAttrs;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.Integer})],af.prototype,"version",void 0),(0,rX.__decorate)([rY({type:ap,context:0,implicit:!0,optional:!0})],af.prototype,"originatorInfo",void 0),(0,rX.__decorate)([rY({type:au})],af.prototype,"recipientInfos",void 0),(0,rX.__decorate)([rY({type:n6})],af.prototype,"encryptedContentInfo",void 0),(0,rX.__decorate)([rY({type:aC,context:1,implicit:!0,optional:!0})],af.prototype,"unprotectedAttrs",void 0);let aI=eo=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,eo.prototype)}};aI=eo=(0,rX.__decorate)([rz({type:Q.Set,itemType:nw})],aI);class aw{version=Y.v0;digestAlgorithms=new aI;encapContentInfo=new n4;certificates;crls;signerInfos=new nS;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.Integer})],aw.prototype,"version",void 0),(0,rX.__decorate)([rY({type:aI})],aw.prototype,"digestAlgorithms",void 0),(0,rX.__decorate)([rY({type:n4})],aw.prototype,"encapContentInfo",void 0),(0,rX.__decorate)([rY({type:n0,context:0,implicit:!0,optional:!0})],aw.prototype,"certificates",void 0),(0,rX.__decorate)([rY({type:ag,context:1,implicit:!0,optional:!0})],aw.prototype,"crls",void 0),(0,rX.__decorate)([rY({type:nS})],aw.prototype,"signerInfos",void 0);let am="1.2.840.10045.2.1",aE="1.2.840.10045.4.1",ay="1.2.840.10045.4.3.1",aB="1.2.840.10045.4.3.2",aQ="1.2.840.10045.4.3.3",aD="1.2.840.10045.4.3.4",ab="1.2.840.10045.3.1.7",aS="1.3.132.0.34",ak="1.3.132.0.35";function aR(e){return new na({algorithm:e})}let av=aR(aE);aR(ay);let aG=aR(aB),aT=aR(aQ),aM=aR(aD),aN=class{fieldType;parameters;constructor(e={}){Object.assign(this,e)}};(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],aN.prototype,"fieldType",void 0),(0,rX.__decorate)([rY({type:D.Any})],aN.prototype,"parameters",void 0),aN=(0,rX.__decorate)([rz({type:Q.Sequence})],aN);let aO=class{a;b;seed;constructor(e={}){Object.assign(this,e)}};(0,rX.__decorate)([rY({type:D.OctetString})],aO.prototype,"a",void 0),(0,rX.__decorate)([rY({type:D.OctetString})],aO.prototype,"b",void 0),(0,rX.__decorate)([rY({type:D.BitString,optional:!0})],aO.prototype,"seed",void 0),aO=(0,rX.__decorate)([rz({type:Q.Sequence})],aO),(c=es||(es={}))[c.ecpVer1=1]="ecpVer1";let aH=class{version=es.ecpVer1;fieldID;curve;base;order;cofactor;constructor(e={}){Object.assign(this,e)}};(0,rX.__decorate)([rY({type:D.Integer})],aH.prototype,"version",void 0),(0,rX.__decorate)([rY({type:aN})],aH.prototype,"fieldID",void 0),(0,rX.__decorate)([rY({type:aO})],aH.prototype,"curve",void 0),(0,rX.__decorate)([rY({type:class extends rC{}})],aH.prototype,"base",void 0),(0,rX.__decorate)([rY({type:D.Integer,converter:rm})],aH.prototype,"order",void 0),(0,rX.__decorate)([rY({type:D.Integer,optional:!0})],aH.prototype,"cofactor",void 0),aH=(0,rX.__decorate)([rz({type:Q.Sequence})],aH);let aU=class{namedCurve;implicitCurve;specifiedCurve;constructor(e={}){Object.assign(this,e)}};(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],aU.prototype,"namedCurve",void 0),(0,rX.__decorate)([rY({type:D.Null})],aU.prototype,"implicitCurve",void 0),(0,rX.__decorate)([rY({type:aH})],aU.prototype,"specifiedCurve",void 0),aU=(0,rX.__decorate)([rz({type:Q.Choice})],aU);class a_{version=1;privateKey=new rC;parameters;publicKey;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.Integer})],a_.prototype,"version",void 0),(0,rX.__decorate)([rY({type:rC})],a_.prototype,"privateKey",void 0),(0,rX.__decorate)([rY({type:aU,context:0,optional:!0})],a_.prototype,"parameters",void 0),(0,rX.__decorate)([rY({type:D.BitString,context:1,optional:!0})],a_.prototype,"publicKey",void 0);class ax{r=new ArrayBuffer(0);s=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.Integer,converter:rm})],ax.prototype,"r",void 0),(0,rX.__decorate)([rY({type:D.Integer,converter:rm})],ax.prototype,"s",void 0);let aL="1.2.840.113549.1.1",aP=`${aL}.1`,aq=`${aL}.7`,aK=`${aL}.9`,aJ=`${aL}.10`,aF=`${aL}.2`,aj=`${aL}.4`,az=`${aL}.5`,aY=`${aL}.14`,aZ=`${aL}.11`,aV=`${aL}.12`,aW=`${aL}.13`,a$=`${aL}.15`,aX=`${aL}.16`,a0="1.3.14.3.2.26",a1="2.16.840.1.101.3.4.2.4",a8="2.16.840.1.101.3.4.2.1",a4="2.16.840.1.101.3.4.2.2",a2="2.16.840.1.101.3.4.2.3",a6=`${aL}.8`;function a3(e){return new na({algorithm:e,parameters:null})}a3("1.2.840.113549.2.2"),a3("1.2.840.113549.2.5");let a5=a3(a0);a3(a1),a3(a8),a3(a4),a3(a2),a3("2.16.840.1.101.3.4.2.5"),a3("2.16.840.1.101.3.4.2.6");let a9=new na({algorithm:a6,parameters:r$.serialize(a5)}),a7=new na({algorithm:aK,parameters:r$.serialize(rD.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});a3(aP),a3(aF),a3(aj),a3(az),a3(a$),a3(aX),a3(aV),a3(aW),a3(a$),a3(aX);class oe{hashAlgorithm=new na(a5);maskGenAlgorithm=new na({algorithm:a6,parameters:r$.serialize(a5)});pSourceAlgorithm=new na(a7);constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:na,context:0,defaultValue:a5})],oe.prototype,"hashAlgorithm",void 0),(0,rX.__decorate)([rY({type:na,context:1,defaultValue:a9})],oe.prototype,"maskGenAlgorithm",void 0),(0,rX.__decorate)([rY({type:na,context:2,defaultValue:a7})],oe.prototype,"pSourceAlgorithm",void 0),new na({algorithm:aq,parameters:r$.serialize(new oe)});class oA{hashAlgorithm=new na(a5);maskGenAlgorithm=new na({algorithm:a6,parameters:r$.serialize(a5)});saltLength=20;trailerField=1;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:na,context:0,defaultValue:a5})],oA.prototype,"hashAlgorithm",void 0),(0,rX.__decorate)([rY({type:na,context:1,defaultValue:a9})],oA.prototype,"maskGenAlgorithm",void 0),(0,rX.__decorate)([rY({type:D.Integer,context:2,defaultValue:20})],oA.prototype,"saltLength",void 0),(0,rX.__decorate)([rY({type:D.Integer,context:3,defaultValue:1})],oA.prototype,"trailerField",void 0),new na({algorithm:aJ,parameters:r$.serialize(new oA)});class ot{digestAlgorithm=new na;digest=new rC;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:na})],ot.prototype,"digestAlgorithm",void 0),(0,rX.__decorate)([rY({type:rC})],ot.prototype,"digest",void 0);class or{prime=new ArrayBuffer(0);exponent=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.Integer,converter:rm})],or.prototype,"prime",void 0),(0,rX.__decorate)([rY({type:D.Integer,converter:rm})],or.prototype,"exponent",void 0),(0,rX.__decorate)([rY({type:D.Integer,converter:rm})],or.prototype,"coefficient",void 0);let oi=el=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,el.prototype)}};oi=el=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:or})],oi);class on{version=0;modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);privateExponent=new ArrayBuffer(0);prime1=new ArrayBuffer(0);prime2=new ArrayBuffer(0);exponent1=new ArrayBuffer(0);exponent2=new ArrayBuffer(0);coefficient=new ArrayBuffer(0);otherPrimeInfos;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.Integer})],on.prototype,"version",void 0),(0,rX.__decorate)([rY({type:D.Integer,converter:rm})],on.prototype,"modulus",void 0),(0,rX.__decorate)([rY({type:D.Integer,converter:rm})],on.prototype,"publicExponent",void 0),(0,rX.__decorate)([rY({type:D.Integer,converter:rm})],on.prototype,"privateExponent",void 0),(0,rX.__decorate)([rY({type:D.Integer,converter:rm})],on.prototype,"prime1",void 0),(0,rX.__decorate)([rY({type:D.Integer,converter:rm})],on.prototype,"prime2",void 0),(0,rX.__decorate)([rY({type:D.Integer,converter:rm})],on.prototype,"exponent1",void 0),(0,rX.__decorate)([rY({type:D.Integer,converter:rm})],on.prototype,"exponent2",void 0),(0,rX.__decorate)([rY({type:D.Integer,converter:rm})],on.prototype,"coefficient",void 0),(0,rX.__decorate)([rY({type:oi,optional:!0})],on.prototype,"otherPrimeInfos",void 0);class oa{modulus=new ArrayBuffer(0);publicExponent=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.Integer,converter:rm})],oa.prototype,"modulus",void 0),(0,rX.__decorate)([rY({type:D.Integer,converter:rm})],oa.prototype,"publicExponent",void 0),(h=ed||(ed={}))[h.Transient=0]="Transient",h[h.Singleton=1]="Singleton",h[h.ResolutionScoped=2]="ResolutionScoped",h[h.ContainerScoped=3]="ContainerScoped";let oo=ed;var os=function(e,A){return(os=Object.setPrototypeOf||({__proto__:[]})instanceof Array&&function(e,A){e.__proto__=A}||function(e,A){for(var t in A)A.hasOwnProperty(t)&&(e[t]=A[t])})(e,A)};function ol(e,A){function t(){this.constructor=e}os(e,A),e.prototype=null===A?Object.create(A):(t.prototype=A.prototype,new t)}function od(e){var A="function"==typeof Symbol&&Symbol.iterator,t=A&&e[A],r=0;if(t)return t.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(A?"Object is not iterable.":"Symbol.iterator is not defined.")}function ou(e,A){var t="function"==typeof Symbol&&e[Symbol.iterator];if(!t)return e;var r,i,n=t.call(e),a=[];try{for(;(void 0===A||A-- >0)&&!(r=n.next()).done;)a.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return a}function oc(){for(var e=[],A=0;A<arguments.length;A++)e=e.concat(ou(arguments[A]));return e}var oh=function(){function e(e){this.wrap=e,this.reflectMethods=["get","getPrototypeOf","setPrototypeOf","getOwnPropertyDescriptor","defineProperty","has","set","deleteProperty","apply","construct","ownKeys"]}return e.prototype.createProxy=function(e){var A,t=this,r=!1;return new Proxy({},this.createHandler(function(){return r||(A=e(t.wrap()),r=!0),A}))},e.prototype.createHandler=function(e){var A={};return this.reflectMethods.forEach(function(t){A[t]=function(){for(var A=[],r=0;r<arguments.length;r++)A[r]=arguments[r];return A[0]=e(),Reflect[t].apply(void 0,oc(A))}}),A},e}();function og(e){return"string"==typeof e||"symbol"==typeof e}function op(e){return"object"==typeof e&&"token"in e&&"transform"in e}function oC(e){return!!e.useClass}function of(e){return!!e.useFactory}function oI(e){return!!e.useToken}function ow(e){return void 0!=e.useValue}var om=function(){function e(){this._registryMap=new Map}return e.prototype.entries=function(){return this._registryMap.entries()},e.prototype.getAll=function(e){return this.ensure(e),this._registryMap.get(e)},e.prototype.get=function(e){this.ensure(e);var A=this._registryMap.get(e);return A[A.length-1]||null},e.prototype.set=function(e,A){this.ensure(e),this._registryMap.get(e).push(A)},e.prototype.setAll=function(e,A){this._registryMap.set(e,A)},e.prototype.has=function(e){return this.ensure(e),this._registryMap.get(e).length>0},e.prototype.clear=function(){this._registryMap.clear()},e.prototype.ensure=function(e){this._registryMap.has(e)||this._registryMap.set(e,[])},e}(),oE=function(e){function A(){return null!==e&&e.apply(this,arguments)||this}return ol(A,e),A}(om);let oy=function(){this.scopedResolutions=new Map};var oB=function(e){function A(){return null!==e&&e.apply(this,arguments)||this}return ol(A,e),A}(om),oQ=function(e){function A(){return null!==e&&e.apply(this,arguments)||this}return ol(A,e),A}(om);let oD=function(){this.preResolution=new oB,this.postResolution=new oQ};var ob=new Map,oS=new(function(){function e(e){this.parent=e,this._registry=new oE,this.interceptors=new oD,this.disposed=!1,this.disposables=new Set}return e.prototype.register=function(e,A,t){if(void 0===t&&(t={lifecycle:oo.Transient}),this.ensureNotDisposed(),r=oC(A)||ow(A)||oI(A)||of(A)?A:{useClass:A},oI(r))for(var r,i=[e],n=r;null!=n;){var a=n.useToken;if(i.includes(a))throw Error("Token registration cycle detected! "+oc(i,[a]).join(" -> "));i.push(a);var o=this._registry.get(a);n=o&&oI(o.provider)?o.provider:null}if((t.lifecycle===oo.Singleton||t.lifecycle==oo.ContainerScoped||t.lifecycle==oo.ResolutionScoped)&&(ow(r)||of(r)))throw Error('Cannot use lifecycle "'+oo[t.lifecycle]+'" with ValueProviders or FactoryProviders');return this._registry.set(e,{provider:r,options:t}),this},e.prototype.registerType=function(e,A){return(this.ensureNotDisposed(),og(A))?this.register(e,{useToken:A}):this.register(e,{useClass:A})},e.prototype.registerInstance=function(e,A){return this.ensureNotDisposed(),this.register(e,{useValue:A})},e.prototype.registerSingleton=function(e,A){if(this.ensureNotDisposed(),og(e)){if(og(A))return this.register(e,{useToken:A},{lifecycle:oo.Singleton});if(A)return this.register(e,{useClass:A},{lifecycle:oo.Singleton});throw Error('Cannot register a type name as a singleton without a "to" token')}var t=e;return A&&!og(A)&&(t=A),this.register(e,{useClass:t},{lifecycle:oo.Singleton})},e.prototype.resolve=function(e,A,t){void 0===A&&(A=new oy),void 0===t&&(t=!1),this.ensureNotDisposed();var r=this.getRegistration(e);if(!r&&og(e)){if(t)return;throw Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"Single"),r){var i=this.resolveRegistration(r,A);return this.executePostResolutionInterceptor(e,i,"Single"),i}if("function"==typeof e||e instanceof oh){var i=this.construct(e,A);return this.executePostResolutionInterceptor(e,i,"Single"),i}throw Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.")},e.prototype.executePreResolutionInterceptor=function(e,A){var t,r;if(this.interceptors.preResolution.has(e)){var i=[];try{for(var n=od(this.interceptors.preResolution.getAll(e)),a=n.next();!a.done;a=n.next()){var o=a.value;"Once"!=o.options.frequency&&i.push(o),o.callback(e,A)}}catch(e){t={error:e}}finally{try{a&&!a.done&&(r=n.return)&&r.call(n)}finally{if(t)throw t.error}}this.interceptors.preResolution.setAll(e,i)}},e.prototype.executePostResolutionInterceptor=function(e,A,t){var r,i;if(this.interceptors.postResolution.has(e)){var n=[];try{for(var a=od(this.interceptors.postResolution.getAll(e)),o=a.next();!o.done;o=a.next()){var s=o.value;"Once"!=s.options.frequency&&n.push(s),s.callback(e,A,t)}}catch(e){r={error:e}}finally{try{o&&!o.done&&(i=a.return)&&i.call(a)}finally{if(r)throw r.error}}this.interceptors.postResolution.setAll(e,n)}},e.prototype.resolveRegistration=function(e,A){if(this.ensureNotDisposed(),e.options.lifecycle===oo.ResolutionScoped&&A.scopedResolutions.has(e))return A.scopedResolutions.get(e);var t,r=e.options.lifecycle===oo.Singleton,i=e.options.lifecycle===oo.ContainerScoped,n=r||i;return t=ow(e.provider)?e.provider.useValue:oI(e.provider)?n?e.instance||(e.instance=this.resolve(e.provider.useToken,A)):this.resolve(e.provider.useToken,A):oC(e.provider)?n?e.instance||(e.instance=this.construct(e.provider.useClass,A)):this.construct(e.provider.useClass,A):of(e.provider)?e.provider.useFactory(this):this.construct(e.provider,A),e.options.lifecycle===oo.ResolutionScoped&&A.scopedResolutions.set(e,t),t},e.prototype.resolveAll=function(e,A,t){var r=this;void 0===A&&(A=new oy),void 0===t&&(t=!1),this.ensureNotDisposed();var i=this.getAllRegistrations(e);if(!i&&og(e)){if(t)return[];throw Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"All"),i){var n=i.map(function(e){return r.resolveRegistration(e,A)});return this.executePostResolutionInterceptor(e,n,"All"),n}var a=[this.construct(e,A)];return this.executePostResolutionInterceptor(e,a,"All"),a},e.prototype.isRegistered=function(e,A){return void 0===A&&(A=!1),this.ensureNotDisposed(),this._registry.has(e)||A&&(this.parent||!1)&&this.parent.isRegistered(e,!0)},e.prototype.reset=function(){this.ensureNotDisposed(),this._registry.clear(),this.interceptors.preResolution.clear(),this.interceptors.postResolution.clear()},e.prototype.clearInstances=function(){var e,A;this.ensureNotDisposed();try{for(var t=od(this._registry.entries()),r=t.next();!r.done;r=t.next()){var i=ou(r.value,2),n=i[0],a=i[1];this._registry.setAll(n,a.filter(function(e){return!ow(e.provider)}).map(function(e){return e.instance=void 0,e}))}}catch(A){e={error:A}}finally{try{r&&!r.done&&(A=t.return)&&A.call(t)}finally{if(e)throw e.error}}},e.prototype.createChildContainer=function(){this.ensureNotDisposed();var A,t,r=new e(this);try{for(var i=od(this._registry.entries()),n=i.next();!n.done;n=i.next()){var a=ou(n.value,2),o=a[0],s=a[1];s.some(function(e){return e.options.lifecycle===oo.ContainerScoped})&&r._registry.setAll(o,s.map(function(e){return e.options.lifecycle===oo.ContainerScoped?{provider:e.provider,options:e.options}:e}))}}catch(e){A={error:e}}finally{try{n&&!n.done&&(t=i.return)&&t.call(i)}finally{if(A)throw A.error}}return r},e.prototype.beforeResolution=function(e,A,t){void 0===t&&(t={frequency:"Always"}),this.interceptors.preResolution.set(e,{callback:A,options:t})},e.prototype.afterResolution=function(e,A,t){void 0===t&&(t={frequency:"Always"}),this.interceptors.postResolution.set(e,{callback:A,options:t})},e.prototype.dispose=function(){var e,A,t,r;return e=this,A=void 0,t=void 0,r=function(){var e;return function(e,A){var t,r,i,n,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return n={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(n[Symbol.iterator]=function(){return this}),n;function o(n){return function(o){var s=[n,o];if(t)throw TypeError("Generator is already executing.");for(;a;)try{if(t=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return a.label++,{value:s[1],done:!1};case 5:a.label++,r=s[1],s=[0];continue;case 7:s=a.ops.pop(),a.trys.pop();continue;default:if(!(i=(i=a.trys).length>0&&i[i.length-1])&&(6===s[0]||2===s[0])){a=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){a.label=s[1];break}if(6===s[0]&&a.label<i[1]){a.label=i[1],i=s;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(s);break}i[2]&&a.ops.pop(),a.trys.pop();continue}s=A.call(e,a)}catch(e){s=[6,e],r=0}finally{t=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}}}(this,function(A){switch(A.label){case 0:return this.disposed=!0,e=[],this.disposables.forEach(function(A){var t=A.dispose();t&&e.push(t)}),[4,Promise.all(e)];case 1:return A.sent(),[2]}})},new(t||(t=Promise))(function(i,n){function a(e){try{s(r.next(e))}catch(e){n(e)}}function o(e){try{s(r.throw(e))}catch(e){n(e)}}function s(e){var A;e.done?i(e.value):((A=e.value)instanceof t?A:new t(function(e){e(A)})).then(a,o)}s((r=r.apply(e,A||[])).next())})},e.prototype.getRegistration=function(e){return this.isRegistered(e)?this._registry.get(e):this.parent?this.parent.getRegistration(e):null},e.prototype.getAllRegistrations=function(e){return this.isRegistered(e)?this._registry.getAll(e):this.parent?this.parent.getAllRegistrations(e):null},e.prototype.construct=function(e,A){var t=this;if(e instanceof oh)return e.createProxy(function(e){return t.resolve(e,A)});var r=function(){var r=ob.get(e);if(!r||0===r.length)if(0===e.length)return new e;else throw Error('TypeInfo not known for "'+e.name+'"');var i=r.map(t.resolveParams(A,e));return new(e.bind.apply(e,oc([void 0],i)))}();return"function"!=typeof r.dispose||r.dispose.length>0||this.disposables.add(r),r},e.prototype.resolveParams=function(e,A){var t=this;return function(r,i){var n,a,o,s,l,d,u;try{if("object"==typeof r&&"token"in r&&"multiple"in r)if(op(r))return r.multiple?(n=t.resolve(r.transform)).transform.apply(n,oc([t.resolveAll(r.token,new oy,r.isOptional)],r.transformArgs)):(a=t.resolve(r.transform)).transform.apply(a,oc([t.resolve(r.token,e,r.isOptional)],r.transformArgs));else return r.multiple?t.resolveAll(r.token,new oy,r.isOptional):t.resolve(r.token,e,r.isOptional);if(op(r))return(o=t.resolve(r.transform,e)).transform.apply(o,oc([t.resolve(r.token,e)],r.transformArgs));return t.resolve(r,e)}catch(e){throw Error((d="Cannot inject the dependency "+(l=void 0===(s=ou(A.toString().match(/constructor\(([\w, ]+)\)/)||[],2)[1])?null:s,null===l?"at position #"+i:'"'+l.split(",")[i].trim()+'" at position #'+i)+' of "'+A.name+'" constructor. Reason:',void 0===u&&(u=" "),oc([d],e.message.split("\n").map(function(e){return u+e})).join("\n")))}}},e.prototype.ensureNotDisposed=function(){if(this.disposed)throw Error("This container has been disposed, you cannot interact with a disposed container")},e}());let ok=function(e){return function(A){var t,r;ob.set(A,(t=Reflect.getMetadata("design:paramtypes",A)||[],Object.keys(r=Reflect.getOwnMetadata("injectionTokens",A)||{}).forEach(function(e){t[+e]=r[e]}),t)),e&&e.token&&(Array.isArray(e.token)?e.token.forEach(function(e){oS.register(e,A)}):oS.register(e.token,A))}};if("u"<typeof Reflect||!Reflect.getMetadata)throw Error("tsyringe requires a reflect polyfill. Please add 'import \"reflect-metadata\"' to the top of your entry point.");class oR{attrId="";attrValues=[];constructor(e={}){Object.assign(e)}}(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],oR.prototype,"attrId",void 0),(0,rX.__decorate)([rY({type:D.Any,repeated:"set"})],oR.prototype,"attrValues",void 0);let ov=eu=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,eu.prototype)}};ov=eu=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:oR})],ov);let oG=ec=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,ec.prototype)}};oG=ec=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:n1})],oG);class oT{certId="";certValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],oT.prototype,"certId",void 0),(0,rX.__decorate)([rY({type:D.Any,context:0})],oT.prototype,"certValue",void 0);class oM{crlId="";crltValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],oM.prototype,"crlId",void 0),(0,rX.__decorate)([rY({type:D.Any,context:0})],oM.prototype,"crltValue",void 0);class oN extends rC{}class oO{encryptionAlgorithm=new na;encryptedData=new oN;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:na})],oO.prototype,"encryptionAlgorithm",void 0),(0,rX.__decorate)([rY({type:oN})],oO.prototype,"encryptedData",void 0),(g=eg||(eg={}))[g.v1=0]="v1";class oH extends rC{}let oU=eh=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,eh.prototype)}};oU=eh=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:i9})],oU);class o_{version=eg.v1;privateKeyAlgorithm=new na;privateKey=new oH;attributes;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.Integer})],o_.prototype,"version",void 0),(0,rX.__decorate)([rY({type:na})],o_.prototype,"privateKeyAlgorithm",void 0),(0,rX.__decorate)([rY({type:oH})],o_.prototype,"privateKey",void 0),(0,rX.__decorate)([rY({type:oU,implicit:!0,context:0,optional:!0})],o_.prototype,"attributes",void 0);let ox=class extends o_{};ox=(0,rX.__decorate)([rz({type:Q.Sequence})],ox);let oL=class extends oO{};oL=(0,rX.__decorate)([rz({type:Q.Sequence})],oL);class oP{secretTypeId="";secretValue=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],oP.prototype,"secretTypeId",void 0),(0,rX.__decorate)([rY({type:D.Any,context:0})],oP.prototype,"secretValue",void 0);class oq{mac=new ot;macSalt=new rC;iterations=1;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:ot})],oq.prototype,"mac",void 0),(0,rX.__decorate)([rY({type:rC})],oq.prototype,"macSalt",void 0),(0,rX.__decorate)([rY({type:D.Integer,defaultValue:1})],oq.prototype,"iterations",void 0);class oK{version=3;authSafe=new n1;macData=new oq;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.Integer})],oK.prototype,"version",void 0),(0,rX.__decorate)([rY({type:n1})],oK.prototype,"authSafe",void 0),(0,rX.__decorate)([rY({type:oq,optional:!0})],oK.prototype,"macData",void 0);class oJ{bagId="";bagValue=new ArrayBuffer(0);bagAttributes;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],oJ.prototype,"bagId",void 0),(0,rX.__decorate)([rY({type:D.Any,context:0})],oJ.prototype,"bagValue",void 0),(0,rX.__decorate)([rY({type:oR,repeated:"set",optional:!0})],oJ.prototype,"bagAttributes",void 0);let oF=ep=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,ep.prototype)}};oF=ep=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:oJ})],oF);let oj="1.2.840.113549.1.9",oz=`${oj}.7`,oY=`${oj}.14`,oZ=class extends r8{ia5String;constructor(e={}){super(e)}toString(){return({}).toString(),this.ia5String||super.toString()}};(0,rX.__decorate)([rY({type:D.IA5String})],oZ.prototype,"ia5String",void 0),oZ=(0,rX.__decorate)([rz({type:Q.Choice})],oZ);let oV=class extends n1{};oV=(0,rX.__decorate)([rz({type:Q.Sequence})],oV);let oW=class extends oK{};oW=(0,rX.__decorate)([rz({type:Q.Sequence})],oW);let o$=class extends oO{};o$=(0,rX.__decorate)([rz({type:Q.Sequence})],o$);let oX=class{value;constructor(e=""){this.value=e}toString(){return this.value}};(0,rX.__decorate)([rY({type:D.IA5String})],oX.prototype,"value",void 0),oX=(0,rX.__decorate)([rz({type:Q.Choice})],oX);let o0=class extends oZ{};o0=(0,rX.__decorate)([rz({type:Q.Choice})],o0);let o1=class extends r8{};o1=(0,rX.__decorate)([rz({type:Q.Choice})],o1);let o8=class{value;constructor(e=new Date){this.value=e}};(0,rX.__decorate)([rY({type:D.GeneralizedTime})],o8.prototype,"value",void 0),o8=(0,rX.__decorate)([rz({type:Q.Choice})],o8);let o4=class extends r8{};o4=(0,rX.__decorate)([rz({type:Q.Choice})],o4);let o2=class{value;constructor(e="M"){this.value=e}toString(){return this.value}};(0,rX.__decorate)([rY({type:D.PrintableString})],o2.prototype,"value",void 0),o2=(0,rX.__decorate)([rz({type:Q.Choice})],o2);let o6=class{value;constructor(e=""){this.value=e}toString(){return this.value}};(0,rX.__decorate)([rY({type:D.PrintableString})],o6.prototype,"value",void 0),o6=(0,rX.__decorate)([rz({type:Q.Choice})],o6);let o3=class extends o6{};o3=(0,rX.__decorate)([rz({type:Q.Choice})],o3);let o5=class extends r8{};o5=(0,rX.__decorate)([rz({type:Q.Choice})],o5);let o9=class{value;constructor(e=""){this.value=e}toString(){return this.value}};(0,rX.__decorate)([rY({type:D.ObjectIdentifier})],o9.prototype,"value",void 0),o9=(0,rX.__decorate)([rz({type:Q.Choice})],o9);let o7=class extends ns{};o7=(0,rX.__decorate)([rz({type:Q.Choice})],o7);let se=class{value;constructor(e=0){this.value=e}toString(){return this.value.toString()}};(0,rX.__decorate)([rY({type:D.Integer})],se.prototype,"value",void 0),se=(0,rX.__decorate)([rz({type:Q.Choice})],se);let sA=class extends nb{};sA=(0,rX.__decorate)([rz({type:Q.Sequence})],sA);let st=class extends r8{};st=(0,rX.__decorate)([rz({type:Q.Choice})],st);let sr=eC=class extends nu{constructor(e){super(e),Object.setPrototypeOf(this,eC.prototype)}};sr=eC=(0,rX.__decorate)([rz({type:Q.Sequence})],sr);let si=ef=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,ef.prototype)}};si=ef=(0,rX.__decorate)([rz({type:Q.Set,itemType:nD})],si);let sn=class{value;constructor(e=""){this.value=e}toString(){return this.value}};(0,rX.__decorate)([rY({type:D.BmpString})],sn.prototype,"value",void 0),sn=(0,rX.__decorate)([rz({type:Q.Choice})],sn);let sa=class extends na{};sa=(0,rX.__decorate)([rz({type:Q.Sequence})],sa);let so=eI=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,eI.prototype)}};so=eI=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:sa})],so);let ss=ew=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,ew.prototype)}};ss=ew=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:na})],ss);let sl=em=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,em.prototype)}};sl=em=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:D.BitString})],sl),(p=ey||(ey={}))[p.v1=0]="v1",p[p.v2=1]="v2";let sd=class extends na{};sd=(0,rX.__decorate)([rz({type:Q.Sequence})],sd);let su=class{version=ey.v1;privateKeyAlgorithm=new na;privateKey=new ArrayBuffer(0);attributes;publicKey};(0,rX.__decorate)([rY({type:D.Integer})],su.prototype,"version",void 0),(0,rX.__decorate)([rY({type:na})],su.prototype,"privateKeyAlgorithm",void 0),(0,rX.__decorate)([rY({type:D.OctetString})],su.prototype,"privateKey",void 0),(0,rX.__decorate)([rY({type:oU,context:0,implicit:!0,optional:!0})],su.prototype,"attributes",void 0),(0,rX.__decorate)([rY({type:D.BitString,context:1,implicit:!0,optional:!0})],su.prototype,"publicKey",void 0),su=(0,rX.__decorate)([rz({type:Q.Sequence})],su);let sc=class extends su{};sc=(0,rX.__decorate)([rz({type:Q.Sequence})],sc);let sh=eE=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,eE.prototype)}};sh=eE=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:su})],sh);let sg=class extends na{};sg=(0,rX.__decorate)([rz({type:Q.Sequence})],sg);let sp=eB=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,eB.prototype)}};sp=eB=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:no})],sp);let sC=eQ=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,eQ.prototype)}};sC=eQ=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:su})],sC);let sf="2.16.840.1.101.3.4.3",sI=`${sf}.17`,sw=`${sf}.18`,sm=`${sf}.19`,sE=`${sf}.20`,sy=`${sf}.21`,sB=`${sf}.22`,sQ=`${sf}.23`,sD=`${sf}.24`,sb=`${sf}.25`,sS=`${sf}.26`,sk=`${sf}.27`,sR=`${sf}.28`,sv=`${sf}.29`,sG=`${sf}.30`,sT=`${sf}.31`,sM=eD=class extends r0{constructor(e){super(e),Object.setPrototypeOf(this,eD.prototype)}};sM=eD=(0,rX.__decorate)([rz({type:Q.Sequence,itemType:i9})],sM);class sN{version=0;subject=new r5;subjectPKInfo=new no;attributes=new sM;constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:D.Integer})],sN.prototype,"version",void 0),(0,rX.__decorate)([rY({type:r5})],sN.prototype,"subject",void 0),(0,rX.__decorate)([rY({type:no})],sN.prototype,"subjectPKInfo",void 0),(0,rX.__decorate)([rY({type:sM,implicit:!0,context:0,optional:!0})],sN.prototype,"attributes",void 0);class sO{certificationRequestInfo=new sN;certificationRequestInfoRaw;signatureAlgorithm=new na;signature=new ArrayBuffer(0);constructor(e={}){Object.assign(this,e)}}(0,rX.__decorate)([rY({type:sN,raw:!0})],sO.prototype,"certificationRequestInfo",void 0),(0,rX.__decorate)([rY({type:na})],sO.prototype,"signatureAlgorithm",void 0),(0,rX.__decorate)([rY({type:D.BitString})],sO.prototype,"signature",void 0);let sH="crypto.algorithm",sU="crypto.algorithmProvider";oS.registerSingleton(sU,class{getAlgorithms(){return oS.resolveAll(sH)}toAsnAlgorithm(e){let A={...e};for(let e of(A.hash&&"string"==typeof A.hash&&(A.hash={name:A.hash}),this.getAlgorithms())){let t=e.toAsnAlgorithm(A);if(t)return t}if(/^[0-9.]+$/.test(e.name)){let A=new na({algorithm:e.name});return"parameters"in e&&(A.parameters=e.parameters),A}throw Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(e){for(let A of this.getAlgorithms()){let t=A.toWebAlgorithm(e);if(t)return t}return{name:e.algorithm,parameters:e.parameters}}});let s_="1.3.36.3.3.2.8.1.1",sx=`${s_}.1`,sL=`${s_}.2`,sP=`${s_}.3`,sq=`${s_}.4`,sK=`${s_}.5`,sJ=`${s_}.6`,sF=`${s_}.7`,sj=`${s_}.8`,sz=`${s_}.9`,sY=`${s_}.10`,sZ=`${s_}.11`,sV=`${s_}.12`,sW=`${s_}.13`,s$=`${s_}.14`,sX="brainpoolP160r1",s0="brainpoolP160t1",s1="brainpoolP192r1",s8="brainpoolP192t1",s4="brainpoolP224r1",s2="brainpoolP224t1",s6="brainpoolP256r1",s3="brainpoolP256t1",s5="brainpoolP320r1",s9="brainpoolP320t1",s7="brainpoolP384r1",le="brainpoolP384t1",lA="brainpoolP512r1",lt="brainpoolP512t1",lr="ECDSA",li=eb=class{toAsnAlgorithm(e){if(e.name.toLowerCase()===lr.toLowerCase()){if("hash"in e)switch(("string"==typeof e.hash?e.hash:e.hash.name).toLowerCase()){case"sha-1":return av;case"sha-256":return aG;case"sha-384":return aT;case"sha-512":return aM}else if("namedCurve"in e){let A="";switch(e.namedCurve){case"P-256":A=ab;break;case"K-256":A=eb.SECP256K1;break;case"P-384":A=aS;break;case"P-521":A=ak;break;case sX:A=sx;break;case s0:A=sL;break;case s1:A=sP;break;case s8:A=sq;break;case s4:A=sK;break;case s2:A=sJ;break;case s6:A=sF;break;case s3:A=sj;break;case s5:A=sz;break;case s9:A=sY;break;case s7:A=sZ;break;case le:A=sV;break;case lA:A=sW;break;case lt:A=s$}if(A)return new na({algorithm:am,parameters:r$.serialize(new aU({namedCurve:A}))})}}return null}toWebAlgorithm(e){switch(e.algorithm){case aE:return{name:lr,hash:{name:"SHA-1"}};case aB:return{name:lr,hash:{name:"SHA-256"}};case aQ:return{name:lr,hash:{name:"SHA-384"}};case aD:return{name:lr,hash:{name:"SHA-512"}};case am:if(!e.parameters)throw TypeError("Cannot get required parameters from EC algorithm");switch(r$.parse(e.parameters,aU).namedCurve){case ab:return{name:lr,namedCurve:"P-256"};case eb.SECP256K1:return{name:lr,namedCurve:"K-256"};case aS:return{name:lr,namedCurve:"P-384"};case ak:return{name:lr,namedCurve:"P-521"};case sx:return{name:lr,namedCurve:sX};case sL:return{name:lr,namedCurve:s0};case sP:return{name:lr,namedCurve:s1};case sq:return{name:lr,namedCurve:s8};case sK:return{name:lr,namedCurve:s4};case sJ:return{name:lr,namedCurve:s2};case sF:return{name:lr,namedCurve:s6};case sj:return{name:lr,namedCurve:s3};case sz:return{name:lr,namedCurve:s5};case sY:return{name:lr,namedCurve:s9};case sZ:return{name:lr,namedCurve:s7};case sV:return{name:lr,namedCurve:le};case sW:return{name:lr,namedCurve:lA};case s$:return{name:lr,namedCurve:lt}}}return null}};li.SECP256K1="1.3.132.0.10",li=eb=(0,rX.__decorate)([ok()],li),oS.registerSingleton(sH,li);let ln=Symbol("name"),la=Symbol("value");class lo{constructor(e,A={},t=""){for(const r in this[ln]=e,this[la]=t,A)this[r]=A[r]}}lo.NAME=ln,lo.VALUE=la;class ls{static toString(e){let A=this.items[e];return A||e}}ls.items={[a0]:"sha1",[a1]:"sha224",[a8]:"sha256",[a4]:"sha384",[a2]:"sha512",[aP]:"rsaEncryption",[az]:"sha1WithRSAEncryption",[aY]:"sha224WithRSAEncryption",[aZ]:"sha256WithRSAEncryption",[aV]:"sha384WithRSAEncryption",[aW]:"sha512WithRSAEncryption",[am]:"ecPublicKey",[aE]:"ecdsaWithSHA1",[ay]:"ecdsaWithSHA224",[aB]:"ecdsaWithSHA256",[aQ]:"ecdsaWithSHA384",[aD]:"ecdsaWithSHA512",[iq]:"TLS WWW server authentication",[iK]:"TLS WWW client authentication",[iJ]:"Code Signing",[iF]:"E-mail Protection",[ij]:"Time Stamping",[iz]:"OCSP Signing","1.2.840.113549.1.7.2":"Signed Data"};class ll{static serialize(e){return this.serializeObj(e).join("\n")}static pad(e=0){return"".padStart(2*e," ")}static serializeObj(e,A=0){let t=[],r=this.pad(A++),i="",n=e[lo.VALUE];for(let a in n&&(i=` ${n}`),t.push(`${r}${e[lo.NAME]}:${i}`),r=this.pad(A),e){if("symbol"==typeof a)continue;let i=e[a],n=a?`${a}: `:"";if("string"==typeof i||"number"==typeof i||"boolean"==typeof i)t.push(`${r}${n}${i}`);else if(i instanceof Date)t.push(`${r}${n}${i.toUTCString()}`);else if(Array.isArray(i))for(let e of i)e[lo.NAME]=a,t.push(...this.serializeObj(e,A));else if(i instanceof lo)i[lo.NAME]=a,t.push(...this.serializeObj(i,A));else if(eV.isBufferSource(i))a?(t.push(`${r}${n}`),t.push(...this.serializeBufferSource(i,A+1))):t.push(...this.serializeBufferSource(i,A));else if("toTextObject"in i){let e=i.toTextObject();e[lo.NAME]=a,t.push(...this.serializeObj(e,A))}else throw TypeError("Cannot serialize data in text format. Unsupported type.")}return t}static serializeBufferSource(e,A=0){let t=this.pad(A),r=eV.toUint8Array(e),i=[];for(let e=0;e<r.length;){let A=[];for(let t=0;t<16&&e<r.length;t++){8===t&&A.push("");let i=r[e++].toString(16).padStart(2,"0");A.push(i)}i.push(`${t}${A.join(" ")}`)}return i}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}}ll.oidSerializer=ls,ll.algorithmSerializer=class{static toTextObject(e){let A=new lo("Algorithm Identifier",{},ls.toString(e.algorithm));if(e.parameters)if(e.algorithm===am){let t=new li().toWebAlgorithm(e);t&&"namedCurve"in t?A["Named Curve"]=t.namedCurve:A.Parameters=e.parameters}else A.Parameters=e.parameters;return A}};class ld{get parseOptions(){return(0,rX.__classPrivateFieldGet)(this,ek,"f")}get rawData(){return(0,rX.__classPrivateFieldGet)(this,eS,"f")||(0,rX.__classPrivateFieldSet)(this,eS,r$.serialize(this.asn),"f"),(0,rX.__classPrivateFieldGet)(this,eS,"f")}constructor(...e){eS.set(this,void 0),ek.set(this,void 0),eV.isBufferSource(e[0])?((0,rX.__classPrivateFieldSet)(this,ek,e[2],"f"),this.asn=r$.parse(e[0],e[1],e[2]),(0,rX.__classPrivateFieldSet)(this,eS,eV.toArrayBuffer(e[0]),"f")):((0,rX.__classPrivateFieldSet)(this,ek,e[1],"f"),this.asn=e[0]),this.onInit(this.asn)}equal(e){return e instanceof ld&&function(e,A){if(!(e&&A)||e.byteLength!==A.byteLength)return!1;let t=new Uint8Array(e),r=new Uint8Array(A);for(let A=0;A<e.byteLength;A++)if(t[A]!==r[A])return!1;return!0}(e.rawData,this.rawData)}toString(e="text"){switch(e){case"asn":return r$.toString(this.rawData,(0,rX.__classPrivateFieldGet)(this,ek,"f"));case"text":return ll.serialize(this.toTextObject());case"hex":return e4.ToHex(this.rawData);case"base64":return e4.ToBase64(this.rawData);case"base64url":return e4.ToBase64Url(this.rawData);default:throw TypeError("Argument 'format' is unsupported value")}}getTextName(){return this.constructor.NAME}toTextObject(){let e=this.toTextObjectEmpty();return e[""]=this.rawData,e}toTextObjectEmpty(e){return new lo(this.getTextName(),{},e)}}eS=new WeakMap,ek=new WeakMap,ld.NAME="ASN";class lu extends ld{constructor(...e){let A,t;eV.isBufferSource(e[0])?(A=eV.toArrayBuffer(e[0]),t=e[1]):A=r$.serialize(new nd({extnID:e[0],critical:e[1],extnValue:new rC(eV.toArrayBuffer(e[2]))})),super(A,nd,t)}onInit(e){this.type=e.extnID,this.critical=e.critical,this.value=e.extnValue.buffer}toTextObject(){let e=this.toTextObjectWithoutValue();return e[""]=this.value,e}toTextObjectWithoutValue(){let e=this.toTextObjectEmpty(this.critical?"critical":void 0);return e[lo.NAME]===lu.NAME&&(e[lo.NAME]=ls.toString(this.type)),e}}class lc{static isCryptoKeyPair(e){return e&&e.privateKey&&e.publicKey}static isCryptoKey(e){return e&&e.usages&&e.type&&e.algorithm&&void 0!==e.extractable}constructor(){this.items=new Map,this[eR]="CryptoProvider","u">typeof self&&"u">typeof crypto?this.set(lc.DEFAULT,crypto):e.g.crypto&&e.g.crypto.subtle&&this.set(lc.DEFAULT,e.g.crypto)}clear(){this.items.clear()}delete(e){return this.items.delete(e)}forEach(e,A){return this.items.forEach(e,A)}has(e){return this.items.has(e)}get size(){return this.items.size}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}[Symbol.iterator](){return this.items[Symbol.iterator]()}get(e=lc.DEFAULT){let A=this.items.get(e.toLowerCase());if(!A)throw Error(`Cannot get Crypto by name '${e}'`);return A}set(e,A){if("string"==typeof e){if(!A)throw TypeError("Argument 'value' is required");this.items.set(e.toLowerCase(),A)}else this.items.set(lc.DEFAULT,e);return this}}eR=Symbol.toStringTag,lc.DEFAULT="default";let lh=new lc,lg=/^[0-2](?:\.[1-9][0-9]*)+$/;class lp{constructor(e={}){for(const A in this.items={},e)this.register(A,e[A])}get(e){return this.items[e]||null}findId(e){return new RegExp(lg).test(e)?e:this.get(e)}register(e,A){this.items[e]=A,this.items[A]=e}}let lC=new lp;function lf(e,A){return`\\${e4.ToHex(e4.FromUtf8String(A)).toUpperCase()}`}lC.register("CN","2.5.4.3"),lC.register("L","2.5.4.7"),lC.register("ST","2.5.4.8"),lC.register("O","2.5.4.10"),lC.register("OU","2.5.4.11"),lC.register("C","2.5.4.6"),lC.register("DC","0.9.2342.19200300.100.1.25"),lC.register("E","1.2.840.113549.1.9.1"),lC.register("G","2.5.4.42"),lC.register("I","2.5.4.43"),lC.register("SN","2.5.4.4"),lC.register("T","2.5.4.12");class lI{static isASCII(e){for(let A=0;A<e.length;A++)if(e.charCodeAt(A)>255)return!1;return!0}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e,A={}){for(const e in this.extraNames=new lp,this.asn=new r5,A)if(Object.prototype.hasOwnProperty.call(A,e)){const t=A[e];this.extraNames.register(e,t)}"string"==typeof e?this.asn=this.fromString(e):e instanceof r5?this.asn=e:eV.isBufferSource(e)?this.asn=r$.parse(e,r5):this.asn=this.fromJSON(e)}getField(e){let A=this.extraNames.findId(e)||lC.findId(e),t=[];for(let e of this.asn)for(let r of e)r.type===A&&t.push(r.value.toString());return t}getName(e){return this.extraNames.get(e)||lC.get(e)}toString(){return this.asn.map(e=>e.map(e=>{let A=this.getName(e.type)||e.type,t=e.value.anyValue?`#${e4.ToHex(e.value.anyValue)}`:e.value.toString().replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,lf);return`${A}=${t}`}).join("+")).join(", ")}toJSON(){let e=[];for(let A of this.asn){let t={};for(let e of A){let A=this.getName(e.type)||e.type;null!=t[A]||(t[A]=[]),t[A].push(e.value.anyValue?`#${e4.ToHex(e.value.anyValue)}`:e.value.toString())}e.push(t)}return e}fromString(e){let A=new r5,t=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+"\\](?=[,+]|$))|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g,r=null,i=",";for(;r=t.exec(`${e},`);){let[,e,t]=r,n=t[t.length-1];(","===n||"+"===n)&&(t=t.slice(0,t.length-1),r[3]=n);let a=r[3];e=this.getTypeOid(e);let o=this.createAttribute(e,t);"+"===i?A[A.length-1].push(o):A.push(new r6([o])),i=a}return A}fromJSON(e){let A=new r5;for(let t of e){let e=new r6;for(let A in t){let r=this.getTypeOid(A);for(let i of t[A]){let A=this.createAttribute(r,i);e.push(A)}}A.push(e)}return A}getTypeOid(e){if(/[\d.]+/.test(e)||(e=this.getName(e)||""),!e)throw Error(`Cannot get OID for name type '${e}'`);return e}createAttribute(e,A){let t=new r2({type:e});if("object"==typeof A)for(let e in A)switch(e){case"ia5String":t.value.ia5String=A[e];break;case"utf8String":t.value.utf8String=A[e];break;case"universalString":t.value.universalString=A[e];break;case"bmpString":t.value.bmpString=A[e];break;case"printableString":t.value.printableString=A[e]}else if("#"===A[0])t.value.anyValue=e4.FromHex(A.slice(1));else{let r=this.processStringValue(A);e===this.getName("E")||e===this.getName("DC")?t.value.ia5String=r:lI.isPrintableString(r)?t.value.printableString=r:t.value.utf8String=r}return t}processStringValue(e){let A=/"(.*?[^\\])?"/.exec(e);return A&&(e=A[1]),e.replace(/\\0a/gi,"\n").replace(/\\0d/gi,"\r").replace(/\\0g/gi," ").replace(/\\(.)/g,"$1")}toArrayBuffer(){return r$.serialize(this.asn)}async getThumbprint(e,A){let t,r="SHA-1";return e&&("object"==typeof e&&"subtle"in e?t=e:(r=e,t=A)),null!=t||(t=lh.get()),await t.subtle.digest(r,this.toArrayBuffer())}}let lw="Cannot initialize GeneralName from ASN.1 data.",lm=`${lw} Unsupported string format in use.`,lE=`${lw} Value doesn't match to GUID regular expression.`,ly=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,lB="1.3.6.1.4.1.311.25.1",lQ="1.3.6.1.4.1.311.20.2.3",lD="email",lb="guid";class lS extends ld{constructor(...e){let A;if(2===e.length)switch(e[0]){case"dn":{const t=new lI(e[1]).toArrayBuffer(),r=r$.parse(t,r5);A=new ie({directoryName:r});break}case"dns":A=new ie({dNSName:e[1]});break;case lD:A=new ie({rfc822Name:e[1]});break;case lb:{const t=RegExp(ly,"i").exec(e[1]);if(!t)throw Error("Cannot parse GUID value. Value doesn't match to regular expression");const r=t.slice(1).map((e,A)=>A<3?e4.ToHex(new Uint8Array(e4.FromHex(e)).reverse()):e).join("");A=new ie({otherName:new r9({typeId:lB,value:r$.serialize(new rC(e4.FromHex(r)))})});break}case"ip":A=new ie({iPAddress:e[1]});break;case"id":A=new ie({registeredID:e[1]});break;case"upn":A=new ie({otherName:new r9({typeId:lQ,value:r$.serialize(rS.toASN(e[1]))})});break;case"url":A=new ie({uniformResourceIdentifier:e[1]});break;default:throw Error("Cannot create GeneralName. Unsupported type of the name")}else A=eV.isBufferSource(e[0])?r$.parse(e[0],ie):e[0];super(A)}onInit(e){if(void 0!=e.dNSName)this.type="dns",this.value=e.dNSName;else if(void 0!=e.rfc822Name)this.type=lD,this.value=e.rfc822Name;else if(void 0!=e.iPAddress)this.type="ip",this.value=e.iPAddress;else if(void 0!=e.uniformResourceIdentifier)this.type="url",this.value=e.uniformResourceIdentifier;else if(void 0!=e.registeredID)this.type="id",this.value=e.registeredID;else if(void 0!=e.directoryName)this.type="dn",this.value=new lI(e.directoryName).toString();else if(void 0!=e.otherName)if(e.otherName.typeId===lB){this.type=lb;let A=r$.parse(e.otherName.value,rC),t=RegExp(ly,"i").exec(e4.ToHex(A));if(!t)throw Error(lE);this.value=t.slice(1).map((e,A)=>A<3?e4.ToHex(new Uint8Array(e4.FromHex(e)).reverse()):e).join("-")}else if(e.otherName.typeId===lQ)this.type="upn",this.value=r$.parse(e.otherName.value,r8).toString();else throw Error(lm);else throw Error(lm)}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let e;switch(this.type){case"dn":case"dns":case lb:case"ip":case"id":case"upn":case"url":e=this.type.toUpperCase();break;case lD:e="Email";break;default:throw Error("Unsupported GeneralName type")}let A=this.value;return"id"===this.type&&(A=ls.toString(A)),new lo(e,void 0,A)}}class lk extends ld{constructor(e){let A;if(e instanceof im)A=e;else if(Array.isArray(e)){const t=[];for(const A of e)if(A instanceof ie)t.push(A);else{const e=r$.parse(new lS(A.type,A.value).rawData,ie);t.push(e)}A=new im(t)}else if(eV.isBufferSource(e))A=r$.parse(e,im);else throw Error("Cannot initialize GeneralNames. Incorrect incoming arguments");super(A)}onInit(e){let A=[];for(let t of e){let e=null;try{e=new lS(t)}catch{continue}A.push(e)}this.items=A}toJSON(){return this.items.map(e=>e.toJSON())}toTextObject(){let e=super.toTextObjectEmpty();for(let A of this.items){let t=A.toTextObject(),r=e[t[lo.NAME]];Array.isArray(r)||(r=[],e[t[lo.NAME]]=r),r.push(t)}return e}}lk.NAME="GeneralNames";let lR="-{5}",lv=`${lR}BEGIN ([^\\n]+(?=${lR}))${lR}`,lG=`${lR}END \\1${lR}`,lT=`${lv}\\n(?:((?:[^:\\n]+: (?:[^\\n]+\\n(?: +[^\\n]+\\n)*))+))?\\n?((?:[a-zA-Z0-9=+/]+\\n)+)${lG}`,lM=RegExp("[\\n]+","g");class lN{static isPem(e){return"string"==typeof e&&RegExp(lT,"g").test(e.replace(/\r/g,""))}static decodeWithHeaders(e){e=e.replace(/\r/g,"");let A=RegExp(lT,"g"),t=[],r=null;for(;r=A.exec(e);){let e=r[3].replace(lM,""),A={type:r[1],headers:[],rawData:e4.FromBase64(e)},i=r[2];if(i){let e=i.split(RegExp("\\n","g")),t=null;for(let r of e){let[e,i]=r.split(/:(.*)/);if(void 0===i){if(!t)throw Error("Cannot parse PEM string. Incorrect header value");t.value+=e.trim()}else t&&A.headers.push(t),t={key:e,value:i.trim()}}t&&A.headers.push(t)}t.push(A)}return t}static decode(e){return this.decodeWithHeaders(e).map(e=>e.rawData)}static decodeFirst(e){let A=this.decode(e);if(!A.length)throw RangeError("PEM string doesn't contain any objects");return A[0]}static encode(e,A){if(Array.isArray(e)){let t=[];return A?e.forEach(e=>{if(!eV.isBufferSource(e))throw TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");t.push(this.encodeStruct({type:A,rawData:eV.toArrayBuffer(e)}))}):e.forEach(e=>{if(!("type"in e))throw TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");t.push(this.encodeStruct(e))}),t.join("\n")}if(!A)throw Error("Required argument 'tag' is missed");return this.encodeStruct({type:A,rawData:eV.toArrayBuffer(e)})}static encodeStruct(e){var A;let t=e.type.toLocaleUpperCase(),r=[];if(r.push(`-----BEGIN ${t}-----`),null==(A=e.headers)?void 0:A.length){for(let A of e.headers)r.push(`${A.key}: ${A.value}`);r.push("")}let i=e4.ToBase64(e.rawData);for(let e=0;e<i.length;e+=64)r.push(i.substring(e,e+64));return r.push(`-----END ${t}-----`),r.join("\n")}}lN.CertificateTag="CERTIFICATE",lN.CrlTag="CRL",lN.CertificateRequestTag="CERTIFICATE REQUEST",lN.PublicKeyTag="PUBLIC KEY",lN.PrivateKeyTag="PRIVATE KEY";class lO extends ld{static isAsnEncoded(e){return eV.isBufferSource(e)||"string"==typeof e}static toArrayBuffer(e){if("string"==typeof e)if(lN.isPem(e))return lN.decode(e)[0];else if(e4.isHex(e))return e4.FromHex(e);else if(e4.isBase64(e))return e4.FromBase64(e);else if(e4.isBase64Url(e))return e4.FromBase64Url(e);else throw TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url");{let A=eV.toUint8Array(e);if(A.length>0&&48===A[0])return eV.toArrayBuffer(e);let t=e4.ToBinary(e);if(lN.isPem(t))return lN.decode(t)[0];if(e4.isHex(t))return e4.FromHex(t);if(e4.isBase64(t))return e4.FromBase64(t);else if(e4.isBase64Url(t))return e4.FromBase64Url(t);throw TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}}constructor(...e){lO.isAsnEncoded(e[0])?super(lO.toArrayBuffer(e[0]),e[1],e[2]):super(e[0],e[1])}toString(e="pem"){return"pem"===e?lN.encode(this.rawData,this.tag):super.toString(e)}}class lH extends lO{static async create(e,A=lh.get()){if(e instanceof lH)return e;if(lc.isCryptoKey(e)){if("public"!==e.type)throw TypeError("Public key is required");return new lH(await A.subtle.exportKey("spki",e))}if(e.publicKey)return e.publicKey;if(eV.isBufferSource(e))return new lH(e);throw TypeError("Unsupported PublicKeyType")}constructor(e,A){lO.isAsnEncoded(e)?super(e,no,A):super(e,A),this.tag=lN.PublicKeyTag}async export(e,A,t){var r;let i,n=["verify"],a={hash:"SHA-256",...this.algorithm};A?(a=e,n=A,i=t):i=e,null!=i||(i=lh.get());let o=this.rawData,s=r$.parse(this.rawData,no,this.parseOptions);return s.algorithm.algorithm===aJ&&(r=s,r.algorithm=new na({algorithm:aP,parameters:null}),o=r$.serialize(r)),i.subtle.importKey("spki",o,a,!0,n)}onInit(e){let A=oS.resolve(sU),t=this.algorithm=A.toWebAlgorithm(e.algorithm);if(e.algorithm.algorithm===aP){let A=r$.parse(e.subjectPublicKey,oa,this.parseOptions),r=eV.toUint8Array(A.modulus);t.publicExponent=eV.toUint8Array(A.publicExponent),t.modulusLength=(!r[0]?r.slice(1):r).byteLength<<3}}async getThumbprint(e,A){let t,r="SHA-1";return e&&("object"==typeof e&&"subtle"in e?t=e:(r=e,t=A)),null!=t||(t=lh.get()),await t.subtle.digest(r,this.rawData)}async getKeyIdentifier(e,A){let t,r="SHA-1";e&&("object"==typeof e&&"subtle"in e?t=e:(r=e,t=A)),null!=t||(t=lh.get());let i=r$.parse(this.rawData,no,this.parseOptions);return await t.subtle.digest(r,i.subjectPublicKey)}toTextObject(){let e=this.toTextObjectEmpty(),A=r$.parse(this.rawData,no,this.parseOptions);return e.Algorithm=ll.serializeAlgorithm(A.algorithm),A.algorithm.algorithm===am?e["EC Point"]=A.subjectPublicKey:e["Raw Data"]=A.subjectPublicKey,e}}class lU extends lu{static async create(e,A=!1,t=lh.get()){if("name"in e&&"serialNumber"in e)return new lU(e,A);let r=await lH.create(e,t),i=await r.getKeyIdentifier(t);return new lU(e4.ToHex(i),A)}constructor(...e){if(eV.isBufferSource(e[0]))super(e[0],e[1]);else if("string"==typeof e[0]){const A=new iC({keyIdentifier:new ip(e4.FromHex(e[0]))});super(ig,e[1],r$.serialize(A))}else{const A=e[0],t=new iC({authorityCertIssuer:A.name instanceof lk?r$.parse(A.name.rawData,im):A.name,authorityCertSerialNumber:e4.FromHex(A.serialNumber)});super(ig,e[1],r$.serialize(t))}}onInit(e){super.onInit(e);let A=r$.parse(e.extnValue,iC,this.parseOptions);A.keyIdentifier&&(this.keyId=e4.ToHex(A.keyIdentifier)),(A.authorityCertIssuer||A.authorityCertSerialNumber)&&(this.certId={name:A.authorityCertIssuer||[],serialNumber:A.authorityCertSerialNumber?e4.ToHex(A.authorityCertSerialNumber):""})}toTextObject(){let e=this.toTextObjectWithoutValue(),A=r$.parse(this.value,iC,this.parseOptions);return A.authorityCertIssuer&&(e["Authority Issuer"]=new lk(A.authorityCertIssuer).toTextObject()),A.authorityCertSerialNumber&&(e["Authority Serial Number"]=A.authorityCertSerialNumber),A.keyIdentifier&&(e[""]=A.keyIdentifier),e}}lU.NAME="Authority Key Identifier";class l_ extends lu{constructor(...e){if(eV.isBufferSource(e[0])){super(e[0],e[1]);const A=r$.parse(this.value,iw,this.parseOptions);this.ca=A.cA,this.pathLength=A.pathLenConstraint}else{const A=new iw({cA:e[0],pathLenConstraint:e[1]});super(iI,e[2],r$.serialize(A)),this.ca=e[0],this.pathLength=e[1]}}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ca&&(e.CA=this.ca),void 0!==this.pathLength&&(e["Path Length"]=this.pathLength),e}}l_.NAME="Basic Constraints",(C=ev||(ev={})).serverAuth="1.3.6.1.5.5.7.3.1",C.clientAuth="1.3.6.1.5.5.7.3.2",C.codeSigning="1.3.6.1.5.5.7.3.3",C.emailProtection="1.3.6.1.5.5.7.3.4",C.timeStamping="1.3.6.1.5.5.7.3.8",C.ocspSigning="1.3.6.1.5.5.7.3.9";class lx extends lu{constructor(...e){if(eV.isBufferSource(e[0])){super(e[0],e[1]);const A=r$.parse(this.value,iP,this.parseOptions);this.usages=A.map(e=>e)}else{const A=new iP(e[0]);super(iL,e[1],r$.serialize(A)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[""]=this.usages.map(e=>ls.toString(e)).join(", "),e}}lx.NAME="Extended Key Usages",(f=eG||(eG={}))[f.digitalSignature=1]="digitalSignature",f[f.nonRepudiation=2]="nonRepudiation",f[f.keyEncipherment=4]="keyEncipherment",f[f.dataEncipherment=8]="dataEncipherment",f[f.keyAgreement=16]="keyAgreement",f[f.keyCertSign=32]="keyCertSign",f[f.cRLSign=64]="cRLSign",f[f.encipherOnly=128]="encipherOnly",f[f.decipherOnly=256]="decipherOnly";class lL extends lu{constructor(...e){if(eV.isBufferSource(e[0])){super(e[0],e[1]);const A=r$.parse(this.value,iX,this.parseOptions);this.usages=A.toNumber()}else{const A=new iX(e[0]);super(i$,e[1],r$.serialize(A)),this.usages=e[0]}}toTextObject(){let e=this.toTextObjectWithoutValue(),A=r$.parse(this.value,iX,this.parseOptions);return e[""]=A.toJSON().join(", "),e}}lL.NAME="Key Usages";class lP extends lu{static async create(e,A=!1,t=lh.get()){let r=await lH.create(e,t),i=await r.getKeyIdentifier(t);return new lP(e4.ToHex(i),A)}constructor(...e){if(eV.isBufferSource(e[0])){super(e[0],e[1]);const A=r$.parse(this.value,nA,this.parseOptions);this.keyId=e4.ToHex(A)}else{const A="string"==typeof e[0]?e4.FromHex(e[0]):e[0],t=new nA(A);super(ne,e[1],r$.serialize(t)),this.keyId=e4.ToHex(A)}}toTextObject(){let e=this.toTextObjectWithoutValue(),A=r$.parse(this.value,nA,this.parseOptions);return e[""]=A,e}}lP.NAME="Subject Key Identifier";class lq extends lu{constructor(...e){eV.isBufferSource(e[0])?super(e[0],e[1]):super(i3,e[1],new lk(e[0]||[]).rawData)}onInit(e){super.onInit(e);let A=r$.parse(e.extnValue,i5,this.parseOptions);this.names=new lk(A)}toTextObject(){let e=this.toTextObjectWithoutValue(),A=this.names.toTextObject();for(let t in A)e[t]=A[t];return e}}lq.NAME="Subject Alternative Name";class lK{static register(e,A){this.items.set(e,A)}static create(e,A){let t=new lu(e,A),r=this.items.get(t.type);return r?new r(e,A):t}}lK.items=new Map;class lJ extends lu{constructor(...e){var A;if(eV.isBufferSource(e[0])){super(e[0],e[1]);const A=r$.parse(this.value,iR,this.parseOptions);this.policies=A.map(e=>e.policyIdentifier)}else{const t=e[0],r=null!=(A=e[1])&&A,i=new iR(t.map(e=>new ik({policyIdentifier:e})));super(iy,r,r$.serialize(i)),this.policies=t}}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map(e=>new lo("",{},ls.toString(e))),e}}lJ.NAME="Certificate Policies",lK.register(iy,lJ);class lF extends lu{constructor(...e){if(eV.isBufferSource(e[0]))super(e[0],e[1]);else if(Array.isArray(e[0])&&"string"==typeof e[0][0]){const A=e[0].map(e=>new iO({distributionPoint:new iN({fullName:[new ie({uniformResourceIdentifier:e})]})})),t=new iH(A);super(iT,e[1],r$.serialize(t))}else{const A=new iH(e[0]);super(iT,e[1],r$.serialize(A))}null!=this.distributionPoints||(this.distributionPoints=[])}onInit(e){super.onInit(e);let A=r$.parse(e.extnValue,iH,this.parseOptions);this.distributionPoints=A}toTextObject(){let e=this.toTextObjectWithoutValue();return e["Distribution Point"]=this.distributionPoints.map(e=>{var A;let t=new lo("");return(null==(A=e.distributionPoint)?void 0:A.fullName)&&(t[""]=e.distributionPoint.fullName.map(e=>new lS(e).toString()).join(", ")),e.reasons&&(t.Reasons=e.reasons.toString()),e.cRLIssuer&&(t["CRL Issuer"]=e.cRLIssuer.map(e=>e.toString()).join(", ")),t}),e}}lF.NAME="CRL Distribution Points";class lj extends lu{constructor(...e){if(eV.isBufferSource(e[0]))super(e[0],e[1]);else if(e[0]instanceof ih){const A=new ih(e[0]);super(iu,e[1],r$.serialize(A))}else{const A=e[0],t=new ih;lY(t,A,ia,"ocsp"),lY(t,A,io,"caIssuers"),lY(t,A,is,"timeStamping"),lY(t,A,il,"caRepository"),super(iu,e[1],r$.serialize(t))}null!=this.ocsp||(this.ocsp=[]),null!=this.caIssuers||(this.caIssuers=[]),null!=this.timeStamping||(this.timeStamping=[]),null!=this.caRepository||(this.caRepository=[])}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],r$.parse(e.extnValue,ih,this.parseOptions).forEach(e=>{switch(e.accessMethod){case ia:this.ocsp.push(new lS(e.accessLocation));break;case io:this.caIssuers.push(new lS(e.accessLocation));break;case is:this.timeStamping.push(new lS(e.accessLocation));break;case il:this.caRepository.push(new lS(e.accessLocation))}})}toTextObject(){let e=this.toTextObjectWithoutValue();return this.ocsp.length&&lz(e,"OCSP",this.ocsp),this.caIssuers.length&&lz(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&lz(e,"Time Stamping",this.timeStamping),this.caRepository.length&&lz(e,"CA Repository",this.caRepository),e}}function lz(e,A,t){if(1===t.length)e[A]=t[0].toTextObject();else{let r=new lo("");t.forEach((e,A)=>{let t=e.toTextObject(),i=`${t[lo.NAME]} ${A+1}`,n=r[i];Array.isArray(n)||(n=[],r[i]=n),n.push(t)}),e[A]=r}}function lY(e,A,t,r){let i=A[r];i&&(Array.isArray(i)?i:[i]).forEach(A=>{"string"==typeof A&&(A=new lS("url",A)),e.push(new ic({accessMethod:t,accessLocation:r$.parse(A.rawData,ie)}))})}lj.NAME="Authority Info Access";class lZ extends lu{constructor(...e){eV.isBufferSource(e[0])?super(e[0],e[1]):super(iV,e[1],new lk(e[0]||[]).rawData)}onInit(e){super.onInit(e);let A=r$.parse(e.extnValue,im,this.parseOptions);this.names=new lk(A)}toTextObject(){let e=this.toTextObjectWithoutValue(),A=this.names.toTextObject();for(let t in A)e[t]=A[t];return e}}lZ.NAME="Issuer Alternative Name";class lV extends ld{constructor(...e){let A,t;if(eV.isBufferSource(e[0]))A=eV.toArrayBuffer(e[0]),t=e[1];else{const t=e[0],r=Array.isArray(e[1])?e[1].map(e=>eV.toArrayBuffer(e)):[];A=r$.serialize(new i9({type:t,values:r}))}super(A,i9,t)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){let e=this.toTextObjectWithoutValue();return e.Value=this.values.map(e=>new lo("",{"":e})),e}toTextObjectWithoutValue(){let e=this.toTextObjectEmpty();return e[lo.NAME]===lV.NAME&&(e[lo.NAME]=ls.toString(this.type)),e}}lV.NAME="Attribute";class lW extends lV{constructor(...e){if(eV.isBufferSource(e[0]))super(e[0],e[1]);else{const A=new st({printableString:e[0]});super(oz,[r$.serialize(A)])}null!=this.password||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){let e=r$.parse(this.values[0],st,this.parseOptions);this.password=e.toString()}}toTextObject(){let e=this.toTextObjectWithoutValue();return e[lo.VALUE]=this.password,e}}lW.NAME="Challenge Password";class l$ extends lV{constructor(...e){if(eV.isBufferSource(e[0]))super(e[0],e[1]);else{const A=e[0],t=new nu;for(const e of A)t.push(r$.parse(e.rawData,nd));super(oY,[r$.serialize(t)])}null!=this.items||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){let e=r$.parse(this.values[0],nu,this.parseOptions);this.items=e.map(e=>lK.create(r$.serialize(e),this.parseOptions))}}toTextObject(){let e=this.toTextObjectWithoutValue();for(let A of this.items.map(e=>e.toTextObject()))e[A[lo.NAME]]=A;return e}}l$.NAME="Extensions";class lX{static register(e,A){this.items.set(e,A)}static create(e,A){let t=new lV(e,A),r=this.items.get(t.type);return r?new r(e,A):t}}lX.items=new Map;let l0="crypto.signatureFormatter",l1=eT=class{static createPssParams(e,A){let t=eT.getHashAlgorithm(e);return t?new oA({hashAlgorithm:t,maskGenAlgorithm:new na({algorithm:a6,parameters:r$.serialize(t)}),saltLength:A}):null}static getHashAlgorithm(e){let A=oS.resolve(sU);return"string"==typeof e?A.toAsnAlgorithm({name:e}):"object"==typeof e&&e&&"name"in e?A.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"rsassa-pkcs1-v1_5":if(!("hash"in e))return new na({algorithm:aP,parameters:null});{let A;if("string"==typeof e.hash)A=e.hash;else if(e.hash&&"object"==typeof e.hash&&"name"in e.hash&&"string"==typeof e.hash.name)A=e.hash.name.toUpperCase();else throw Error("Cannot get hash algorithm name");switch(A.toLowerCase()){case"sha-1":return new na({algorithm:az,parameters:null});case"sha-256":return new na({algorithm:aZ,parameters:null});case"sha-384":return new na({algorithm:aV,parameters:null});case"sha-512":return new na({algorithm:aW,parameters:null})}}break;case"rsa-pss":if(!("hash"in e))return new na({algorithm:aJ,parameters:null});{if(!("saltLength"in e&&"number"==typeof e.saltLength))throw Error("Cannot get 'saltLength' from 'alg' argument");let A=eT.createPssParams(e.hash,e.saltLength);if(!A)throw Error("Cannot create PSS parameters");return new na({algorithm:aJ,parameters:r$.serialize(A)})}}return null}toWebAlgorithm(e){switch(e.algorithm){case aP:return{name:"RSASSA-PKCS1-v1_5"};case az:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case aZ:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case aV:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case aW:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case aJ:if(!e.parameters)return{name:"RSA-PSS"};{let A=r$.parse(e.parameters,oA);return{name:"RSA-PSS",hash:oS.resolve(sU).toWebAlgorithm(A.hashAlgorithm),saltLength:A.saltLength}}}return null}};l1=eT=(0,rX.__decorate)([ok()],l1),oS.registerSingleton(sH,l1);let l8=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new na({algorithm:a0});case"sha-256":return new na({algorithm:a8});case"sha-384":return new na({algorithm:a4});case"sha-512":return new na({algorithm:a2})}return null}toWebAlgorithm(e){switch(e.algorithm){case a0:return{name:"SHA-1"};case a8:return{name:"SHA-256"};case a4:return{name:"SHA-384"};case a2:return{name:"SHA-512"}}return null}};l8=(0,rX.__decorate)([ok()],l8),oS.registerSingleton(sH,l8);class l4{addPadding(e,A){let t=eV.toUint8Array(A),r=new Uint8Array(e);return r.set(t,e-t.length),r.buffer}removePadding(e,A=!1){let t=eV.toUint8Array(e);for(let e=0;e<t.length;e++)if(t[e]){t=t.slice(e);break}if(A&&t[0]>127){let e=new Uint8Array(t.length+1);return e.set(t,1),e.buffer}return t.buffer}toAsnSignature(e,A){if("ECDSA"===e.name){let t=e.namedCurve,r=l4.namedCurveSize.get(t)||l4.defaultNamedCurveSize,i=new ax,n=eV.toUint8Array(A);return i.r=this.removePadding(n.slice(0,r),!0),i.s=this.removePadding(n.slice(r,r+r),!0),r$.serialize(i)}return null}toWebSignature(e,A){if("ECDSA"===e.name){let t=r$.parse(A,ax),r=e.namedCurve,i=l4.namedCurveSize.get(r)||l4.defaultNamedCurveSize;return function(...e){let A=new Uint8Array(e.map(e=>e.byteLength).reduce((e,A)=>e+A)),t=0;return e.map(e=>new Uint8Array(e)).forEach(e=>{for(let r of e)A[t++]=r}),A.buffer}(this.addPadding(i,this.removePadding(t.r)),this.addPadding(i,this.removePadding(t.s)))}return null}}l4.namedCurveSize=new Map,l4.defaultNamedCurveSize=32;let l2="1.3.101.110",l6="1.3.101.111",l3="1.3.101.112",l5="1.3.101.113",l9=class{toAsnAlgorithm(e){let A=null;switch(e.name.toLowerCase()){case"ed25519":A=l3;break;case"x25519":A=l2;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":A=l3;break;case"ed448":A=l5}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":A=l2;break;case"x448":A=l6}}return A?new na({algorithm:A}):null}toWebAlgorithm(e){switch(e.algorithm){case l3:return{name:"Ed25519"};case l5:return{name:"EdDSA",namedCurve:"Ed448"};case l2:return{name:"X25519"};case l6:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};l9=(0,rX.__decorate)([ok()],l9),oS.registerSingleton(sH,l9);let l7=class{toAsnAlgorithm(e){let A=null;switch(e.name.toLowerCase()){case"ml-dsa-44":A=sI;break;case"ml-dsa-65":A=sw;break;case"ml-dsa-87":A=sm}return A?new na({algorithm:A}):null}toWebAlgorithm(e){switch(e.algorithm){case sI:return{name:"ML-DSA-44"};case sw:return{name:"ML-DSA-65"};case sm:return{name:"ML-DSA-87"}}return null}};l7=(0,rX.__decorate)([ok()],l7),oS.registerSingleton(sH,l7);let de=class{toAsnAlgorithm(e){let A=null;switch(e.name.toLowerCase()){case"slh-dsa-sha2-128s":A=sE;break;case"slh-dsa-sha2-128f":A=sy;break;case"slh-dsa-sha2-192s":A=sB;break;case"slh-dsa-sha2-192f":A=sQ;break;case"slh-dsa-sha2-256s":A=sD;break;case"slh-dsa-sha2-256f":A=sb;break;case"slh-dsa-shake-128s":A=sS;break;case"slh-dsa-shake-128f":A=sk;break;case"slh-dsa-shake-192s":A=sR;break;case"slh-dsa-shake-192f":A=sv;break;case"slh-dsa-shake-256s":A=sG;break;case"slh-dsa-shake-256f":A=sT}return A?new na({algorithm:A}):null}toWebAlgorithm(e){switch(e.algorithm){case sE:return{name:"SLH-DSA-SHA2-128s"};case sy:return{name:"SLH-DSA-SHA2-128f"};case sB:return{name:"SLH-DSA-SHA2-192s"};case sQ:return{name:"SLH-DSA-SHA2-192f"};case sD:return{name:"SLH-DSA-SHA2-256s"};case sb:return{name:"SLH-DSA-SHA2-256f"};case sS:return{name:"SLH-DSA-SHAKE-128s"};case sk:return{name:"SLH-DSA-SHAKE-128f"};case sR:return{name:"SLH-DSA-SHAKE-192s"};case sv:return{name:"SLH-DSA-SHAKE-192f"};case sG:return{name:"SLH-DSA-SHAKE-256s"};case sT:return{name:"SLH-DSA-SHAKE-256f"}}return null}};de=(0,rX.__decorate)([ok()],de),oS.registerSingleton(sH,de),new WeakMap,new WeakMap,new WeakMap,new WeakMap,new WeakMap,new WeakMap,new WeakMap,new WeakMap;class dA extends lO{get publicKey(){return(0,rX.__classPrivateFieldGet)(this,eJ,"f")||(0,rX.__classPrivateFieldSet)(this,eJ,new lH(this.asn.tbsCertificate.subjectPublicKeyInfo,this.parseOptions),"f"),(0,rX.__classPrivateFieldGet)(this,eJ,"f")}get serialNumber(){var e;let A;return(0,rX.__classPrivateFieldGet)(this,eN,"f")||(0,rX.__classPrivateFieldSet)(this,eN,(e=this.asn.tbsCertificate.serialNumber,(A=eV.toUint8Array(e)).length>1&&0===A[0]&&A[1]>127&&(A=A.slice(1)),e4.ToHex(A)),"f"),(0,rX.__classPrivateFieldGet)(this,eN,"f")}get subjectName(){return(0,rX.__classPrivateFieldGet)(this,eO,"f")||(0,rX.__classPrivateFieldSet)(this,eO,new lI(this.asn.tbsCertificate.subject),"f"),(0,rX.__classPrivateFieldGet)(this,eO,"f")}get subject(){return(0,rX.__classPrivateFieldGet)(this,eH,"f")||(0,rX.__classPrivateFieldSet)(this,eH,this.subjectName.toString(),"f"),(0,rX.__classPrivateFieldGet)(this,eH,"f")}get issuerName(){return(0,rX.__classPrivateFieldGet)(this,eU,"f")||(0,rX.__classPrivateFieldSet)(this,eU,new lI(this.asn.tbsCertificate.issuer),"f"),(0,rX.__classPrivateFieldGet)(this,eU,"f")}get issuer(){return(0,rX.__classPrivateFieldGet)(this,e_,"f")||(0,rX.__classPrivateFieldSet)(this,e_,this.issuerName.toString(),"f"),(0,rX.__classPrivateFieldGet)(this,e_,"f")}get notBefore(){if(!(0,rX.__classPrivateFieldGet)(this,ex,"f")){let e=this.asn.tbsCertificate.validity.notBefore.utcTime||this.asn.tbsCertificate.validity.notBefore.generalTime;if(!e)throw Error("Cannot get 'notBefore' value");(0,rX.__classPrivateFieldSet)(this,ex,e,"f")}return(0,rX.__classPrivateFieldGet)(this,ex,"f")}get notAfter(){if(!(0,rX.__classPrivateFieldGet)(this,eL,"f")){let e=this.asn.tbsCertificate.validity.notAfter.utcTime||this.asn.tbsCertificate.validity.notAfter.generalTime;if(!e)throw Error("Cannot get 'notAfter' value");(0,rX.__classPrivateFieldSet)(this,eL,e,"f")}return(0,rX.__classPrivateFieldGet)(this,eL,"f")}get signatureAlgorithm(){if(!(0,rX.__classPrivateFieldGet)(this,eP,"f")){let e=oS.resolve(sU);(0,rX.__classPrivateFieldSet)(this,eP,e.toWebAlgorithm(this.asn.signatureAlgorithm),"f")}return(0,rX.__classPrivateFieldGet)(this,eP,"f")}get signature(){return(0,rX.__classPrivateFieldGet)(this,eq,"f")||(0,rX.__classPrivateFieldSet)(this,eq,this.asn.signatureValue,"f"),(0,rX.__classPrivateFieldGet)(this,eq,"f")}get extensions(){return!(0,rX.__classPrivateFieldGet)(this,eK,"f")&&((0,rX.__classPrivateFieldSet)(this,eK,[],"f"),this.asn.tbsCertificate.extensions&&(0,rX.__classPrivateFieldSet)(this,eK,this.asn.tbsCertificate.extensions.map(e=>lK.create(r$.serialize(e),this.parseOptions)),"f")),(0,rX.__classPrivateFieldGet)(this,eK,"f")}get tbs(){return(0,rX.__classPrivateFieldGet)(this,eM,"f")||(0,rX.__classPrivateFieldSet)(this,eM,this.asn.tbsCertificateRaw||r$.serialize(this.asn.tbsCertificate),"f"),(0,rX.__classPrivateFieldGet)(this,eM,"f")}constructor(e,A){const t=lO.isAsnEncoded(e)?[e,nh,A]:[e,A];super(t[0],t[1],t[2]),eM.set(this,void 0),eN.set(this,void 0),eO.set(this,void 0),eH.set(this,void 0),eU.set(this,void 0),e_.set(this,void 0),ex.set(this,void 0),eL.set(this,void 0),eP.set(this,void 0),eq.set(this,void 0),eK.set(this,void 0),eJ.set(this,void 0),this.tag=lN.CertificateTag}onInit(e){}getExtension(e){for(let A of this.extensions)if("string"==typeof e){if(A.type===e)return A}else if(A instanceof e)return A;return null}getExtensions(e){return this.extensions.filter(A=>"string"==typeof e?A.type===e:A instanceof e)}async verify(e={},A=lh.get()){let t,r,i=e.publicKey;try{if(i)if("publicKey"in i)t={...i.publicKey.algorithm,...this.signatureAlgorithm},r=await i.publicKey.export(t,["verify"],A);else if(i instanceof lH)t={...i.algorithm,...this.signatureAlgorithm},r=await i.export(t,["verify"],A);else if(eV.isBufferSource(i)){let e=new lH(i);t={...e.algorithm,...this.signatureAlgorithm},r=await e.export(t,["verify"],A)}else t={...i.algorithm,...this.signatureAlgorithm},r=i;else t={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(t,["verify"],A)}catch{return!1}let n=oS.resolveAll(l0).reverse(),a=null;for(let e of n)if(a=e.toWebSignature(t,this.signature))break;if(!a)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");let o=await A.subtle.verify(this.signatureAlgorithm,r,a,this.tbs);if(e.signatureOnly)return o;{let A=(e.date||new Date).getTime();return o&&this.notBefore.getTime()<A&&A<this.notAfter.getTime()}}async getThumbprint(e,A){let t,r="SHA-1";return e&&("object"==typeof e&&"subtle"in e?t=e:(r=e,t=A)),null!=t||(t=lh.get()),await t.subtle.digest(r,this.rawData)}async isSelfSigned(e=lh.get()){return this.subject===this.issuer&&await this.verify({signatureOnly:!0},e)}toTextObject(){let e=this.toTextObjectEmpty(),A=r$.parse(this.rawData,nh,this.parseOptions),t=A.tbsCertificate,r=new lo("",{Version:`${z[t.version]} (${t.version})`,"Serial Number":t.serialNumber,"Signature Algorithm":ll.serializeAlgorithm(t.signature),Issuer:this.issuer,Validity:new lo("",{"Not Before":t.validity.notBefore.getTime(),"Not After":t.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(t.issuerUniqueID&&(r["Issuer Unique ID"]=t.issuerUniqueID),t.subjectUniqueID&&(r["Subject Unique ID"]=t.subjectUniqueID),this.extensions.length){let e=new lo("");for(let A of this.extensions){let t=A.toTextObject();e[t[lo.NAME]]=t}r.Extensions=e}return e.Data=r,e.Signature=new lo("",{Algorithm:ll.serializeAlgorithm(A.signatureAlgorithm),"":A.signatureValue}),e}}eM=new WeakMap,eN=new WeakMap,eO=new WeakMap,eH=new WeakMap,eU=new WeakMap,e_=new WeakMap,ex=new WeakMap,eL=new WeakMap,eP=new WeakMap,eq=new WeakMap,eK=new WeakMap,eJ=new WeakMap,dA.NAME="Certificate",new WeakMap;class dt{static async createSelfSigned(e,A=lh.get()){if(!e.keys.privateKey)throw Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");if(!e.keys.publicKey)throw Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");return this.create({serialNumber:e.serialNumber,subject:e.name,issuer:e.name,notBefore:e.notBefore,notAfter:e.notAfter,publicKey:e.keys.publicKey,signingKey:e.keys.privateKey,signingAlgorithm:e.signingAlgorithm,extensions:e.extensions},A)}static async create(e,A=lh.get()){var t;let r;r=e.publicKey instanceof lH?e.publicKey.rawData:"publicKey"in e.publicKey?e.publicKey.publicKey.rawData:eV.isBufferSource(e.publicKey)?e.publicKey:await A.subtle.exportKey("spki",e.publicKey);let i=function(e,A=lh.get()){let t=eV.toUint8Array(e4.FromHex(e||""));var r=t.length&&t.some(e=>e>0)?t:A.getRandomValues(new Uint8Array(16));let i=0;for(;i<r.length-1&&0===r[i];)i++;let n=r.slice(i);if(n.length||(n=new Uint8Array([0])),n[0]>127){let e=new Uint8Array(n.length+1);e[0]=0,e.set(n,1),n=e}return n.buffer}(e.serialNumber,A),n=e.notBefore||new Date,a=e.notAfter||new Date(n.getTime()+31536e6),o=new nh({tbsCertificate:new nc({version:z.v3,serialNumber:i,validity:new nl({notBefore:n,notAfter:a}),extensions:new nu((null==(t=e.extensions)?void 0:t.map(e=>r$.parse(e.rawData,nd)))||[]),subjectPublicKeyInfo:r$.parse(r,no)})});if(e.subject){let A=e.subject instanceof lI?e.subject:new lI(e.subject);o.tbsCertificate.subject=r$.parse(A.toArrayBuffer(),r5)}if(e.issuer){let A=e.issuer instanceof lI?e.issuer:new lI(e.issuer);o.tbsCertificate.issuer=r$.parse(A.toArrayBuffer(),r5)}let s={hash:"SHA-256"},l="signingKey"in e?{...s,...e.signingAlgorithm,...e.signingKey.algorithm}:{...s,...e.signingAlgorithm},d=oS.resolve(sU);o.tbsCertificate.signature=o.signatureAlgorithm=d.toAsnAlgorithm(l);let u=r$.serialize(o.tbsCertificate),c="signingKey"in e?await A.subtle.sign(l,e.signingKey,u):e.signature,h=oS.resolveAll(l0).reverse(),g=null;for(let e of h)if(g=e.toAsnSignature(l,c))break;if(!g)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return o.signatureValue=g,new dA(r$.serialize(o))}}(I=eF||(eF={}))[I.unspecified=0]="unspecified",I[I.keyCompromise=1]="keyCompromise",I[I.cACompromise=2]="cACompromise",I[I.affiliationChanged=3]="affiliationChanged",I[I.superseded=4]="superseded",I[I.cessationOfOperation=5]="cessationOfOperation",I[I.certificateHold=6]="certificateHold",I[I.removeFromCRL=8]="removeFromCRL",I[I.privilegeWithdrawn=9]="privilegeWithdrawn",I[I.aACompromise=10]="aACompromise",new WeakMap,new WeakMap,new WeakMap,new WeakMap,new WeakMap,new WeakMap,new WeakMap,new WeakMap,new WeakMap,new WeakMap,new WeakMap,new WeakMap,lK.register(iI,l_),lK.register(iL,lx),lK.register(i$,lL),lK.register(ne,lP),lK.register(ig,lU),lK.register(i3,lq),lK.register(iT,lF),lK.register(iu,lj),lK.register(iV,lZ),lX.register(oz,lW),lX.register(oY,l$),oS.registerSingleton(l0,class{toAsnSignature(e,A){return eV.toArrayBuffer(A)}toWebSignature(e,A){return eV.toArrayBuffer(A)}}),oS.registerSingleton(l0,l4),l4.namedCurveSize.set("P-256",32),l4.namedCurveSize.set("K-256",32),l4.namedCurveSize.set("P-384",48),l4.namedCurveSize.set("P-521",66);class dr{constructor(e={}){if("view"in e)this.fromUint8Array(e.view);else if("buffer"in e)this.fromArrayBuffer(e.buffer);else if("string"in e)this.fromString(e.string);else if("hexstring"in e)this.fromHexString(e.hexstring);else if("length"in e&&e.length>0){if(this.length=e.length,e.stub)for(let A=0;A<this._view.length;A++)this._view[A]=e.stub}else this.length=0}set buffer(e){this._buffer=e,this._view=new Uint8Array(this._buffer)}get buffer(){return this._buffer}set view(e){this._buffer=new ArrayBuffer(e.length),this._view=new Uint8Array(this._buffer),this._view.set(e)}get view(){return this._view}get length(){return this.view.byteLength}set length(e){this._buffer=new ArrayBuffer(e),this._view=new Uint8Array(this._buffer)}clear(){this._buffer=new ArrayBuffer(0),this._view=new Uint8Array(this._buffer)}fromArrayBuffer(e){this._buffer=e,this._view=new Uint8Array(this._buffer)}fromUint8Array(e){this.fromArrayBuffer(new Uint8Array(e).buffer)}fromString(e){let A=e.length;this.length=A;for(let t=0;t<A;t++)this.view[t]=e.charCodeAt(t)}toString(e=0,A=this.view.length-e){let t="";(e>=this.view.length||e<0)&&(e=0),(A>=this.view.length||A<0)&&(A=this.view.length-e);for(let r=e;r<e+A;r++)t+=String.fromCharCode(this.view[r]);return t}fromHexString(e){let A=e.length;this.buffer=new ArrayBuffer(A>>1),this.view=new Uint8Array(this.buffer);let t=new Map;t.set("0",0),t.set("1",1),t.set("2",2),t.set("3",3),t.set("4",4),t.set("5",5),t.set("6",6),t.set("7",7),t.set("8",8),t.set("9",9),t.set("A",10),t.set("a",10),t.set("B",11),t.set("b",11),t.set("C",12),t.set("c",12),t.set("D",13),t.set("d",13),t.set("E",14),t.set("e",14),t.set("F",15),t.set("f",15);let r=0,i=0;for(let n=0;n<A;n++)n%2?(i|=t.get(e.charAt(n)),this.view[r]=i,r++):i=t.get(e.charAt(n))<<4}toHexString(e=0,A=this.view.length-e){let t="";(e>=this.view.length||e<0)&&(e=0),(A>=this.view.length||A<0)&&(A=this.view.length-e);for(let r=e;r<e+A;r++){let e=this.view[r].toString(16).toUpperCase();t=t+(1==e.length?"0":"")+e}return t}copy(e=0,A=this.length-e){if(!e&&!this.length)return new dr;if(e<0||e>this.length-1)throw Error(`Wrong start position: ${e}`);return new dr({buffer:this._buffer.slice(e,e+A)})}slice(e=0,A=this.length){if(!e&&!this.length)return new dr;if(e<0||e>this.length-1)throw Error(`Wrong start position: ${e}`);return new dr({buffer:this._buffer.slice(e,A)})}realloc(e){let A=new ArrayBuffer(e),t=new Uint8Array(A);e>this._view.length?t.set(this._view):t.set(new Uint8Array(this._buffer,0,e)),this._buffer=A,this._view=new Uint8Array(this._buffer)}append(e){let A=this.length,t=e.length,r=e._view.subarray();this.realloc(A+t),this._view.set(r,A)}insert(e,A=0,t=this.length-A){return!(A>this.length-1)&&(t>this.length-A&&(t=this.length-A),t>e.length&&(t=e.length),t==e.length?this._view.set(e._view,A):this._view.set(e._view.subarray(0,t),A),!0)}isEqual(e){if(this.length!=e.length)return!1;for(let A=0;A<e.length;A++)if(this.view[A]!=e.view[A])return!1;return!0}isEqualView(e){if(e.length!=this.view.length)return!1;for(let A=0;A<e.length;A++)if(this.view[A]!=e[A])return!1;return!0}findPattern(e,A,t,r){let{start:i,length:n,backward:a}=this.prepareFindParameters(A,t,r),o=e.length;if(o>n)return -1;let s=[];for(let A=0;A<o;A++)s.push(e.view[A]);for(let e=0;e<=n-o;e++){let A=!0,t=a?i-o-e:i+e;for(let e=0;e<o;e++)if(this.view[e+t]!=s[e]){A=!1;break}if(A)return a?i-o-e:i+o+e}return -1}findFirstIn(e,A,t,r){let{start:i,length:n,backward:a}=this.prepareFindParameters(A,t,r),o={id:-1,position:a?0:i+n,length:0};for(let A=0;A<e.length;A++){let t=this.findPattern(e[A],i,n,a);if(-1!=t){let r=!1,i=e[A].length;a?t-i>=o.position-o.length&&(r=!0):t-i<=o.position-o.length&&(r=!0),r&&(o.position=t,o.id=A,o.length=i)}}return o}findAllIn(e,A,t){let{start:r,length:i}=this.prepareFindParameters(A,t),n=[],a={id:-1,position:r};for(;;){let A=a.position;if(-1==(a=this.findFirstIn(e,a.position,i)).id)break;i-=a.position-A,n.push({id:a.id,position:a.position})}return n}findAllPatternIn(e,A,t){let{start:r,length:i}=this.prepareFindParameters(A,t),n=[],a=e.length;if(a>i)return -1;let o=Array.from(e.view);for(let e=0;e<=i-a;e++){let A=!0,t=r+e;for(let e=0;e<a;e++)if(this.view[e+t]!=o[e]){A=!1;break}A&&(n.push(r+a+e),e+=a-1)}return n}findFirstNotIn(e,A,t,r){let{start:i,length:n,backward:a}=this.prepareFindParameters(A,t,r),o={left:{id:-1,position:i},right:{id:-1,position:0},value:new dr},s=n;for(;s>0;){if(o.right=this.findFirstIn(e,a?i-n+s:i+n-s,s,a),-1==o.right.id){n=s,a?i-=n:i=o.left.position,o.value=new dr({buffer:this._buffer.slice(i,i+n)});break}if(o.right.position!=(a?o.left.position-e[o.right.id].length:o.left.position+e[o.right.id].length)){a?(i=o.right.position+e[o.right.id].length,n=o.left.position-o.right.position-e[o.right.id].length):(i=o.left.position,n=o.right.position-o.left.position-e[o.right.id].length),o.value=new dr({buffer:this._buffer.slice(i,i+n)});break}o.left=o.right,s-=e[o.right.id].length}if(a){let e=o.right;o.right=o.left,o.left=e}return o}findAllNotIn(e,A,t){let{start:r,length:i}=this.prepareFindParameters(A,t),n=[],a={left:{id:-1,position:r},right:{id:-1,position:r},value:new dr};do{let A=a.right.position;a=this.findFirstNotIn(e,a.right.position,i),i-=a.right.position-A,n.push({left:{id:a.left.id,position:a.left.position},right:{id:a.right.id,position:a.right.position},value:a.value})}while(-1!=a.right.id)return n}findFirstSequence(e,A,t,r){let{start:i,length:n,backward:a}=this.prepareFindParameters(A,t,r),o=this.skipNotPatterns(e,i,n,a);if(-1==o)return{position:-1,value:new dr};let s=this.skipPatterns(e,o,n-(a?i-o:o-i),a);return a?(i=s,n=o-s):(i=o,n=s-o),{position:s,value:new dr({buffer:this._buffer.slice(i,i+n)})}}findAllSequences(e,A,t){let{start:r,length:i}=this.prepareFindParameters(A,t),n=[],a={position:r,value:new dr};do{let A=a.position;-1!=(a=this.findFirstSequence(e,a.position,i)).position&&(i-=a.position-A,n.push({position:a.position,value:a.value}))}while(-1!=a.position)return n}findPairedPatterns(e,A,t,r){let i=[];if(e.isEqual(A))return i;let{start:n,length:a}=this.prepareFindParameters(t,r),o=0,s=this.findAllPatternIn(e,n,a);if(!Array.isArray(s)||0==s.length)return i;let l=this.findAllPatternIn(A,n,a);if(!Array.isArray(l)||0==l.length)return i;for(;o<s.length&&0!=l.length;){if(s[0]==l[0]){i.push({left:s[0],right:l[0]}),s.splice(0,1),l.splice(0,1);continue}if(s[o]>l[0])break;for(;s[o]<l[0]&&!(++o>=s.length););i.push({left:s[o-1],right:l[0]}),s.splice(o-1,1),l.splice(0,1),o=0}return i.sort((e,A)=>e.left-A.left),i}findPairedArrays(e,A,t,r){let{start:i,length:n}=this.prepareFindParameters(t,r),a=[],o=0,s=this.findAllIn(e,i,n);if(0==s.length)return a;let l=this.findAllIn(A,i,n);if(0==l.length)return a;for(;o<s.length&&0!=l.length;){if(s[0].position==l[0].position){a.push({left:s[0],right:l[0]}),s.splice(0,1),l.splice(0,1);continue}if(s[o].position>l[0].position)break;for(;s[o].position<l[0].position&&!(++o>=s.length););a.push({left:s[o-1],right:l[0]}),s.splice(o-1,1),l.splice(0,1),o=0}return a.sort((e,A)=>e.left.position-A.left.position),a}replacePattern(e,A,t,r,i=null){let n,a=[],o={status:-1,searchPatternPositions:[],replacePatternPositions:[]},{start:s,length:l}=this.prepareFindParameters(t,r);if(null==i){if(0==(a=this.findAllIn([e],s,l)).length)return o}else a=i;o.searchPatternPositions.push(...Array.from(a,e=>e.position));let d=e.length-A.length,u=new ArrayBuffer(this.view.length-a.length*d),c=new Uint8Array(u);for(c.set(new Uint8Array(this.buffer,0,s)),n=0;n<a.length;n++){let t=0==n?s:a[n-1].position;c.set(new Uint8Array(this.buffer,t,a[n].position-e.length-t),t-n*d),c.set(A.view,a[n].position-e.length-n*d),o.replacePatternPositions.push(a[n].position-e.length-n*d)}return n--,c.set(new Uint8Array(this.buffer,a[n].position,this.length-a[n].position),a[n].position-e.length+A.length-n*d),this.buffer=u,this.view=new Uint8Array(this.buffer),o.status=1,o}skipPatterns(e,A,t,r){let{start:i,length:n,backward:a}=this.prepareFindParameters(A,t,r),o=i;for(let A=0;A<e.length;A++){let t=e[A].length,r=a?o-t:o,s=!0;for(let i=0;i<t;i++)if(this.view[i+r]!=e[A].view[i]){s=!1;break}if(s){if(A=-1,a){if((o-=t)<=0)break}else if((o+=t)>=i+n)break}}return o}skipNotPatterns(e,A,t,r){let{start:i,length:n,backward:a}=this.prepareFindParameters(A,t,r),o=-1;for(let A=0;A<n;A++){for(let t=0;t<e.length;t++){let r=e[t].length,n=a?i-A-r:i+A,s=!0;for(let A=0;A<r;A++)if(this.view[A+n]!=e[t].view[A]){s=!1;break}if(s){o=a?i-A:i+A;break}}if(-1!=o)break}return o}prepareFindParameters(e=null,A=null,t=!1){return null===e&&(e=t?this.length:0),e>this.length&&(e=this.length),t?(null===A&&(A=e),A>e&&(A=e)):(null===A&&(A=this.length-e),A>this.length-e&&(A=this.length-e)),{start:e,length:A,backward:t}}}class di{constructor(e={}){this._stream=new dr,this._length=0,this._start=0,this.backward=!1,this.appendBlock=0,this.prevLength=0,this.prevStart=0,"view"in e?this.stream=new dr({view:e.view}):"buffer"in e?this.stream=new dr({buffer:e.buffer}):"string"in e?this.stream=new dr({string:e.string}):"hexstring"in e?this.stream=new dr({hexstring:e.hexstring}):"stream"in e?this.stream=e.stream.slice():this.stream=new dr,"backward"in e&&e.backward&&(this.backward=e.backward,this._start=this.stream.length),"length"in e&&e.length>0&&(this._length=e.length),"start"in e&&e.start&&e.start>0&&(this._start=e.start),"appendBlock"in e&&e.appendBlock&&e.appendBlock>0&&(this.appendBlock=e.appendBlock)}set stream(e){this._stream=e,this.prevLength=this._length,this._length=e.length,this.prevStart=this._start,this._start=0}get stream(){return this._stream}set length(e){this.prevLength=this._length,this._length=e}get length(){return this.appendBlock?this.start:this._length}set start(e){e>this.stream.length||(this.prevStart=this._start,this.prevLength=this._length,this._length-=this.backward?this._start-e:e-this._start,this._start=e)}get start(){return this._start}get buffer(){return this._stream.buffer.slice(0,this._length)}resetPosition(){this._start=this.prevStart,this._length=this.prevLength}findPattern(e,A=null){(null==A||A>this.length)&&(A=this.length);let t=this.stream.findPattern(e,this.start,this.length,this.backward);if(-1==t)return t;if(this.backward){if(t<this.start-e.length-A)return -1}else if(t>this.start+e.length+A)return -1;return this.start=t,t}findFirstIn(e,A=null){(null==A||A>this.length)&&(A=this.length);let t=this.stream.findFirstIn(e,this.start,this.length,this.backward);if(-1==t.id)return t;if(this.backward){if(t.position<this.start-e[t.id].length-A)return{id:-1,position:this.backward?0:this.start+this.length}}else if(t.position>this.start+e[t.id].length+A)return{id:-1,position:this.backward?0:this.start+this.length};return this.start=t.position,t}findAllIn(e){let A=this.backward?this.start-this.length:this.start;return this.stream.findAllIn(e,A,this.length)}findFirstNotIn(e,A=null){(null==A||A>this._length)&&(A=this._length);let t=this._stream.findFirstNotIn(e,this._start,this._length,this.backward);if(-1==t.left.id&&-1==t.right.id)return t;if(this.backward){if(-1!=t.right.id&&t.right.position<this._start-e[t.right.id].length-A)return{left:{id:-1,position:this._start},right:{id:-1,position:0},value:new dr}}else if(-1!=t.left.id&&t.left.position>this._start+e[t.left.id].length+A)return{left:{id:-1,position:this._start},right:{id:-1,position:0},value:new dr};return this.backward?-1==t.left.id?this.start=0:this.start=t.left.position:-1==t.right.id?this.start=this._start+this._length:this.start=t.right.position,t}findAllNotIn(e){let A=this.backward?this._start-this._length:this._start;return this._stream.findAllNotIn(e,A,this._length)}findFirstSequence(e,A=null,t=null){(null==A||A>this._length)&&(A=this._length),(null==t||t>A)&&(t=A);let r=this._stream.findFirstSequence(e,this._start,A,this.backward);if(0==r.value.length)return r;if(this.backward){if(r.position<this._start-r.value.length-t)return{position:-1,value:new dr}}else if(r.position>this._start+r.value.length+t)return{position:-1,value:new dr};return this.start=r.position,r}findAllSequences(e){let A=this.backward?this.start-this.length:this.start;return this.stream.findAllSequences(e,A,this.length)}findPairedPatterns(e,A,t=null){(null==t||t>this.length)&&(t=this.length);let r=this.backward?this.start-this.length:this.start,i=this.stream.findPairedPatterns(e,A,r,this.length);if(i.length){if(this.backward){if(i[0].right<this.start-A.length-t)return[]}else if(i[0].left>this.start+e.length+t)return[]}return i}findPairedArrays(e,A,t=null){(null==t||t>this.length)&&(t=this.length);let r=this.backward?this.start-this.length:this.start,i=this.stream.findPairedArrays(e,A,r,this.length);if(i.length){if(this.backward){if(i[0].right.position<this.start-A[i[0].right.id].length-t)return[]}else if(i[0].left.position>this.start+e[i[0].left.id].length+t)return[]}return i}replacePattern(e,A){let t=this.backward?this.start-this.length:this.start;return this.stream.replacePattern(e,A,t,this.length)}skipPatterns(e){let A=this.stream.skipPatterns(e,this.start,this.length,this.backward);return this.start=A,A}skipNotPatterns(e){let A=this.stream.skipNotPatterns(e,this.start,this.length,this.backward);return -1==A?-1:(this.start=A,A)}append(e){this.beforeAppend(e.length),this._stream.view.set(e.view,this._start),this._length+=2*e.length,this.start=this._start+e.length,this.prevLength-=2*e.length}appendView(e){this.beforeAppend(e.length),this._stream.view.set(e,this._start),this._length+=2*e.length,this.start=this._start+e.length,this.prevLength-=2*e.length}appendChar(e){this.beforeAppend(1),this._stream.view[this._start]=e,this._length+=2,this.start=this._start+1,this.prevLength-=2}appendUint16(e){this.beforeAppend(2);let A=new Uint8Array(new Uint16Array([e]).buffer);this.stream.view[this._start]=A[1],this._stream.view[this._start+1]=A[0],this._length+=4,this.start=this._start+2,this.prevLength-=4}appendUint24(e){this.beforeAppend(3);let A=new Uint8Array(new Uint32Array([e]).buffer);this._stream.view[this._start]=A[2],this._stream.view[this._start+1]=A[1],this._stream.view[this._start+2]=A[0],this._length+=6,this.start=this._start+3,this.prevLength-=6}appendUint32(e){this.beforeAppend(4);let A=new Uint8Array(new Uint32Array([e]).buffer);this._stream.view[this._start]=A[3],this._stream.view[this._start+1]=A[2],this._stream.view[this._start+2]=A[1],this._stream.view[this._start+3]=A[0],this._length+=8,this.start=this._start+4,this.prevLength-=8}appendInt16(e){this.beforeAppend(2);let A=new Uint8Array(new Int16Array([e]).buffer);this._stream.view[this._start]=A[1],this._stream.view[this._start+1]=A[0],this._length+=4,this.start=this._start+2,this.prevLength-=4}appendInt32(e){this.beforeAppend(4);let A=new Uint8Array(new Int32Array([e]).buffer);this._stream.view[this._start]=A[3],this._stream.view[this._start+1]=A[2],this._stream.view[this._start+2]=A[1],this._stream.view[this._start+3]=A[0],this._length+=8,this.start=this._start+4,this.prevLength-=8}getBlock(e,A=!0){let t;if(this._length<=0)return new Uint8Array(0);if(this._length<e&&(e=this._length),this.backward){let A=this._stream.view.subarray(this._length-e,this._length);t=new Uint8Array(e);for(let r=0;r<e;r++)t[e-1-r]=A[r]}else t=this._stream.view.subarray(this._start,this._start+e);return A&&(this.start+=this.backward?-1*e:e),t}getUint16(e=!0){let A=this.getBlock(2,e);return A.length<2?0:A[0]<<8|A[1]}getInt16(e=!0){let A=this.getUint16(e);return 32768&A?-(32768-(32768^A)):A}getUint24(e=!0){let A=this.getBlock(4,e);return A.length<3?0:A[0]<<16|A[1]<<8|A[2]}getUint32(e=!0){let A=this.getBlock(4,e);return A.length<4?0:0x1000000*A[0]+(A[1]<<16)+(A[2]<<8)+A[3]}getInt32(e=!0){let A=this.getUint32(e);return 0x80000000&A?-(0x80000000-(0x80000000^A)):A}beforeAppend(e){this._start+e>this._stream.length&&(e>this.appendBlock&&(this.appendBlock=e+di.APPEND_BLOCK),this._stream.realloc(this._stream.length+this.appendBlock))}}function dn(e,...A){if(!(e instanceof Uint8Array||null!=e&&"object"==typeof e&&"Uint8Array"===e.constructor.name))throw Error("Uint8Array expected");if(A.length>0&&!A.includes(e.length))throw Error(`Uint8Array expected of length ${A}, not of length=${e.length}`)}function da(e,A=!0){if(e.destroyed)throw Error("Hash instance has been destroyed");if(A&&e.finished)throw Error("Hash#digest() has already been called")}di.APPEND_BLOCK=1e3;let ds=e=>new DataView(e.buffer,e.byteOffset,e.byteLength),dl=(e,A)=>e<<32-A|e>>>A,dd=(e,A)=>e<<A|e>>>32-A>>>0;function du(e){return"string"==typeof e&&(e=function(e){if("string"!=typeof e)throw Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}(e)),dn(e),e}new Uint8Array(new Uint32Array([0x11223344]).buffer)[0];class dc{clone(){return this._cloneInto()}}function dh(e){let A=A=>e().update(du(A)).digest(),t=e();return A.outputLen=t.outputLen,A.blockLen=t.blockLen,A.create=()=>e(),A}let dg=(e,A,t)=>e&A^~e&t,dp=(e,A,t)=>e&A^e&t^A&t;class dC extends dc{constructor(e,A,t,r){super(),this.blockLen=e,this.outputLen=A,this.padOffset=t,this.isLE=r,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=ds(this.buffer)}update(e){da(this);let{view:A,buffer:t,blockLen:r}=this,i=(e=du(e)).length;for(let n=0;n<i;){let a=Math.min(r-this.pos,i-n);if(a===r){let A=ds(e);for(;r<=i-n;n+=r)this.process(A,n);continue}t.set(e.subarray(n,n+a),this.pos),this.pos+=a,n+=a,this.pos===r&&(this.process(A,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){da(this);dn(e);let A=this.outputLen;if(e.length<A)throw Error(`digestInto() expects output buffer of length at least ${A}`);this.finished=!0;let{buffer:t,view:r,blockLen:i,isLE:n}=this,{pos:a}=this;t[a++]=128,this.buffer.subarray(a).fill(0),this.padOffset>i-a&&(this.process(r,0),a=0);for(let e=a;e<i;e++)t[e]=0;!function(e,A,t,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(A,t,r);let i=BigInt(32),n=BigInt(0xffffffff),a=Number(t>>i&n),o=Number(t&n),s=4*!!r,l=4*!r;e.setUint32(A+s,a,r),e.setUint32(A+l,o,r)}(r,i-8,BigInt(8*this.length),n),this.process(r,0);let o=ds(e),s=this.outputLen;if(s%4)throw Error("_sha2: outputLen should be aligned to 32bit");let l=s/4,d=this.get();if(l>d.length)throw Error("_sha2: outputLen bigger than state");for(let e=0;e<l;e++)o.setUint32(4*e,d[e],n)}digest(){let{buffer:e,outputLen:A}=this;this.digestInto(e);let t=e.slice(0,A);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:A,buffer:t,length:r,finished:i,destroyed:n,pos:a}=this;return e.length=r,e.pos=a,e.finished=i,e.destroyed=n,r%A&&e.buffer.set(t),e}}let df=new Uint32Array([0x67452301,0xefcdab89,0x98badcfe,0x10325476,0xc3d2e1f0]),dI=new Uint32Array(80);class dw extends dC{constructor(){super(64,20,8,!1),this.A=0|df[0],this.B=0|df[1],this.C=0|df[2],this.D=0|df[3],this.E=0|df[4]}get(){let{A:e,B:A,C:t,D:r,E:i}=this;return[e,A,t,r,i]}set(e,A,t,r,i){this.A=0|e,this.B=0|A,this.C=0|t,this.D=0|r,this.E=0|i}process(e,A){for(let t=0;t<16;t++,A+=4)dI[t]=e.getUint32(A,!1);for(let e=16;e<80;e++)dI[e]=dd(dI[e-3]^dI[e-8]^dI[e-14]^dI[e-16],1);let{A:t,B:r,C:i,D:n,E:a}=this;for(let e=0;e<80;e++){let A,o;e<20?(A=dg(r,i,n),o=0x5a827999):e<40?(A=r^i^n,o=0x6ed9eba1):e<60?(A=dp(r,i,n),o=0x8f1bbcdc):(A=r^i^n,o=0xca62c1d6);let s=dd(t,5)+A+a+o+dI[e]|0;a=n,n=i,i=dd(r,30),r=t,t=s}t=t+this.A|0,r=r+this.B|0,i=i+this.C|0,n=n+this.D|0,a=a+this.E|0,this.set(t,r,i,n,a)}roundClean(){dI.fill(0)}destroy(){this.set(0,0,0,0,0),this.buffer.fill(0)}}let dm=dh(()=>new dw),dE=BigInt(0x100000000-1),dy=BigInt(32),dB=(e,A,t)=>e>>>t,dQ=(e,A,t)=>e<<32-t|A>>>t,dD=(e,A,t)=>e>>>t|A<<32-t,db=(e,A,t)=>e<<32-t|A>>>t,dS=(e,A,t)=>e<<64-t|A>>>t-32,dk=(e,A,t)=>e>>>t-32|A<<64-t,dR=function(e,A,t,r){let i=(A>>>0)+(r>>>0);return{h:e+t+(i/0x100000000|0)|0,l:0|i}},dv=(e,A,t)=>(e>>>0)+(A>>>0)+(t>>>0),dG=(e,A,t,r)=>A+t+r+(e/0x100000000|0)|0,dT=(e,A,t,r)=>(e>>>0)+(A>>>0)+(t>>>0)+(r>>>0),dM=(e,A,t,r,i)=>A+t+r+i+(e/0x100000000|0)|0,dN=(e,A,t,r,i,n)=>A+t+r+i+n+(e/0x100000000|0)|0,dO=(e,A,t,r,i)=>(e>>>0)+(A>>>0)+(t>>>0)+(r>>>0)+(i>>>0),[dH,dU]=function(e,A=!1){let t=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let i=0;i<e.length;i++){let{h:n,l:a}=function(e,A=!1){return A?{h:Number(e&dE),l:Number(e>>dy&dE)}:{h:0|Number(e>>dy&dE),l:0|Number(e&dE)}}(e[i],A);[t[i],r[i]]=[n,a]}return[t,r]}(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),d_=new Uint32Array(80),dx=new Uint32Array(80);class dL extends dC{constructor(){super(128,64,16,!1),this.Ah=0x6a09e667,this.Al=-0xc4336f8,this.Bh=-0x4498517b,this.Bl=-0x7b3558c5,this.Ch=0x3c6ef372,this.Cl=-0x16b07d5,this.Dh=-0x5ab00ac6,this.Dl=0x5f1d36f1,this.Eh=0x510e527f,this.El=-0x52197d2f,this.Fh=-0x64fa9774,this.Fl=0x2b3e6c1f,this.Gh=0x1f83d9ab,this.Gl=-0x4be4295,this.Hh=0x5be0cd19,this.Hl=0x137e2179}get(){let{Ah:e,Al:A,Bh:t,Bl:r,Ch:i,Cl:n,Dh:a,Dl:o,Eh:s,El:l,Fh:d,Fl:u,Gh:c,Gl:h,Hh:g,Hl:p}=this;return[e,A,t,r,i,n,a,o,s,l,d,u,c,h,g,p]}set(e,A,t,r,i,n,a,o,s,l,d,u,c,h,g,p){this.Ah=0|e,this.Al=0|A,this.Bh=0|t,this.Bl=0|r,this.Ch=0|i,this.Cl=0|n,this.Dh=0|a,this.Dl=0|o,this.Eh=0|s,this.El=0|l,this.Fh=0|d,this.Fl=0|u,this.Gh=0|c,this.Gl=0|h,this.Hh=0|g,this.Hl=0|p}process(e,A){for(let t=0;t<16;t++,A+=4)d_[t]=e.getUint32(A),dx[t]=e.getUint32(A+=4);for(let e=16;e<80;e++){let A=0|d_[e-15],t=0|dx[e-15],r=dD(A,t,1)^dD(A,t,8)^dB(A,t,7),i=db(A,t,1)^db(A,t,8)^dQ(A,t,7),n=0|d_[e-2],a=0|dx[e-2],o=dD(n,a,19)^dS(n,a,61)^dB(n,a,6),s=dT(i,db(n,a,19)^dk(n,a,61)^dQ(n,a,6),dx[e-7],dx[e-16]),l=dM(s,r,o,d_[e-7],d_[e-16]);d_[e]=0|l,dx[e]=0|s}let{Ah:t,Al:r,Bh:i,Bl:n,Ch:a,Cl:o,Dh:s,Dl:l,Eh:d,El:u,Fh:c,Fl:h,Gh:g,Gl:p,Hh:C,Hl:f}=this;for(let e=0;e<80;e++){let A=dD(d,u,14)^dD(d,u,18)^dS(d,u,41),I=db(d,u,14)^db(d,u,18)^dk(d,u,41),w=d&c^~d&g,m=dO(f,I,u&h^~u&p,dU[e],dx[e]),E=dN(m,C,A,w,dH[e],d_[e]),y=0|m,B=dD(t,r,28)^dS(t,r,34)^dS(t,r,39),Q=db(t,r,28)^dk(t,r,34)^dk(t,r,39),D=t&i^t&a^i&a,b=r&n^r&o^n&o;C=0|g,f=0|p,g=0|c,p=0|h,c=0|d,h=0|u,({h:d,l:u}=dR(0|s,0|l,0|E,0|y)),s=0|a,l=0|o,a=0|i,o=0|n,i=0|t,n=0|r;let S=dv(y,Q,b);t=dG(S,E,B,D),r=0|S}({h:t,l:r}=dR(0|this.Ah,0|this.Al,0|t,0|r)),({h:i,l:n}=dR(0|this.Bh,0|this.Bl,0|i,0|n)),({h:a,l:o}=dR(0|this.Ch,0|this.Cl,0|a,0|o)),({h:s,l:l}=dR(0|this.Dh,0|this.Dl,0|s,0|l)),({h:d,l:u}=dR(0|this.Eh,0|this.El,0|d,0|u)),({h:c,l:h}=dR(0|this.Fh,0|this.Fl,0|c,0|h)),({h:g,l:p}=dR(0|this.Gh,0|this.Gl,0|g,0|p)),({h:C,l:f}=dR(0|this.Hh,0|this.Hl,0|C,0|f)),this.set(t,r,i,n,a,o,s,l,d,u,c,h,g,p,C,f)}roundClean(){d_.fill(0),dx.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class dP extends dL{constructor(){super(),this.Ah=-0x344462a3,this.Al=-0x3efa6128,this.Bh=0x629a292a,this.Bl=0x367cd507,this.Ch=-0x6ea6fea6,this.Cl=0x3070dd17,this.Dh=0x152fecd8,this.Dl=-0x8f1a6c7,this.Eh=0x67332667,this.El=-4191439,this.Fh=-0x714bb579,this.Fl=0x68581511,this.Gh=-0x24f3d1f3,this.Gl=0x64f98fa7,this.Hh=0x47b5481d,this.Hl=-0x4105b05c,this.outputLen=48}}let dq=dh(()=>new dL),dK=dh(()=>new dP),dJ=new Uint32Array([0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0xfc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x6ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2]),dF=new Uint32Array([0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19]),dj=new Uint32Array(64);class dz extends dC{constructor(){super(64,32,8,!1),this.A=0|dF[0],this.B=0|dF[1],this.C=0|dF[2],this.D=0|dF[3],this.E=0|dF[4],this.F=0|dF[5],this.G=0|dF[6],this.H=0|dF[7]}get(){let{A:e,B:A,C:t,D:r,E:i,F:n,G:a,H:o}=this;return[e,A,t,r,i,n,a,o]}set(e,A,t,r,i,n,a,o){this.A=0|e,this.B=0|A,this.C=0|t,this.D=0|r,this.E=0|i,this.F=0|n,this.G=0|a,this.H=0|o}process(e,A){for(let t=0;t<16;t++,A+=4)dj[t]=e.getUint32(A,!1);for(let e=16;e<64;e++){let A=dj[e-15],t=dj[e-2],r=dl(A,7)^dl(A,18)^A>>>3,i=dl(t,17)^dl(t,19)^t>>>10;dj[e]=i+dj[e-7]+r+dj[e-16]|0}let{A:t,B:r,C:i,D:n,E:a,F:o,G:s,H:l}=this;for(let e=0;e<64;e++){let A=l+(dl(a,6)^dl(a,11)^dl(a,25))+dg(a,o,s)+dJ[e]+dj[e]|0,d=(dl(t,2)^dl(t,13)^dl(t,22))+dp(t,r,i)|0;l=s,s=o,o=a,a=n+A|0,n=i,i=r,r=t,t=A+d|0}t=t+this.A|0,r=r+this.B|0,i=i+this.C|0,n=n+this.D|0,a=a+this.E|0,o=o+this.F|0,s=s+this.G|0,l=l+this.H|0,this.set(t,r,i,n,a,o,s,l)}roundClean(){dj.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}let dY=dh(()=>new dz),dZ=new ArrayBuffer(0);class dV extends TypeError{constructor(){super(...arguments),this.name=dV.NAME}static isType(e,A){if("string"==typeof A){if("Array"===A&&Array.isArray(e))return!0;else if("ArrayBuffer"===A&&e instanceof ArrayBuffer)return!0;else if("ArrayBufferView"===A&&ArrayBuffer.isView(e))return!0;else if(typeof e===A)return!0}else if(e instanceof A)return!0;return!1}static assert(e,A,...t){for(let A of t)if(this.isType(e,A))return;let r=t.map(e=>e instanceof Function&&"name"in e?e.name:`${e}`);throw new dV(`Parameter '${A}' is not of type ${r.length>1?`(${r.join(" or ")})`:r[0]}`)}}dV.NAME="ArgumentError";class dW extends TypeError{static assert(...e){let A,t,r=null;for(let i of("string"==typeof e[0]?(r=e[0],A=e[1],t=e.slice(2)):(A=e[0],t=e.slice(1)),dV.assert(A,"parameters","object"),t))if(null==A[i])throw new dW(i,r)}static assertEmpty(e,A,t){if(null==e)throw new dW(A,t)}constructor(e,A=null,t){super(),this.name=dW.NAME,this.field=e,A&&(this.target=A),t?this.message=t:this.message=`Absent mandatory parameter '${e}' ${A?` in '${A}'`:""}`}}dW.NAME="ParameterError";class d$ extends Error{static assertSchema(e,A){if(!e.verified)throw Error(`Object's schema was not verified against input data for ${A}`)}static assert(e,A){if(-1===e.offset)throw new d$(`Error during parsing of ASN.1 data. Data is not correct for '${A}'.`)}constructor(e){super(e),this.name="AsnError"}}class dX{static blockName(){return this.CLASS_NAME}static fromBER(e){let A=AU(e);d$.assert(A,this.name);try{return new this({schema:A.result})}catch(e){throw new d$(`Cannot create '${this.CLASS_NAME}' from ASN.1 object`)}}static defaultValues(e){throw Error(`Invalid member name for ${this.CLASS_NAME} class: ${e}`)}static schema(e={}){throw Error(`Method '${this.CLASS_NAME}.schema' should be overridden`)}get className(){return this.constructor.CLASS_NAME}toString(e="hex"){let A;try{A=this.toSchema()}catch{A=this.toSchema(!0)}return e4.ToString(A.toBER(),e)}}function d0(e){let A=!1,t="",r=e.trim();for(let e=0;e<r.length;e++)32===r.charCodeAt(e)?!1===A&&(A=!0):(A&&(t+=" ",A=!1),t+=r[e]);return t.toLowerCase()}dX.CLASS_NAME="PkiObject";let d1="type",d8="value";class d4 extends dX{constructor(e={}){super(),this.type=e2(e,d1,d4.defaultValues(d1)),this.value=e2(e,d8,d4.defaultValues(d8)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case d1:return"";case d8:return{};default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new A1({name:A.type||""}),new ty({name:A.value||""})]})}fromSchema(e){Ad(e,[d1,"typeValue"]);let A=tb(e,e,d4.schema({names:{type:d1,value:"typeValue"}}));d$.assertSchema(A,this.className),this.type=A.result.type.valueBlock.toString(),this.value=A.result.typeValue}toSchema(){return new A6({value:[new A1({value:this.type}),this.value]})}toJSON(){let e={type:this.type};return 0!==Object.keys(this.value).length?e.value=this.value.toJSON():e.value=this.value,e}isEqual(e){let A=[tA.blockName(),tr.blockName(),tn.blockName(),ta.blockName(),to.blockName(),ts.blockName(),tl.blockName(),td.blockName(),tu.blockName(),tc.blockName(),th.blockName(),tg.blockName()];if(e instanceof ArrayBuffer)return eV.isEqual(this.value.valueBeforeDecodeView,e);if(e.constructor.blockName()===d4.blockName()){if(this.type!==e.type)return!1;let t=[!1,!1],r=this.value.constructor.blockName();for(let i of A)r===i&&(t[0]=!0),e.value.constructor.blockName()===i&&(t[1]=!0);if(t[0]!==t[1])return!1;if(t[0]&&t[1]){let A=d0(this.value.valueBlock.value),t=d0(e.value.valueBlock.value);if(0!==A.localeCompare(t))return!1}else if(!eV.isEqual(this.value.valueBeforeDecodeView,e.value.valueBeforeDecodeView))return!1;return!0}return!1}}d4.CLASS_NAME="AttributeTypeAndValue";let d2="typesAndValues",d6="valueBeforeDecode";class d3 extends dX{constructor(e={}){super(),this.typesAndValues=e2(e,d2,d3.defaultValues(d2)),this.valueBeforeDecode=e2(e,d6,d3.defaultValues(d6)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case d2:return[];case d6:return dZ;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case d2:return 0===A.length;case d6:return 0===A.byteLength;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new tQ({name:A.repeatedSequence||"",value:new A3({value:[new tQ({name:A.repeatedSet||"",value:d4.schema(A.typeAndValue||{})})]})})]})}fromSchema(e){Ad(e,["RDN",d2]);let A=tb(e,e,d3.schema({names:{blockName:"RDN",repeatedSet:d2}}));d$.assertSchema(A,this.className),d2 in A.result&&(this.typesAndValues=Array.from(A.result.typesAndValues,e=>new d4({schema:e}))),this.valueBeforeDecode=A.result.RDN.valueBeforeDecodeView.slice().buffer}toSchema(){if(0===this.valueBeforeDecode.byteLength)return new A6({value:[new A3({value:Array.from(this.typesAndValues,e=>e.toSchema())})]});let e=AU(this.valueBeforeDecode);if(d$.assert(e,"RelativeDistinguishedNames"),!(e.result instanceof A6))throw Error("ASN.1 result should be SEQUENCE");return e.result}toJSON(){return{typesAndValues:Array.from(this.typesAndValues,e=>e.toJSON())}}isEqual(e){if(e instanceof d3){if(this.typesAndValues.length!==e.typesAndValues.length)return!1;for(let[A,t]of this.typesAndValues.entries())if(!1===t.isEqual(e.typesAndValues[A]))return!1;return!0}return e instanceof ArrayBuffer&&AA(this.valueBeforeDecode,e)}}d3.CLASS_NAME="RelativeDistinguishedNames";let d5="type",d9="value";class d7 extends dX{constructor(e={}){super(),this.type=e2(e,d5,d7.defaultValues(d5)),this.value=e2(e,d9,d7.defaultValues(d9)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case d5:return 9;case d9:return{};default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case d5:return A===d7.defaultValues(e);case d9:return 0===Object.keys(A).length;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new tB({value:[new Ax({idBlock:{tagClass:3,tagNumber:0},name:A.blockName||"",value:[new A1,new Ax({idBlock:{tagClass:3,tagNumber:0},value:[new ty]})]}),new AM({name:A.blockName||"",idBlock:{tagClass:3,tagNumber:1}}),new AM({name:A.blockName||"",idBlock:{tagClass:3,tagNumber:2}}),new Ax({idBlock:{tagClass:3,tagNumber:3},name:A.blockName||"",value:[function(e={},A=!1){let t=e2(e,"names",{});return new A6({optional:A,value:[new Ax({optional:!0,idBlock:{tagClass:2,tagNumber:1},name:t.country_name||"",value:[new tB({value:[new ta,new to]})]}),new Ax({optional:!0,idBlock:{tagClass:2,tagNumber:2},name:t.administration_domain_name||"",value:[new tB({value:[new ta,new to]})]}),new AM({optional:!0,idBlock:{tagClass:3,tagNumber:0},name:t.network_address||"",isHexOnly:!0}),new AM({optional:!0,idBlock:{tagClass:3,tagNumber:1},name:t.terminal_identifier||"",isHexOnly:!0}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:2},name:t.private_domain_name||"",value:[new tB({value:[new ta,new to]})]}),new AM({optional:!0,idBlock:{tagClass:3,tagNumber:3},name:t.organization_name||"",isHexOnly:!0}),new AM({optional:!0,name:t.numeric_user_identifier||"",idBlock:{tagClass:3,tagNumber:4},isHexOnly:!0}),new Ax({optional:!0,name:t.personal_name||"",idBlock:{tagClass:3,tagNumber:5},value:[new AM({idBlock:{tagClass:3,tagNumber:0},isHexOnly:!0}),new AM({optional:!0,idBlock:{tagClass:3,tagNumber:1},isHexOnly:!0}),new AM({optional:!0,idBlock:{tagClass:3,tagNumber:2},isHexOnly:!0}),new AM({optional:!0,idBlock:{tagClass:3,tagNumber:3},isHexOnly:!0})]}),new Ax({optional:!0,name:t.organizational_unit_names||"",idBlock:{tagClass:3,tagNumber:6},value:[new tQ({value:new to})]})]})}(A.builtInStandardAttributes||{},!1),function(e=!1){return new A6({optional:e,value:[new to,new to]})}(!0),function(e=!1){return new A3({optional:e,value:[new AM({optional:!0,idBlock:{tagClass:3,tagNumber:0},isHexOnly:!0}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new ty]})]})}(!0)]}),new Ax({idBlock:{tagClass:3,tagNumber:4},name:A.blockName||"",value:[d3.schema(A.directoryName||{})]}),new Ax({idBlock:{tagClass:3,tagNumber:5},name:A.blockName||"",value:[new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new tB({value:[new ts,new to,new tn,new tA,new tr]})]}),new Ax({idBlock:{tagClass:3,tagNumber:1},value:[new tB({value:[new ts,new to,new tn,new tA,new tr]})]})]}),new AM({name:A.blockName||"",idBlock:{tagClass:3,tagNumber:6}}),new AM({name:A.blockName||"",idBlock:{tagClass:3,tagNumber:7}}),new AM({name:A.blockName||"",idBlock:{tagClass:3,tagNumber:8}})]})}fromSchema(e){Ad(e,["blockName","otherName","rfc822Name","dNSName","x400Address","directoryName","ediPartyName","uniformResourceIdentifier","iPAddress","registeredID"]);let A=tb(e,e,d7.schema({names:{blockName:"blockName",otherName:"otherName",rfc822Name:"rfc822Name",dNSName:"dNSName",x400Address:"x400Address",directoryName:{names:{blockName:"directoryName"}},ediPartyName:"ediPartyName",uniformResourceIdentifier:"uniformResourceIdentifier",iPAddress:"iPAddress",registeredID:"registeredID"}}));switch(d$.assertSchema(A,this.className),this.type=A.result.blockName.idBlock.tagNumber,this.type){case 0:case 3:this.value=A.result.blockName;break;case 1:case 2:case 6:{let e=A.result.blockName;e.idBlock.tagClass=1,e.idBlock.tagNumber=22;let t=AU(e.toBER(!1));d$.assert(t,"GeneralName value"),this.value=t.result.valueBlock.value}break;case 4:this.value=new d3({schema:A.result.directoryName});break;case 5:this.value=A.result.ediPartyName;break;case 7:this.value=new Aj({valueHex:A.result.blockName.valueBlock.valueHex});break;case 8:{let e=A.result.blockName;e.idBlock.tagClass=1,e.idBlock.tagNumber=6;let t=AU(e.toBER(!1));d$.assert(t,"GeneralName registeredID"),this.value=t.result.valueBlock.toString()}}}toSchema(){switch(this.type){case 0:case 3:case 5:return new Ax({idBlock:{tagClass:3,tagNumber:this.type},value:[this.value]});case 1:case 2:case 6:{let e=new td({value:this.value});return e.idBlock.tagClass=3,e.idBlock.tagNumber=this.type,e}case 4:return new Ax({idBlock:{tagClass:3,tagNumber:4},value:[this.value.toSchema()]});case 7:{let e=this.value;return e.idBlock.tagClass=3,e.idBlock.tagNumber=this.type,e}case 8:{let e=new A1({value:this.value});return e.idBlock.tagClass=3,e.idBlock.tagNumber=this.type,e}default:return d7.schema()}}toJSON(){let e={type:this.type,value:""};if("string"==typeof this.value)e.value=this.value;else try{e.value=this.value.toJSON()}catch{}return e}}d7.CLASS_NAME="GeneralName";let ue="accessMethod",uA="accessLocation",ut=[ue,uA];class ur extends dX{constructor(e={}){super(),this.accessMethod=e2(e,ue,ur.defaultValues(ue)),this.accessLocation=e2(e,uA,ur.defaultValues(uA)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case ue:return"";case uA:return new d7;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new A1({name:A.accessMethod||""}),d7.schema(A.accessLocation||{})]})}fromSchema(e){Ad(e,ut);let A=tb(e,e,ur.schema({names:{accessMethod:ue,accessLocation:{names:{blockName:uA}}}}));d$.assertSchema(A,this.className),this.accessMethod=A.result.accessMethod.valueBlock.toString(),this.accessLocation=new d7({schema:A.result.accessLocation})}toSchema(){return new A6({value:[new A1({value:this.accessMethod}),this.accessLocation.toSchema()]})}toJSON(){return{accessMethod:this.accessMethod,accessLocation:this.accessLocation.toJSON()}}}ur.CLASS_NAME="AccessDescription";let ui="seconds",un="millis",ua="micros";class uo extends dX{constructor(e={}){super(),ui in e&&(this.seconds=e2(e,ui,uo.defaultValues(ui))),un in e&&(this.millis=e2(e,un,uo.defaultValues(un))),ua in e&&(this.micros=e2(e,ua,uo.defaultValues(ua))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case ui:case un:case ua:return 0;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case ui:case un:case ua:return A===uo.defaultValues(e);default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",optional:!0,value:[new AW({optional:!0,name:A.seconds||""}),new AM({name:A.millis||"",optional:!0,idBlock:{tagClass:3,tagNumber:0}}),new AM({name:A.micros||"",optional:!0,idBlock:{tagClass:3,tagNumber:1}})]})}fromSchema(e){Ad(e,[ui,un,ua]);let A=tb(e,e,uo.schema({names:{seconds:ui,millis:un,micros:ua}}));if(d$.assertSchema(A,this.className),"seconds"in A.result&&(this.seconds=A.result.seconds.valueBlock.valueDec),"millis"in A.result){let e=new AW({valueHex:A.result.millis.valueBlock.valueHex});this.millis=e.valueBlock.valueDec}if("micros"in A.result){let e=new AW({valueHex:A.result.micros.valueBlock.valueHex});this.micros=e.valueBlock.valueDec}}toSchema(){let e=[];if(void 0!==this.seconds&&e.push(new AW({value:this.seconds})),void 0!==this.millis){let A=new AW({value:this.millis});e.push(new AM({idBlock:{tagClass:3,tagNumber:0},valueHex:A.valueBlock.valueHexView}))}if(void 0!==this.micros){let A=new AW({value:this.micros});e.push(new AM({idBlock:{tagClass:3,tagNumber:1},valueHex:A.valueBlock.valueHexView}))}return new A6({value:e})}toJSON(){let e={};return void 0!==this.seconds&&(e.seconds=this.seconds),void 0!==this.millis&&(e.millis=this.millis),void 0!==this.micros&&(e.micros=this.micros),e}}uo.CLASS_NAME="Accuracy";let us="algorithmId",ul="algorithmParams",ud="algorithm",uu="params",uc=[ud,uu];class uh extends dX{constructor(e={}){super(),this.algorithmId=e2(e,us,uh.defaultValues(us)),ul in e&&(this.algorithmParams=e2(e,ul,uh.defaultValues(ul))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case us:return"";case ul:return new ty;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case us:return""===A;case ul:return A instanceof ty;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",optional:A.optional||!1,value:[new A1({name:A.algorithmIdentifier||""}),new ty({name:A.algorithmParams||"",optional:!0})]})}fromSchema(e){Ad(e,uc);let A=tb(e,e,uh.schema({names:{algorithmIdentifier:ud,algorithmParams:uu}}));d$.assertSchema(A,this.className),this.algorithmId=A.result.algorithm.valueBlock.toString(),uu in A.result&&(this.algorithmParams=A.result.params)}toSchema(){let e=[];return e.push(new A1({value:this.algorithmId})),!this.algorithmParams||this.algorithmParams instanceof ty||e.push(this.algorithmParams),new A6({value:e})}toJSON(){let e={algorithmId:this.algorithmId};return!this.algorithmParams||this.algorithmParams instanceof ty||(e.algorithmParams=this.algorithmParams.toJSON()),e}isEqual(e){return e instanceof uh&&this.algorithmId===e.algorithmId&&(this.algorithmParams?!!e.algorithmParams&&JSON.stringify(this.algorithmParams)===JSON.stringify(e.algorithmParams):!e.algorithmParams)}}uh.CLASS_NAME="AlgorithmIdentifier";let ug="altNames",up=[ug];class uC extends dX{constructor(e={}){super(),this.altNames=e2(e,ug,uC.defaultValues(ug)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e===ug?[]:super.defaultValues(e)}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new tQ({name:A.altNames||"",value:d7.schema()})]})}fromSchema(e){Ad(e,up);let A=tb(e,e,uC.schema({names:{altNames:ug}}));d$.assertSchema(A,this.className),ug in A.result&&(this.altNames=Array.from(A.result.altNames,e=>new d7({schema:e})))}toSchema(){return new A6({value:Array.from(this.altNames,e=>e.toSchema())})}toJSON(){return{altNames:Array.from(this.altNames,e=>e.toJSON())}}}uC.CLASS_NAME="AltName";let uf="type",uI="values",uw=[uf,uI];class um extends dX{constructor(e={}){super(),this.type=e2(e,uf,um.defaultValues(uf)),this.values=e2(e,uI,um.defaultValues(uI)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case uf:return"";case uI:return[];default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case uf:return""===A;case uI:return 0===A.length;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new A1({name:A.type||""}),new A3({name:A.setName||"",value:[new tQ({name:A.values||"",value:new ty})]})]})}fromSchema(e){Ad(e,uw);let A=tb(e,e,um.schema({names:{type:uf,values:uI}}));d$.assertSchema(A,this.className),this.type=A.result.type.valueBlock.toString(),this.values=A.result.values}toSchema(){return new A6({value:[new A1({value:this.type}),new A3({value:this.values})]})}toJSON(){return{type:this.type,values:Array.from(this.values,e=>e.toJSON())}}}um.CLASS_NAME="Attribute";let uE="notBeforeTime",uy="notAfterTime",uB=[uE,uy];class uQ extends dX{constructor(e={}){super(),this.notBeforeTime=e2(e,uE,uQ.defaultValues(uE)),this.notAfterTime=e2(e,uy,uQ.defaultValues(uy)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case uE:case uy:return new Date(0,0,0);default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new tC({name:A.notBeforeTime||""}),new tC({name:A.notAfterTime||""})]})}fromSchema(e){Ad(e,uB);let A=tb(e,e,uQ.schema({names:{notBeforeTime:uE,notAfterTime:uy}}));d$.assertSchema(A,this.className),this.notBeforeTime=A.result.notBeforeTime.toDate(),this.notAfterTime=A.result.notAfterTime.toDate()}toSchema(){return new A6({value:[new tC({valueDate:this.notBeforeTime}),new tC({valueDate:this.notAfterTime})]})}toJSON(){return{notBeforeTime:this.notBeforeTime,notAfterTime:this.notAfterTime}}}uQ.CLASS_NAME="AttCertValidityPeriod";let uD="names",ub="generalNames";class uS extends dX{constructor(e={}){super(),this.names=e2(e,uD,uS.defaultValues(uD)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return"names"===e?[]:super.defaultValues(e)}static schema(e={},A=!1){let t=e2(e,uD,{});return new A6({optional:A,name:t.blockName||"",value:[new tQ({name:t.generalNames||"",value:d7.schema()})]})}fromSchema(e){Ad(e,[uD,ub]);let A=tb(e,e,uS.schema({names:{blockName:uD,generalNames:ub}}));d$.assertSchema(A,this.className),this.names=Array.from(A.result.generalNames,e=>new d7({schema:e}))}toSchema(){return new A6({value:Array.from(this.names,e=>e.toSchema())})}toJSON(){return{names:Array.from(this.names,e=>e.toJSON())}}}uS.CLASS_NAME="GeneralNames";let uk="2.5.29.17",uR="2.5.29.18",uv="2.5.29.19",uG="2.5.29.28",uT="2.5.29.29",uM="2.5.29.30",uN="2.5.29.31",uO="2.5.29.46",uH="2.5.29.32",uU="2.5.29.32.0",u_="2.5.29.33",ux="2.5.29.35",uL="2.5.29.36",uP="1.3.6.1.5.5.7.1.1",uq="1.2.840.113549.1.7.1",uK="1.2.840.113549.1.7.2",uJ="1.2.840.113549.1.7.3",uF="1.2.840.113549.1.7.6",uj="1.2.840.113549.1.9.22.1",uz="1.2.840.113549.1.9.22.3",uY="1.2.840.113549.1.9.23.1",uZ="1.3.6.1.5.5.7.48.1.1",uV="keyIdentifier",uW="authorityCertIssuer",u$="authorityCertSerialNumber",uX=[uV,uW,u$];class u0 extends dX{constructor(e={}){super(),uV in e&&(this.keyIdentifier=e2(e,uV,u0.defaultValues(uV))),uW in e&&(this.authorityCertIssuer=e2(e,uW,u0.defaultValues(uW))),u$ in e&&(this.authorityCertSerialNumber=e2(e,u$,u0.defaultValues(u$))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case uV:return new Aj;case uW:return[];case u$:return new AW;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new AM({name:A.keyIdentifier||"",optional:!0,idBlock:{tagClass:3,tagNumber:0}}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new tQ({name:A.authorityCertIssuer||"",value:d7.schema()})]}),new AM({name:A.authorityCertSerialNumber||"",optional:!0,idBlock:{tagClass:3,tagNumber:2}})]})}fromSchema(e){Ad(e,uX);let A=tb(e,e,u0.schema({names:{keyIdentifier:uV,authorityCertIssuer:uW,authorityCertSerialNumber:u$}}));d$.assertSchema(A,this.className),uV in A.result&&(this.keyIdentifier=new Aj({valueHex:A.result.keyIdentifier.valueBlock.valueHex})),uW in A.result&&(this.authorityCertIssuer=Array.from(A.result.authorityCertIssuer,e=>new d7({schema:e}))),u$ in A.result&&(this.authorityCertSerialNumber=new AW({valueHex:A.result.authorityCertSerialNumber.valueBlock.valueHex}))}toSchema(){let e=[];return this.keyIdentifier&&e.push(new AM({idBlock:{tagClass:3,tagNumber:0},valueHex:this.keyIdentifier.valueBlock.valueHexView})),this.authorityCertIssuer&&e.push(new Ax({idBlock:{tagClass:3,tagNumber:1},value:Array.from(this.authorityCertIssuer,e=>e.toSchema())})),this.authorityCertSerialNumber&&e.push(new AM({idBlock:{tagClass:3,tagNumber:2},valueHex:this.authorityCertSerialNumber.valueBlock.valueHexView})),new A6({value:e})}toJSON(){let e={};return this.keyIdentifier&&(e.keyIdentifier=this.keyIdentifier.toJSON()),this.authorityCertIssuer&&(e.authorityCertIssuer=Array.from(this.authorityCertIssuer,e=>e.toJSON())),this.authorityCertSerialNumber&&(e.authorityCertSerialNumber=this.authorityCertSerialNumber.toJSON()),e}}u0.CLASS_NAME="AuthorityKeyIdentifier";let u1="pathLenConstraint";class u8 extends dX{constructor(e={}){super(),this.cA=e2(e,"cA",!1),u1 in e&&(this.pathLenConstraint=e2(e,u1,0)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return"cA"!==e&&super.defaultValues(e)}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new AJ({optional:!0,name:A.cA||""}),new AW({optional:!0,name:A.pathLenConstraint||""})]})}fromSchema(e){Ad(e,["cA",u1]);let A=tb(e,e,u8.schema({names:{cA:"cA",pathLenConstraint:u1}}));d$.assertSchema(A,this.className),"cA"in A.result&&(this.cA=A.result.cA.valueBlock.value),u1 in A.result&&(A.result.pathLenConstraint.valueBlock.isHexOnly?this.pathLenConstraint=A.result.pathLenConstraint:this.pathLenConstraint=A.result.pathLenConstraint.valueBlock.valueDec)}toSchema(){let e=[];return this.cA!==u8.defaultValues("cA")&&e.push(new AJ({value:this.cA})),u1 in this&&(this.pathLenConstraint instanceof AW?e.push(this.pathLenConstraint):e.push(new AW({value:this.pathLenConstraint}))),new A6({value:e})}toJSON(){let e={};return this.cA!==u8.defaultValues("cA")&&(e.cA=this.cA),u1 in this&&(this.pathLenConstraint instanceof AW?e.pathLenConstraint=this.pathLenConstraint.toJSON():e.pathLenConstraint=this.pathLenConstraint),e}}u8.CLASS_NAME="BasicConstraints";let u4="certificateIndex",u2="keyIndex";class u6 extends dX{constructor(e={}){super(),this.certificateIndex=e2(e,u4,u6.defaultValues(u4)),this.keyIndex=e2(e,u2,u6.defaultValues(u2)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case u4:case u2:return 0;default:return super.defaultValues(e)}}static schema(){return new AW}fromSchema(e){if(e.constructor.blockName()!==AW.blockName())throw Error("Object's schema was not verified against input data for CAVersion");let A=e.valueBlock.valueHex.slice(0),t=new Uint8Array(A);switch(!0){case A.byteLength<4:{let e=new ArrayBuffer(4);new Uint8Array(e).set(t,4-A.byteLength),A=e.slice(0)}break;case A.byteLength>4:{let e=new ArrayBuffer(4);new Uint8Array(e).set(t.slice(0,4)),A=e.slice(0)}}let r=A.slice(0,2),i=new Uint8Array(r),n=i[0];i[0]=i[1],i[1]=n;let a=new Uint16Array(r);this.keyIndex=a[0];let o=A.slice(2),s=new Uint8Array(o);n=s[0],s[0]=s[1],s[1]=n;let l=new Uint16Array(o);this.certificateIndex=l[0]}toSchema(){let e=new ArrayBuffer(2);new Uint16Array(e)[0]=this.certificateIndex;let A=new Uint8Array(e),t=A[0];A[0]=A[1],A[1]=t;let r=new ArrayBuffer(2);new Uint16Array(r)[0]=this.keyIndex;let i=new Uint8Array(r);return t=i[0],i[0]=i[1],i[1]=t,new AW({valueHex:e9(r,e)})}toJSON(){return{certificateIndex:this.certificateIndex,keyIndex:this.keyIndex}}}u6.CLASS_NAME="CAVersion";let u3="policyQualifierId",u5="qualifier",u9=[u3,u5];class u7 extends dX{constructor(e={}){super(),this.policyQualifierId=e2(e,u3,u7.defaultValues(u3)),this.qualifier=e2(e,u5,u7.defaultValues(u5)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case u3:return"";case u5:return new ty;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new A1({name:A.policyQualifierId||""}),new ty({name:A.qualifier||""})]})}fromSchema(e){Ad(e,u9);let A=tb(e,e,u7.schema({names:{policyQualifierId:u3,qualifier:u5}}));d$.assertSchema(A,this.className),this.policyQualifierId=A.result.policyQualifierId.valueBlock.toString(),this.qualifier=A.result.qualifier}toSchema(){return new A6({value:[new A1({value:this.policyQualifierId}),this.qualifier]})}toJSON(){return{policyQualifierId:this.policyQualifierId,qualifier:this.qualifier.toJSON()}}}u7.CLASS_NAME="PolicyQualifierInfo";let ce="policyIdentifier",cA="policyQualifiers",ct=[ce,cA];class cr extends dX{constructor(e={}){super(),this.policyIdentifier=e2(e,ce,cr.defaultValues(ce)),cA in e&&(this.policyQualifiers=e2(e,cA,cr.defaultValues(cA))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case ce:return"";case cA:return[];default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new A1({name:A.policyIdentifier||""}),new A6({optional:!0,value:[new tQ({name:A.policyQualifiers||"",value:u7.schema()})]})]})}fromSchema(e){Ad(e,ct);let A=tb(e,e,cr.schema({names:{policyIdentifier:ce,policyQualifiers:cA}}));d$.assertSchema(A,this.className),this.policyIdentifier=A.result.policyIdentifier.valueBlock.toString(),cA in A.result&&(this.policyQualifiers=Array.from(A.result.policyQualifiers,e=>new u7({schema:e})))}toSchema(){let e=[];return e.push(new A1({value:this.policyIdentifier})),this.policyQualifiers&&e.push(new A6({value:Array.from(this.policyQualifiers,e=>e.toSchema())})),new A6({value:e})}toJSON(){let e={policyIdentifier:this.policyIdentifier};return this.policyQualifiers&&(e.policyQualifiers=Array.from(this.policyQualifiers,e=>e.toJSON())),e}}cr.CLASS_NAME="PolicyInformation";let ci="certificatePolicies",cn=[ci];class ca extends dX{constructor(e={}){super(),this.certificatePolicies=e2(e,ci,ca.defaultValues(ci)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e===ci?[]:super.defaultValues(e)}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new tQ({name:A.certificatePolicies||"",value:cr.schema()})]})}fromSchema(e){Ad(e,cn);let A=tb(e,e,ca.schema({names:{certificatePolicies:ci}}));d$.assertSchema(A,this.className),this.certificatePolicies=Array.from(A.result.certificatePolicies,e=>new cr({schema:e}))}toSchema(){return new A6({value:Array.from(this.certificatePolicies,e=>e.toSchema())})}toJSON(){return{certificatePolicies:Array.from(this.certificatePolicies,e=>e.toJSON())}}}ca.CLASS_NAME="CertificatePolicies";let co="templateID",cs="templateMajorVersion",cl="templateMinorVersion",cd=[co,cs,cl];class cu extends dX{constructor(e={}){super(),this.templateID=e2(e,co,cu.defaultValues(co)),cs in e&&(this.templateMajorVersion=e2(e,cs,cu.defaultValues(cs))),cl in e&&(this.templateMinorVersion=e2(e,cl,cu.defaultValues(cl))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case co:return"";case cs:case cl:return 0;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new A1({name:A.templateID||""}),new AW({name:A.templateMajorVersion||"",optional:!0}),new AW({name:A.templateMinorVersion||"",optional:!0})]})}fromSchema(e){Ad(e,cd);let A=tb(e,e,cu.schema({names:{templateID:co,templateMajorVersion:cs,templateMinorVersion:cl}}));d$.assertSchema(A,this.className),this.templateID=A.result.templateID.valueBlock.toString(),cs in A.result&&(this.templateMajorVersion=A.result.templateMajorVersion.valueBlock.valueDec),cl in A.result&&(this.templateMinorVersion=A.result.templateMinorVersion.valueBlock.valueDec)}toSchema(){let e=[];return e.push(new A1({value:this.templateID})),cs in this&&e.push(new AW({value:this.templateMajorVersion})),cl in this&&e.push(new AW({value:this.templateMinorVersion})),new A6({value:e})}toJSON(){let e={templateID:this.templateID};return cs in this&&(e.templateMajorVersion=this.templateMajorVersion),cl in this&&(e.templateMinorVersion=this.templateMinorVersion),e}}let cc="distributionPoint",ch="distributionPointNames",cg="reasons",cp="cRLIssuer",cC="cRLIssuerNames",cf=[cc,ch,cg,cp,cC];class cI extends dX{constructor(e={}){super(),cc in e&&(this.distributionPoint=e2(e,cc,cI.defaultValues(cc))),cg in e&&(this.reasons=e2(e,cg,cI.defaultValues(cg))),cp in e&&(this.cRLIssuer=e2(e,cp,cI.defaultValues(cp))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case cc:return[];case cg:return new AY;case cp:return[];default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new tB({value:[new Ax({name:A.distributionPoint||"",optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new tQ({name:A.distributionPointNames||"",value:d7.schema()})]}),new Ax({name:A.distributionPoint||"",optional:!0,idBlock:{tagClass:3,tagNumber:1},value:d3.schema().valueBlock.value})]})]}),new AM({name:A.reasons||"",optional:!0,idBlock:{tagClass:3,tagNumber:1}}),new Ax({name:A.cRLIssuer||"",optional:!0,idBlock:{tagClass:3,tagNumber:2},value:[new tQ({name:A.cRLIssuerNames||"",value:d7.schema()})]})]})}fromSchema(e){Ad(e,cf);let A=tb(e,e,cI.schema({names:{distributionPoint:cc,distributionPointNames:ch,reasons:cg,cRLIssuer:cp,cRLIssuerNames:cC}}));d$.assertSchema(A,this.className),cc in A.result&&(0===A.result.distributionPoint.idBlock.tagNumber&&(this.distributionPoint=Array.from(A.result.distributionPointNames,e=>new d7({schema:e}))),1===A.result.distributionPoint.idBlock.tagNumber&&(this.distributionPoint=new d3({schema:new A6({value:A.result.distributionPoint.valueBlock.value})}))),cg in A.result&&(this.reasons=new AY({valueHex:A.result.reasons.valueBlock.valueHex})),cp in A.result&&(this.cRLIssuer=Array.from(A.result.cRLIssuerNames,e=>new d7({schema:e})))}toSchema(){let e=[];if(this.distributionPoint){let A;A=new Ax(this.distributionPoint instanceof Array?{idBlock:{tagClass:3,tagNumber:0},value:Array.from(this.distributionPoint,e=>e.toSchema())}:{idBlock:{tagClass:3,tagNumber:1},value:[this.distributionPoint.toSchema()]}),e.push(new Ax({idBlock:{tagClass:3,tagNumber:0},value:[A]}))}return this.reasons&&e.push(new AM({idBlock:{tagClass:3,tagNumber:1},valueHex:this.reasons.valueBlock.valueHexView})),this.cRLIssuer&&e.push(new Ax({idBlock:{tagClass:3,tagNumber:2},value:Array.from(this.cRLIssuer,e=>e.toSchema())})),new A6({value:e})}toJSON(){let e={};return this.distributionPoint&&(this.distributionPoint instanceof Array?e.distributionPoint=Array.from(this.distributionPoint,e=>e.toJSON()):e.distributionPoint=this.distributionPoint.toJSON()),this.reasons&&(e.reasons=this.reasons.toJSON()),this.cRLIssuer&&(e.cRLIssuer=Array.from(this.cRLIssuer,e=>e.toJSON())),e}}cI.CLASS_NAME="DistributionPoint";let cw="distributionPoints",cm=[cw];class cE extends dX{constructor(e={}){super(),this.distributionPoints=e2(e,cw,cE.defaultValues(cw)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e===cw?[]:super.defaultValues(e)}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new tQ({name:A.distributionPoints||"",value:cI.schema()})]})}fromSchema(e){Ad(e,cm);let A=tb(e,e,cE.schema({names:{distributionPoints:cw}}));d$.assertSchema(A,this.className),this.distributionPoints=Array.from(A.result.distributionPoints,e=>new cI({schema:e}))}toSchema(){return new A6({value:Array.from(this.distributionPoints,e=>e.toSchema())})}toJSON(){return{distributionPoints:Array.from(this.distributionPoints,e=>e.toJSON())}}}cE.CLASS_NAME="CRLDistributionPoints";let cy="keyPurposes",cB=[cy];class cQ extends dX{constructor(e={}){super(),this.keyPurposes=e2(e,cy,cQ.defaultValues(cy)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e===cy?[]:super.defaultValues(e)}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new tQ({name:A.keyPurposes||"",value:new A1})]})}fromSchema(e){Ad(e,cB);let A=tb(e,e,cQ.schema({names:{keyPurposes:cy}}));d$.assertSchema(A,this.className),this.keyPurposes=Array.from(A.result.keyPurposes,e=>e.valueBlock.toString())}toSchema(){return new A6({value:Array.from(this.keyPurposes,e=>new A1({value:e}))})}toJSON(){return{keyPurposes:Array.from(this.keyPurposes)}}}cQ.CLASS_NAME="ExtKeyUsage";let cD="accessDescriptions";class cb extends dX{constructor(e={}){super(),this.accessDescriptions=e2(e,cD,cb.defaultValues(cD)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e===cD?[]:super.defaultValues(e)}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new tQ({name:A.accessDescriptions||"",value:ur.schema()})]})}fromSchema(e){Ad(e,[cD]);let A=tb(e,e,cb.schema({names:{accessDescriptions:cD}}));d$.assertSchema(A,this.className),this.accessDescriptions=Array.from(A.result.accessDescriptions,e=>new ur({schema:e}))}toSchema(){return new A6({value:Array.from(this.accessDescriptions,e=>e.toSchema())})}toJSON(){return{accessDescriptions:Array.from(this.accessDescriptions,e=>e.toJSON())}}}cb.CLASS_NAME="InfoAccess";let cS="distributionPoint",ck="distributionPointNames",cR="onlyContainsUserCerts",cv="onlyContainsCACerts",cG="onlySomeReasons",cT="indirectCRL",cM="onlyContainsAttributeCerts",cN=[cS,ck,cR,cv,cG,cT,cM];class cO extends dX{constructor(e={}){super(),cS in e&&(this.distributionPoint=e2(e,cS,cO.defaultValues(cS))),this.onlyContainsUserCerts=e2(e,cR,cO.defaultValues(cR)),this.onlyContainsCACerts=e2(e,cv,cO.defaultValues(cv)),cG in e&&(this.onlySomeReasons=e2(e,cG,cO.defaultValues(cG))),this.indirectCRL=e2(e,cT,cO.defaultValues(cT)),this.onlyContainsAttributeCerts=e2(e,cM,cO.defaultValues(cM)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case cS:return[];case cR:case cv:return!1;case cG:return 0;case cT:case cM:return!1;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new tB({value:[new Ax({name:A.distributionPoint||"",idBlock:{tagClass:3,tagNumber:0},value:[new tQ({name:A.distributionPointNames||"",value:d7.schema()})]}),new Ax({name:A.distributionPoint||"",idBlock:{tagClass:3,tagNumber:1},value:d3.schema().valueBlock.value})]})]}),new AM({name:A.onlyContainsUserCerts||"",optional:!0,idBlock:{tagClass:3,tagNumber:1}}),new AM({name:A.onlyContainsCACerts||"",optional:!0,idBlock:{tagClass:3,tagNumber:2}}),new AM({name:A.onlySomeReasons||"",optional:!0,idBlock:{tagClass:3,tagNumber:3}}),new AM({name:A.indirectCRL||"",optional:!0,idBlock:{tagClass:3,tagNumber:4}}),new AM({name:A.onlyContainsAttributeCerts||"",optional:!0,idBlock:{tagClass:3,tagNumber:5}})]})}fromSchema(e){Ad(e,cN);let A=tb(e,e,cO.schema({names:{distributionPoint:cS,distributionPointNames:ck,onlyContainsUserCerts:cR,onlyContainsCACerts:cv,onlySomeReasons:cG,indirectCRL:cT,onlyContainsAttributeCerts:cM}}));if(d$.assertSchema(A,this.className),cS in A.result)switch(!0){case 0===A.result.distributionPoint.idBlock.tagNumber:this.distributionPoint=Array.from(A.result.distributionPointNames,e=>new d7({schema:e}));break;case 1===A.result.distributionPoint.idBlock.tagNumber:this.distributionPoint=new d3({schema:new A6({value:A.result.distributionPoint.valueBlock.value})});break;default:throw Error("Unknown tagNumber for distributionPoint: {$asn1.result.distributionPoint.idBlock.tagNumber}")}if(cR in A.result){let e=new Uint8Array(A.result.onlyContainsUserCerts.valueBlock.valueHex);this.onlyContainsUserCerts=0!==e[0]}if(cv in A.result){let e=new Uint8Array(A.result.onlyContainsCACerts.valueBlock.valueHex);this.onlyContainsCACerts=0!==e[0]}if(cG in A.result){let e=new Uint8Array(A.result.onlySomeReasons.valueBlock.valueHex);this.onlySomeReasons=e[0]}if(cT in A.result){let e=new Uint8Array(A.result.indirectCRL.valueBlock.valueHex);this.indirectCRL=0!==e[0]}if(cM in A.result){let e=new Uint8Array(A.result.onlyContainsAttributeCerts.valueBlock.valueHex);this.onlyContainsAttributeCerts=0!==e[0]}}toSchema(){let e=[];if(this.distributionPoint){let A;this.distributionPoint instanceof Array?A=new Ax({idBlock:{tagClass:3,tagNumber:0},value:Array.from(this.distributionPoint,e=>e.toSchema())}):((A=this.distributionPoint.toSchema()).idBlock.tagClass=3,A.idBlock.tagNumber=1),e.push(new Ax({idBlock:{tagClass:3,tagNumber:0},value:[A]}))}if(this.onlyContainsUserCerts!==cO.defaultValues(cR)&&e.push(new AM({idBlock:{tagClass:3,tagNumber:1},valueHex:new Uint8Array([255]).buffer})),this.onlyContainsCACerts!==cO.defaultValues(cv)&&e.push(new AM({idBlock:{tagClass:3,tagNumber:2},valueHex:new Uint8Array([255]).buffer})),void 0!==this.onlySomeReasons){let A=new ArrayBuffer(1);new Uint8Array(A)[0]=this.onlySomeReasons,e.push(new AM({idBlock:{tagClass:3,tagNumber:3},valueHex:A}))}return this.indirectCRL!==cO.defaultValues(cT)&&e.push(new AM({idBlock:{tagClass:3,tagNumber:4},valueHex:new Uint8Array([255]).buffer})),this.onlyContainsAttributeCerts!==cO.defaultValues(cM)&&e.push(new AM({idBlock:{tagClass:3,tagNumber:5},valueHex:new Uint8Array([255]).buffer})),new A6({value:e})}toJSON(){let e={};return this.distributionPoint&&(this.distributionPoint instanceof Array?e.distributionPoint=Array.from(this.distributionPoint,e=>e.toJSON()):e.distributionPoint=this.distributionPoint.toJSON()),this.onlyContainsUserCerts!==cO.defaultValues(cR)&&(e.onlyContainsUserCerts=this.onlyContainsUserCerts),this.onlyContainsCACerts!==cO.defaultValues(cv)&&(e.onlyContainsCACerts=this.onlyContainsCACerts),cG in this&&(e.onlySomeReasons=this.onlySomeReasons),this.indirectCRL!==cO.defaultValues(cT)&&(e.indirectCRL=this.indirectCRL),this.onlyContainsAttributeCerts!==cO.defaultValues(cM)&&(e.onlyContainsAttributeCerts=this.onlyContainsAttributeCerts),e}}cO.CLASS_NAME="IssuingDistributionPoint";let cH="base",cU="minimum",c_="maximum",cx=[cH,cU,c_];class cL extends dX{constructor(e={}){super(),this.base=e2(e,cH,cL.defaultValues(cH)),this.minimum=e2(e,cU,cL.defaultValues(cU)),c_ in e&&(this.maximum=e2(e,c_,cL.defaultValues(c_))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case cH:return new d7;case cU:case c_:return 0;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[d7.schema(A.base||{}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new AW({name:A.minimum||""})]}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new AW({name:A.maximum||""})]})]})}fromSchema(e){Ad(e,cx);let A=tb(e,e,cL.schema({names:{base:{names:{blockName:cH}},minimum:cU,maximum:c_}}));d$.assertSchema(A,this.className),this.base=new d7({schema:A.result.base}),cU in A.result&&(A.result.minimum.valueBlock.isHexOnly?this.minimum=A.result.minimum:this.minimum=A.result.minimum.valueBlock.valueDec),c_ in A.result&&(A.result.maximum.valueBlock.isHexOnly?this.maximum=A.result.maximum:this.maximum=A.result.maximum.valueBlock.valueDec)}toSchema(){let e=[];if(e.push(this.base.toSchema()),0!==this.minimum){let A=0;A=this.minimum instanceof AW?this.minimum:new AW({value:this.minimum}),e.push(new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[A]}))}if(c_ in this){let A=0;A=this.maximum instanceof AW?this.maximum:new AW({value:this.maximum}),e.push(new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[A]}))}return new A6({value:e})}toJSON(){let e={base:this.base.toJSON()};return 0!==this.minimum&&("number"==typeof this.minimum?e.minimum=this.minimum:e.minimum=this.minimum.toJSON()),void 0!==this.maximum&&("number"==typeof this.maximum?e.maximum=this.maximum:e.maximum=this.maximum.toJSON()),e}}cL.CLASS_NAME="GeneralSubtree";let cP="permittedSubtrees",cq="excludedSubtrees",cK=[cP,cq];class cJ extends dX{constructor(e={}){super(),cP in e&&(this.permittedSubtrees=e2(e,cP,cJ.defaultValues(cP))),cq in e&&(this.excludedSubtrees=e2(e,cq,cJ.defaultValues(cq))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case cP:case cq:return[];default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new tQ({name:A.permittedSubtrees||"",value:cL.schema()})]}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new tQ({name:A.excludedSubtrees||"",value:cL.schema()})]})]})}fromSchema(e){Ad(e,cK);let A=tb(e,e,cJ.schema({names:{permittedSubtrees:cP,excludedSubtrees:cq}}));d$.assertSchema(A,this.className),cP in A.result&&(this.permittedSubtrees=Array.from(A.result.permittedSubtrees,e=>new cL({schema:e}))),cq in A.result&&(this.excludedSubtrees=Array.from(A.result.excludedSubtrees,e=>new cL({schema:e})))}toSchema(){let e=[];return this.permittedSubtrees&&e.push(new Ax({idBlock:{tagClass:3,tagNumber:0},value:Array.from(this.permittedSubtrees,e=>e.toSchema())})),this.excludedSubtrees&&e.push(new Ax({idBlock:{tagClass:3,tagNumber:1},value:Array.from(this.excludedSubtrees,e=>e.toSchema())})),new A6({value:e})}toJSON(){let e={};return this.permittedSubtrees&&(e.permittedSubtrees=Array.from(this.permittedSubtrees,e=>e.toJSON())),this.excludedSubtrees&&(e.excludedSubtrees=Array.from(this.excludedSubtrees,e=>e.toJSON())),e}}cJ.CLASS_NAME="NameConstraints";let cF="requireExplicitPolicy",cj="inhibitPolicyMapping",cz=[cF,cj];class cY extends dX{constructor(e={}){super(),cF in e&&(this.requireExplicitPolicy=e2(e,cF,cY.defaultValues(cF))),cj in e&&(this.inhibitPolicyMapping=e2(e,cj,cY.defaultValues(cj))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case cF:case cj:return 0;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new AM({name:A.requireExplicitPolicy||"",optional:!0,idBlock:{tagClass:3,tagNumber:0}}),new AM({name:A.inhibitPolicyMapping||"",optional:!0,idBlock:{tagClass:3,tagNumber:1}})]})}fromSchema(e){Ad(e,cz);let A=tb(e,e,cY.schema({names:{requireExplicitPolicy:cF,inhibitPolicyMapping:cj}}));if(d$.assertSchema(A,this.className),cF in A.result){let e=A.result.requireExplicitPolicy;e.idBlock.tagClass=1,e.idBlock.tagNumber=2;let t=AU(e.toBER(!1));d$.assert(t,"Integer"),this.requireExplicitPolicy=t.result.valueBlock.valueDec}if(cj in A.result){let e=A.result.inhibitPolicyMapping;e.idBlock.tagClass=1,e.idBlock.tagNumber=2;let t=AU(e.toBER(!1));d$.assert(t,"Integer"),this.inhibitPolicyMapping=t.result.valueBlock.valueDec}}toSchema(){let e=[];if(cF in this){let A=new AW({value:this.requireExplicitPolicy});A.idBlock.tagClass=3,A.idBlock.tagNumber=0,e.push(A)}if(cj in this){let A=new AW({value:this.inhibitPolicyMapping});A.idBlock.tagClass=3,A.idBlock.tagNumber=1,e.push(A)}return new A6({value:e})}toJSON(){let e={};return cF in this&&(e.requireExplicitPolicy=this.requireExplicitPolicy),cj in this&&(e.inhibitPolicyMapping=this.inhibitPolicyMapping),e}}cY.CLASS_NAME="PolicyConstraints";let cZ="issuerDomainPolicy",cV="subjectDomainPolicy",cW=[cZ,cV];class c$ extends dX{constructor(e={}){super(),this.issuerDomainPolicy=e2(e,cZ,c$.defaultValues(cZ)),this.subjectDomainPolicy=e2(e,cV,c$.defaultValues(cV)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case cZ:case cV:return"";default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new A1({name:A.issuerDomainPolicy||""}),new A1({name:A.subjectDomainPolicy||""})]})}fromSchema(e){Ad(e,cW);let A=tb(e,e,c$.schema({names:{issuerDomainPolicy:cZ,subjectDomainPolicy:cV}}));d$.assertSchema(A,this.className),this.issuerDomainPolicy=A.result.issuerDomainPolicy.valueBlock.toString(),this.subjectDomainPolicy=A.result.subjectDomainPolicy.valueBlock.toString()}toSchema(){return new A6({value:[new A1({value:this.issuerDomainPolicy}),new A1({value:this.subjectDomainPolicy})]})}toJSON(){return{issuerDomainPolicy:this.issuerDomainPolicy,subjectDomainPolicy:this.subjectDomainPolicy}}}c$.CLASS_NAME="PolicyMapping";let cX="mappings",c0=[cX];class c1 extends dX{constructor(e={}){super(),this.mappings=e2(e,cX,c1.defaultValues(cX)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e===cX?[]:super.defaultValues(e)}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new tQ({name:A.mappings||"",value:c$.schema()})]})}fromSchema(e){Ad(e,c0);let A=tb(e,e,c1.schema({names:{mappings:cX}}));d$.assertSchema(A,this.className),this.mappings=Array.from(A.result.mappings,e=>new c$({schema:e}))}toSchema(){return new A6({value:Array.from(this.mappings,e=>e.toSchema())})}toJSON(){return{mappings:Array.from(this.mappings,e=>e.toJSON())}}}c1.CLASS_NAME="PolicyMappings";let c8="notBefore",c4="notAfter",c2=[c8,c4];class c6 extends dX{constructor(e={}){super(),c8 in e&&(this.notBefore=e2(e,c8,c6.defaultValues(c8))),c4 in e&&(this.notAfter=e2(e,c4,c6.defaultValues(c4))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case c8:case c4:return new Date;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new AM({name:A.notBefore||"",optional:!0,idBlock:{tagClass:3,tagNumber:0}}),new AM({name:A.notAfter||"",optional:!0,idBlock:{tagClass:3,tagNumber:1}})]})}fromSchema(e){Ad(e,c2);let A=tb(e,e,c6.schema({names:{notBefore:c8,notAfter:c4}}));if(d$.assertSchema(A,this.className),c8 in A.result){let e=new tC;e.fromBuffer(A.result.notBefore.valueBlock.valueHex),this.notBefore=e.toDate()}if(c4 in A.result){let e=new tC({valueHex:A.result.notAfter.valueBlock.valueHex});e.fromBuffer(A.result.notAfter.valueBlock.valueHex),this.notAfter=e.toDate()}}toSchema(){let e=[];return c8 in this&&e.push(new AM({idBlock:{tagClass:3,tagNumber:0},valueHex:new tC({valueDate:this.notBefore}).valueBlock.valueHexView})),c4 in this&&e.push(new AM({idBlock:{tagClass:3,tagNumber:1},valueHex:new tC({valueDate:this.notAfter}).valueBlock.valueHexView})),new A6({value:e})}toJSON(){let e={};return this.notBefore&&(e.notBefore=this.notBefore),this.notAfter&&(e.notAfter=this.notAfter),e}}c6.CLASS_NAME="PrivateKeyUsagePeriod";let c3="type",c5="values",c9=["id",c3],c7=[c5];class he extends dX{constructor(e={}){super(),this.id=e2(e,"id",he.defaultValues("id")),c3 in e&&(this.type=e2(e,c3,he.defaultValues(c3))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case"id":return"";case c3:return new Aq;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case"id":return""===A;case c3:return A instanceof Aq;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new A1({name:A.id||""}),new ty({name:A.type||"",optional:!0})]})}fromSchema(e){Ad(e,c9);let A=tb(e,e,he.schema({names:{id:"id",type:c3}}));d$.assertSchema(A,this.className),this.id=A.result.id.valueBlock.toString(),c3 in A.result&&(this.type=A.result.type)}toSchema(){let e=[new A1({value:this.id})];return c3 in this&&e.push(this.type),new A6({value:e})}toJSON(){let e={id:this.id};return this.type&&(e.type=this.type.toJSON()),e}}he.CLASS_NAME="QCStatement";class hA extends dX{constructor(e={}){super(),this.values=e2(e,c5,hA.defaultValues(c5)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e===c5?[]:super.defaultValues(e)}static compareWithDefault(e,A){return e===c5?0===A.length:super.defaultValues(e)}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new tQ({name:A.values||"",value:he.schema(A.value||{})})]})}fromSchema(e){Ad(e,c7);let A=tb(e,e,hA.schema({names:{values:c5}}));d$.assertSchema(A,this.className),this.values=Array.from(A.result.values,e=>new he({schema:e}))}toSchema(){return new A6({value:Array.from(this.values,e=>e.toSchema())})}toJSON(){return{values:Array.from(this.values,e=>e.toJSON())}}}hA.CLASS_NAME="QCStatements";class ht{static register(e,A,t){this.namedCurves[e.toLowerCase()]=this.namedCurves[A]={name:e,id:A,size:t}}static find(e){return this.namedCurves[e.toLowerCase()]||null}}ht.namedCurves={},ht.register("P-256","1.2.840.10045.3.1.7",32),ht.register("P-384","1.3.132.0.34",48),ht.register("P-521","1.3.132.0.35",66),ht.register("brainpoolP256r1","1.3.36.3.3.2.8.1.1.7",32),ht.register("brainpoolP384r1","1.3.36.3.3.2.8.1.1.11",48),ht.register("brainpoolP512r1","1.3.36.3.3.2.8.1.1.13",64);let hr="namedCurve";class hi extends dX{constructor(e={}){super(),this.x=e2(e,"x",hi.defaultValues("x")),this.y=e2(e,"y",hi.defaultValues("y")),this.namedCurve=e2(e,hr,hi.defaultValues(hr)),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case"x":case"y":return dZ;case hr:return"";default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case"x":case"y":return A instanceof ArrayBuffer&&AA(A,hi.defaultValues(e));case hr:return"string"==typeof A&&A===hi.defaultValues(e);default:return super.defaultValues(e)}}static schema(){return new tD}fromSchema(e){let A=eV.toUint8Array(e);if(4!==A[0])throw Error("Object's schema was not verified against input data for ECPublicKey");let t=ht.find(this.namedCurve);if(!t)throw Error(`Incorrect curve OID: ${this.namedCurve}`);let r=t.size;if(A.byteLength!==2*r+1)throw Error("Object's schema was not verified against input data for ECPublicKey");this.namedCurve=t.name,this.x=A.slice(1,r+1).buffer,this.y=A.slice(1+r,2*r+1).buffer}toSchema(){return new tD({data:e9(new Uint8Array([4]).buffer,this.x,this.y)})}toJSON(){let e=ht.find(this.namedCurve);return{crv:e?e.name:this.namedCurve,x:An(Ao(this.x),!0,!0,!1),y:An(Ao(this.y),!0,!0,!1)}}fromJSON(e){dW.assert("json",e,"crv","x","y");let A=0,t=ht.find(e.crv);t&&(this.namedCurve=t.id,A=t.size);let r=As(Aa(e.x,!0));if(r.byteLength<A){this.x=new ArrayBuffer(A);let e=new Uint8Array(this.x),t=new Uint8Array(r);e.set(t,1)}else this.x=r.slice(0,A);let i=As(Aa(e.y,!0));if(i.byteLength<A){this.y=new ArrayBuffer(A);let e=new Uint8Array(this.y),t=new Uint8Array(i);e.set(t,1)}else this.y=i.slice(0,A)}}hi.CLASS_NAME="ECPublicKey";let hn="modulus",ha="publicExponent",ho=[hn,ha];class hs extends dX{constructor(e={}){super(),this.modulus=e2(e,hn,hs.defaultValues(hn)),this.publicExponent=e2(e,ha,hs.defaultValues(ha)),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case hn:case ha:return new AW;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new AW({name:A.modulus||""}),new AW({name:A.publicExponent||""})]})}fromSchema(e){Ad(e,ho);let A=tb(e,e,hs.schema({names:{modulus:hn,publicExponent:ha}}));d$.assertSchema(A,this.className),this.modulus=A.result.modulus.convertFromDER(256),this.publicExponent=A.result.publicExponent}toSchema(){return new A6({value:[this.modulus.convertToDER(),this.publicExponent]})}toJSON(){return{n:e4.ToBase64Url(this.modulus.valueBlock.valueHexView),e:e4.ToBase64Url(this.publicExponent.valueBlock.valueHexView)}}fromJSON(e){let A,t,r;dW.assert("json",e,"n","e");let i=As(Aa(e.n,!0));this.modulus=new AW({valueHex:i.slice(0,Math.pow(2,(t=Math.floor(A=Math.log(i.byteLength)/Al),t===(r=Math.round(A))?t:r)))}),this.publicExponent=new AW({valueHex:As(Aa(e.e,!0)).slice(0,3)})}}hs.CLASS_NAME="RSAPublicKey";let hl="algorithm",hd="subjectPublicKey",hu=[hl,hd];class hc extends dX{get parsedKey(){if(void 0===this._parsedKey){switch(this.algorithm.algorithmId){case"1.2.840.10045.2.1":if("algorithmParams"in this.algorithm&&this.algorithm.algorithmParams.constructor.blockName()===A1.blockName())try{this._parsedKey=new hi({namedCurve:this.algorithm.algorithmParams.valueBlock.toString(),schema:this.subjectPublicKey.valueBlock.valueHexView})}catch{}break;case"1.2.840.113549.1.1.1":case"1.2.840.113549.1.1.10":{let e=AU(this.subjectPublicKey.valueBlock.valueHexView);if(-1!==e.offset)try{this._parsedKey=new hs({schema:e.result})}catch{}}}this._parsedKey||(this._parsedKey=null)}return this._parsedKey||void 0}set parsedKey(e){this._parsedKey=e}constructor(e={}){super(),this.algorithm=e2(e,hl,hc.defaultValues(hl)),this.subjectPublicKey=e2(e,hd,hc.defaultValues(hd));const A=e2(e,"parsedKey",null);A&&(this.parsedKey=A),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case hl:return new uh;case hd:return new AY;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[uh.schema(A.algorithm||{}),new AY({name:A.subjectPublicKey||""})]})}fromSchema(e){Ad(e,hu);let A=tb(e,e,hc.schema({names:{algorithm:{names:{blockName:hl}},subjectPublicKey:hd}}));d$.assertSchema(A,this.className),this.algorithm=new uh({schema:A.result.algorithm}),this.subjectPublicKey=A.result.subjectPublicKey}toSchema(){return new A6({value:[this.algorithm.toSchema(),this.subjectPublicKey]})}toJSON(){if(!this.parsedKey)return{algorithm:this.algorithm.toJSON(),subjectPublicKey:this.subjectPublicKey.toJSON()};let e={};switch(this.algorithm.algorithmId){case"1.2.840.10045.2.1":e.kty="EC";break;case"1.2.840.113549.1.1.1":case"1.2.840.113549.1.1.10":e.kty="RSA"}return Object.assign(e,this.parsedKey.toJSON()),e}fromJSON(e){if("kty"in e){switch(e.kty.toUpperCase()){case"EC":this.parsedKey=new hi({json:e}),this.algorithm=new uh({algorithmId:"1.2.840.10045.2.1",algorithmParams:new A1({value:this.parsedKey.namedCurve})});break;case"RSA":this.parsedKey=new hs({json:e}),this.algorithm=new uh({algorithmId:"1.2.840.113549.1.1.1",algorithmParams:new Aq});break;default:throw Error(`Invalid value for "kty" parameter: ${e.kty}`)}this.subjectPublicKey=new AY({valueHex:this.parsedKey.toSchema().toBER(!1)})}}async importKey(e,A=gn(!0)){try{if(!e)throw Error("Need to provide publicKey input parameter");let t=await A.exportKey("spki",e),r=AU(t);try{this.fromSchema(r.result)}catch{throw Error("Error during initializing object from schema")}}catch(A){let e=A instanceof Error?A.message:`${A}`;throw Error(`Error during exporting public key: ${e}`)}}}hc.CLASS_NAME="PublicKeyInfo";let hh="version",hg="privateKey",hp="namedCurve",hC="publicKey",hf=[hh,hg,hp,hC];class hI extends dX{constructor(e={}){super(),this.version=e2(e,hh,hI.defaultValues(hh)),this.privateKey=e2(e,hg,hI.defaultValues(hg)),hp in e&&(this.namedCurve=e2(e,hp,hI.defaultValues(hp))),hC in e&&(this.publicKey=e2(e,hC,hI.defaultValues(hC))),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case hh:return 1;case hg:return new Aj;case hp:return"";case hC:return new hi;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case hh:return A===hI.defaultValues(e);case hg:return A.isEqual(hI.defaultValues(e));case hp:return""===A;case hC:return hi.compareWithDefault(hp,A.namedCurve)&&hi.compareWithDefault("x",A.x)&&hi.compareWithDefault("y",A.y);default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new AW({name:A.version||""}),new Aj({name:A.privateKey||""}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new A1({name:A.namedCurve||""})]}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new AY({name:A.publicKey||""})]})]})}fromSchema(e){Ad(e,hf);let A=tb(e,e,hI.schema({names:{version:hh,privateKey:hg,namedCurve:hp,publicKey:hC}}));if(d$.assertSchema(A,this.className),this.version=A.result.version.valueBlock.valueDec,this.privateKey=A.result.privateKey,hp in A.result&&(this.namedCurve=A.result.namedCurve.valueBlock.toString()),hC in A.result){let e={schema:A.result.publicKey.valueBlock.valueHex};hp in this&&(e.namedCurve=this.namedCurve),this.publicKey=new hi(e)}}toSchema(){let e=[new AW({value:this.version}),this.privateKey];return this.namedCurve&&e.push(new Ax({idBlock:{tagClass:3,tagNumber:0},value:[new A1({value:this.namedCurve})]})),this.publicKey&&e.push(new Ax({idBlock:{tagClass:3,tagNumber:1},value:[new AY({valueHex:this.publicKey.toSchema().toBER(!1)})]})),new A6({value:e})}toJSON(){if(!this.namedCurve||hI.compareWithDefault(hp,this.namedCurve))throw Error('Not enough information for making JSON: absent "namedCurve" value');let e=ht.find(this.namedCurve),A={crv:e?e.name:this.namedCurve,d:e4.ToBase64Url(this.privateKey.valueBlock.valueHexView)};if(this.publicKey){let e=this.publicKey.toJSON();A.x=e.x,A.y=e.y}return A}fromJSON(e){dW.assert("json",e,"crv","d");let A=0,t=ht.find(e.crv);t&&(this.namedCurve=t.id,A=t.size);let r=e4.FromBase64Url(e.d);if(r.byteLength<A){let e=new ArrayBuffer(A),t=new Uint8Array(e),i=new Uint8Array(r);t.set(i,1),this.privateKey=new Aj({valueHex:e})}else this.privateKey=new Aj({valueHex:r.slice(0,A)});e.x&&e.y&&(this.publicKey=new hi({json:e}))}}hI.CLASS_NAME="ECPrivateKey";let hw="prime",hm="exponent",hE="coefficient",hy=[hw,hm,hE];class hB extends dX{constructor(e={}){super(),this.prime=e2(e,hw,hB.defaultValues(hw)),this.exponent=e2(e,hm,hB.defaultValues(hm)),this.coefficient=e2(e,hE,hB.defaultValues(hE)),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case hw:case hm:case hE:return new AW;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new AW({name:A.prime||""}),new AW({name:A.exponent||""}),new AW({name:A.coefficient||""})]})}fromSchema(e){Ad(e,hy);let A=tb(e,e,hB.schema({names:{prime:hw,exponent:hm,coefficient:hE}}));d$.assertSchema(A,this.className),this.prime=A.result.prime.convertFromDER(),this.exponent=A.result.exponent.convertFromDER(),this.coefficient=A.result.coefficient.convertFromDER()}toSchema(){return new A6({value:[this.prime.convertToDER(),this.exponent.convertToDER(),this.coefficient.convertToDER()]})}toJSON(){return{r:e4.ToBase64Url(this.prime.valueBlock.valueHexView),d:e4.ToBase64Url(this.exponent.valueBlock.valueHexView),t:e4.ToBase64Url(this.coefficient.valueBlock.valueHexView)}}fromJSON(e){dW.assert("json",e,"r","d","r"),this.prime=new AW({valueHex:e4.FromBase64Url(e.r)}),this.exponent=new AW({valueHex:e4.FromBase64Url(e.d)}),this.coefficient=new AW({valueHex:e4.FromBase64Url(e.t)})}}hB.CLASS_NAME="OtherPrimeInfo";let hQ="version",hD="modulus",hb="publicExponent",hS="privateExponent",hk="prime1",hR="prime2",hv="exponent1",hG="exponent2",hT="coefficient",hM="otherPrimeInfos",hN=[hQ,hD,hb,hS,hk,hR,hv,hG,hT,hM];class hO extends dX{constructor(e={}){super(),this.version=e2(e,hQ,hO.defaultValues(hQ)),this.modulus=e2(e,hD,hO.defaultValues(hD)),this.publicExponent=e2(e,hb,hO.defaultValues(hb)),this.privateExponent=e2(e,hS,hO.defaultValues(hS)),this.prime1=e2(e,hk,hO.defaultValues(hk)),this.prime2=e2(e,hR,hO.defaultValues(hR)),this.exponent1=e2(e,hv,hO.defaultValues(hv)),this.exponent2=e2(e,hG,hO.defaultValues(hG)),this.coefficient=e2(e,hT,hO.defaultValues(hT)),hM in e&&(this.otherPrimeInfos=e2(e,hM,hO.defaultValues(hM))),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case hQ:return 0;case hD:case hb:case hS:case hk:case hR:case hv:case hG:case hT:return new AW;case hM:return[];default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new AW({name:A.version||""}),new AW({name:A.modulus||""}),new AW({name:A.publicExponent||""}),new AW({name:A.privateExponent||""}),new AW({name:A.prime1||""}),new AW({name:A.prime2||""}),new AW({name:A.exponent1||""}),new AW({name:A.exponent2||""}),new AW({name:A.coefficient||""}),new A6({optional:!0,value:[new tQ({name:A.otherPrimeInfosName||"",value:hB.schema(A.otherPrimeInfo||{})})]})]})}fromSchema(e){Ad(e,hN);let A=tb(e,e,hO.schema({names:{version:hQ,modulus:hD,publicExponent:hb,privateExponent:hS,prime1:hk,prime2:hR,exponent1:hv,exponent2:hG,coefficient:hT,otherPrimeInfo:{names:{blockName:hM}}}}));d$.assertSchema(A,this.className),this.version=A.result.version.valueBlock.valueDec,this.modulus=A.result.modulus.convertFromDER(256),this.publicExponent=A.result.publicExponent,this.privateExponent=A.result.privateExponent.convertFromDER(256),this.prime1=A.result.prime1.convertFromDER(128),this.prime2=A.result.prime2.convertFromDER(128),this.exponent1=A.result.exponent1.convertFromDER(128),this.exponent2=A.result.exponent2.convertFromDER(128),this.coefficient=A.result.coefficient.convertFromDER(128),hM in A.result&&(this.otherPrimeInfos=Array.from(A.result.otherPrimeInfos,e=>new hB({schema:e})))}toSchema(){let e=[];return e.push(new AW({value:this.version})),e.push(this.modulus.convertToDER()),e.push(this.publicExponent),e.push(this.privateExponent.convertToDER()),e.push(this.prime1.convertToDER()),e.push(this.prime2.convertToDER()),e.push(this.exponent1.convertToDER()),e.push(this.exponent2.convertToDER()),e.push(this.coefficient.convertToDER()),this.otherPrimeInfos&&e.push(new A6({value:Array.from(this.otherPrimeInfos,e=>e.toSchema())})),new A6({value:e})}toJSON(){let e={n:e4.ToBase64Url(this.modulus.valueBlock.valueHexView),e:e4.ToBase64Url(this.publicExponent.valueBlock.valueHexView),d:e4.ToBase64Url(this.privateExponent.valueBlock.valueHexView),p:e4.ToBase64Url(this.prime1.valueBlock.valueHexView),q:e4.ToBase64Url(this.prime2.valueBlock.valueHexView),dp:e4.ToBase64Url(this.exponent1.valueBlock.valueHexView),dq:e4.ToBase64Url(this.exponent2.valueBlock.valueHexView),qi:e4.ToBase64Url(this.coefficient.valueBlock.valueHexView)};return this.otherPrimeInfos&&(e.oth=Array.from(this.otherPrimeInfos,e=>e.toJSON())),e}fromJSON(e){dW.assert("json",e,"n","e","d","p","q","dp","dq","qi"),this.modulus=new AW({valueHex:e4.FromBase64Url(e.n)}),this.publicExponent=new AW({valueHex:e4.FromBase64Url(e.e)}),this.privateExponent=new AW({valueHex:e4.FromBase64Url(e.d)}),this.prime1=new AW({valueHex:e4.FromBase64Url(e.p)}),this.prime2=new AW({valueHex:e4.FromBase64Url(e.q)}),this.exponent1=new AW({valueHex:e4.FromBase64Url(e.dp)}),this.exponent2=new AW({valueHex:e4.FromBase64Url(e.dq)}),this.coefficient=new AW({valueHex:e4.FromBase64Url(e.qi)}),e.oth&&(this.otherPrimeInfos=Array.from(e.oth,e=>new hB({json:e})))}}hO.CLASS_NAME="RSAPrivateKey";let hH="version",hU="privateKeyAlgorithm",h_="privateKey",hx="attributes",hL="parsedKey",hP=[hH,hU,h_,hx];class hq extends dX{constructor(e={}){super(),this.version=e2(e,hH,hq.defaultValues(hH)),this.privateKeyAlgorithm=e2(e,hU,hq.defaultValues(hU)),this.privateKey=e2(e,h_,hq.defaultValues(h_)),hx in e&&(this.attributes=e2(e,hx,hq.defaultValues(hx))),hL in e&&(this.parsedKey=e2(e,hL,hq.defaultValues(hL))),e.json&&this.fromJSON(e.json),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case hH:return 0;case hU:return new uh;case h_:return new Aj;case hx:return[];case hL:return{};default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new AW({name:A.version||""}),uh.schema(A.privateKeyAlgorithm||{}),new Aj({name:A.privateKey||""}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new tQ({name:A.attributes||"",value:um.schema()})]})]})}fromSchema(e){Ad(e,hP);let A=tb(e,e,hq.schema({names:{version:hH,privateKeyAlgorithm:{names:{blockName:hU}},privateKey:h_,attributes:hx}}));switch(d$.assertSchema(A,this.className),this.version=A.result.version.valueBlock.valueDec,this.privateKeyAlgorithm=new uh({schema:A.result.privateKeyAlgorithm}),this.privateKey=A.result.privateKey,hx in A.result&&(this.attributes=Array.from(A.result.attributes,e=>new um({schema:e}))),this.privateKeyAlgorithm.algorithmId){case"1.2.840.113549.1.1.1":{let e=AU(this.privateKey.valueBlock.valueHexView);-1!==e.offset&&(this.parsedKey=new hO({schema:e.result}))}break;case"1.2.840.10045.2.1":if("algorithmParams"in this.privateKeyAlgorithm&&this.privateKeyAlgorithm.algorithmParams instanceof A1){let e=AU(this.privateKey.valueBlock.valueHexView);-1!==e.offset&&(this.parsedKey=new hI({namedCurve:this.privateKeyAlgorithm.algorithmParams.valueBlock.toString(),schema:e.result}))}}}toSchema(){let e=[new AW({value:this.version}),this.privateKeyAlgorithm.toSchema(),this.privateKey];return this.attributes&&e.push(new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:Array.from(this.attributes,e=>e.toSchema())})),new A6({value:e})}toJSON(){if(!this.parsedKey){let e={version:this.version,privateKeyAlgorithm:this.privateKeyAlgorithm.toJSON(),privateKey:this.privateKey.toJSON()};return this.attributes&&(e.attributes=Array.from(this.attributes,e=>e.toJSON())),e}let e={};switch(this.privateKeyAlgorithm.algorithmId){case"1.2.840.10045.2.1":e.kty="EC";break;case"1.2.840.113549.1.1.1":e.kty="RSA"}return Object.assign(e,this.parsedKey.toJSON()),e}fromJSON(e){if("kty"in e){switch(e.kty.toUpperCase()){case"EC":this.parsedKey=new hI({json:e}),this.privateKeyAlgorithm=new uh({algorithmId:"1.2.840.10045.2.1",algorithmParams:new A1({value:this.parsedKey.namedCurve})});break;case"RSA":this.parsedKey=new hO({json:e}),this.privateKeyAlgorithm=new uh({algorithmId:"1.2.840.113549.1.1.1",algorithmParams:new Aq});break;default:throw Error(`Invalid value for "kty" parameter: ${e.kty}`)}this.privateKey=new Aj({valueHex:this.parsedKey.toSchema().toBER(!1)})}}}hq.CLASS_NAME="PrivateKeyInfo";let hK="contentType",hJ="contentEncryptionAlgorithm",hF="encryptedContent",hj=[hK,hJ,hF];class hz extends dX{constructor(e={}){if(super(),this.contentType=e2(e,hK,hz.defaultValues(hK)),this.contentEncryptionAlgorithm=e2(e,hJ,hz.defaultValues(hJ)),hF in e&&e.encryptedContent&&(this.encryptedContent=e.encryptedContent,1===this.encryptedContent.idBlock.tagClass&&4===this.encryptedContent.idBlock.tagNumber&&!1===this.encryptedContent.idBlock.isConstructed&&!e.disableSplit)){const e=new Aj({idBlock:{isConstructed:!0},isConstructed:!0});let A=0;const t=this.encryptedContent.valueBlock.valueHexView.slice().buffer;let r=t.byteLength;for(;r>0;){const i=new Uint8Array(t,A,A+1024>t.byteLength?t.byteLength-A:1024),n=new ArrayBuffer(i.length),a=new Uint8Array(n);for(let e=0;e<a.length;e++)a[e]=i[e];e.valueBlock.value.push(new Aj({valueHex:n})),r-=i.length,A+=i.length}this.encryptedContent=e}e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case hK:return"";case hJ:return new uh;case hF:return new Aj;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case hK:return""===A;case hJ:return""===A.algorithmId&&"algorithmParams"in A==!1;case hF:return A.isEqual(hz.defaultValues(hF));default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new A1({name:A.contentType||""}),uh.schema(A.contentEncryptionAlgorithm||{}),new tB({value:[new Ax({name:A.encryptedContent||"",idBlock:{tagClass:3,tagNumber:0},value:[new tQ({value:new Aj})]}),new AM({name:A.encryptedContent||"",idBlock:{tagClass:3,tagNumber:0}})]})]})}fromSchema(e){Ad(e,hj);let A=tb(e,e,hz.schema({names:{contentType:hK,contentEncryptionAlgorithm:{names:{blockName:hJ}},encryptedContent:hF}}));d$.assertSchema(A,this.className),this.contentType=A.result.contentType.valueBlock.toString(),this.contentEncryptionAlgorithm=new uh({schema:A.result.contentEncryptionAlgorithm}),hF in A.result&&(this.encryptedContent=A.result.encryptedContent,this.encryptedContent.idBlock.tagClass=1,this.encryptedContent.idBlock.tagNumber=4)}toSchema(){let e={isIndefiniteForm:!1},A=[];if(A.push(new A1({value:this.contentType})),A.push(this.contentEncryptionAlgorithm.toSchema()),this.encryptedContent){e.isIndefiniteForm=this.encryptedContent.idBlock.isConstructed;let t=this.encryptedContent;t.idBlock.tagClass=3,t.idBlock.tagNumber=0,t.lenBlock.isIndefiniteForm=this.encryptedContent.idBlock.isConstructed,A.push(t)}return new A6({lenBlock:e,value:A})}toJSON(){let e={contentType:this.contentType,contentEncryptionAlgorithm:this.contentEncryptionAlgorithm.toJSON()};return this.encryptedContent&&(e.encryptedContent=this.encryptedContent.toJSON()),e}getEncryptedContent(){if(!this.encryptedContent)throw Error("Parameter 'encryptedContent' is undefined");return Aj.prototype.getValue.call(this.encryptedContent)}}hz.CLASS_NAME="EncryptedContentInfo";let hY="hashAlgorithm",hZ="maskGenAlgorithm",hV="saltLength",hW="trailerField",h$=[hY,hZ,hV,hW];class hX extends dX{constructor(e={}){super(),this.hashAlgorithm=e2(e,hY,hX.defaultValues(hY)),this.maskGenAlgorithm=e2(e,hZ,hX.defaultValues(hZ)),this.saltLength=e2(e,hV,hX.defaultValues(hV)),this.trailerField=e2(e,hW,hX.defaultValues(hW)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case hY:return new uh({algorithmId:"1.3.14.3.2.26",algorithmParams:new Aq});case hZ:return new uh({algorithmId:"1.2.840.113549.1.1.8",algorithmParams:new uh({algorithmId:"1.3.14.3.2.26",algorithmParams:new Aq}).toSchema()});case hV:return 20;case hW:return 1;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new Ax({idBlock:{tagClass:3,tagNumber:0},optional:!0,value:[uh.schema(A.hashAlgorithm||{})]}),new Ax({idBlock:{tagClass:3,tagNumber:1},optional:!0,value:[uh.schema(A.maskGenAlgorithm||{})]}),new Ax({idBlock:{tagClass:3,tagNumber:2},optional:!0,value:[new AW({name:A.saltLength||""})]}),new Ax({idBlock:{tagClass:3,tagNumber:3},optional:!0,value:[new AW({name:A.trailerField||""})]})]})}fromSchema(e){Ad(e,h$);let A=tb(e,e,hX.schema({names:{hashAlgorithm:{names:{blockName:hY}},maskGenAlgorithm:{names:{blockName:hZ}},saltLength:hV,trailerField:hW}}));d$.assertSchema(A,this.className),hY in A.result&&(this.hashAlgorithm=new uh({schema:A.result.hashAlgorithm})),hZ in A.result&&(this.maskGenAlgorithm=new uh({schema:A.result.maskGenAlgorithm})),hV in A.result&&(this.saltLength=A.result.saltLength.valueBlock.valueDec),hW in A.result&&(this.trailerField=A.result.trailerField.valueBlock.valueDec)}toSchema(){let e=[];return this.hashAlgorithm.isEqual(hX.defaultValues(hY))||e.push(new Ax({idBlock:{tagClass:3,tagNumber:0},value:[this.hashAlgorithm.toSchema()]})),this.maskGenAlgorithm.isEqual(hX.defaultValues(hZ))||e.push(new Ax({idBlock:{tagClass:3,tagNumber:1},value:[this.maskGenAlgorithm.toSchema()]})),this.saltLength!==hX.defaultValues(hV)&&e.push(new Ax({idBlock:{tagClass:3,tagNumber:2},value:[new AW({value:this.saltLength})]})),this.trailerField!==hX.defaultValues(hW)&&e.push(new Ax({idBlock:{tagClass:3,tagNumber:3},value:[new AW({value:this.trailerField})]})),new A6({value:e})}toJSON(){let e={};return this.hashAlgorithm.isEqual(hX.defaultValues(hY))||(e.hashAlgorithm=this.hashAlgorithm.toJSON()),this.maskGenAlgorithm.isEqual(hX.defaultValues(hZ))||(e.maskGenAlgorithm=this.maskGenAlgorithm.toJSON()),this.saltLength!==hX.defaultValues(hV)&&(e.saltLength=this.saltLength),this.trailerField!==hX.defaultValues(hW)&&(e.trailerField=this.trailerField),e}}hX.CLASS_NAME="RSASSAPSSParams";let h0="salt",h1="iterationCount",h8="keyLength",h4=[h0,h1,h8,"prf"];class h2 extends dX{constructor(e={}){super(),this.salt=e2(e,h0,h2.defaultValues(h0)),this.iterationCount=e2(e,h1,h2.defaultValues(h1)),h8 in e&&(this.keyLength=e2(e,h8,h2.defaultValues(h8))),"prf"in e&&(this.prf=e2(e,"prf",h2.defaultValues("prf"))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case h0:return{};case h1:return -1;case h8:return 0;case"prf":return new uh({algorithmId:"1.3.14.3.2.26",algorithmParams:new Aq});default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new tB({value:[new Aj({name:A.saltPrimitive||""}),uh.schema(A.saltConstructed||{})]}),new AW({name:A.iterationCount||""}),new AW({name:A.keyLength||"",optional:!0}),uh.schema(A.prf||{names:{optional:!0}})]})}fromSchema(e){Ad(e,h4);let A=tb(e,e,h2.schema({names:{saltPrimitive:h0,saltConstructed:{names:{blockName:h0}},iterationCount:h1,keyLength:h8,prf:{names:{blockName:"prf",optional:!0}}}}));d$.assertSchema(A,this.className),this.salt=A.result.salt,this.iterationCount=A.result.iterationCount.valueBlock.valueDec,h8 in A.result&&(this.keyLength=A.result.keyLength.valueBlock.valueDec),"prf"in A.result&&(this.prf=new uh({schema:A.result.prf}))}toSchema(){let e=[];return e.push(this.salt),e.push(new AW({value:this.iterationCount})),h8 in this&&h2.defaultValues(h8)!==this.keyLength&&e.push(new AW({value:this.keyLength})),this.prf&&!1===h2.defaultValues("prf").isEqual(this.prf)&&e.push(this.prf.toSchema()),new A6({value:e})}toJSON(){let e={salt:this.salt.toJSON(),iterationCount:this.iterationCount};return h8 in this&&h2.defaultValues(h8)!==this.keyLength&&(e.keyLength=this.keyLength),this.prf&&!1===h2.defaultValues("prf").isEqual(this.prf)&&(e.prf=this.prf.toJSON()),e}}h2.CLASS_NAME="PBKDF2Params";let h6="keyDerivationFunc",h3="encryptionScheme",h5=[h6,h3];class h9 extends dX{constructor(e={}){super(),this.keyDerivationFunc=e2(e,h6,h9.defaultValues(h6)),this.encryptionScheme=e2(e,h3,h9.defaultValues(h3)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case h6:case h3:return new uh;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[uh.schema(A.keyDerivationFunc||{}),uh.schema(A.encryptionScheme||{})]})}fromSchema(e){Ad(e,h5);let A=tb(e,e,h9.schema({names:{keyDerivationFunc:{names:{blockName:h6}},encryptionScheme:{names:{blockName:h3}}}}));d$.assertSchema(A,this.className),this.keyDerivationFunc=new uh({schema:A.result.keyDerivationFunc}),this.encryptionScheme=new uh({schema:A.result.encryptionScheme})}toSchema(){return new A6({value:[this.keyDerivationFunc.toSchema(),this.encryptionScheme.toSchema()]})}toJSON(){return{keyDerivationFunc:this.keyDerivationFunc.toJSON(),encryptionScheme:this.encryptionScheme.toJSON()}}}h9.CLASS_NAME="PBES2Params";class h7{constructor(e){this.crypto=e.crypto,this.subtle="webkitSubtle"in e.crypto?e.crypto.webkitSubtle:e.crypto.subtle,this.name=e2(e,"name","")}async encrypt(...e){return this.subtle.encrypt(...e)}async decrypt(...e){return this.subtle.decrypt(...e)}sign(...e){return this.subtle.sign(...e)}async verify(...e){return this.subtle.verify(...e)}async digest(...e){return this.subtle.digest(...e)}async generateKey(...e){return this.subtle.generateKey(...e)}async deriveKey(...e){return this.subtle.deriveKey(...e)}async deriveBits(...e){return this.subtle.deriveBits(...e)}async wrapKey(...e){return this.subtle.wrapKey(...e)}async unwrapKey(...e){return this.subtle.unwrapKey(...e)}exportKey(...e){return this.subtle.exportKey(...e)}importKey(...e){return this.subtle.importKey(...e)}getRandomValues(e){if(null===e)throw Error('Argument "array" must not be null');return this.crypto.getRandomValues(e)}}async function ge(e,A,t,r,i){let n,a,o;switch(e.toUpperCase()){case"SHA-1":n=20,a=64,o=dm;break;case"SHA-256":n=32,a=64,o=dY;break;case"SHA-384":n=48,a=128,o=dK;break;case"SHA-512":n=64,a=128,o=dq;break;default:throw Error("Unsupported hashing algorithm")}let s=new Uint8Array(t),l=new TextDecoder().decode(t);new TextEncoder().encode(l).some((e,A)=>e!==s[A])&&(l=String.fromCharCode(...s));let d=new Uint8Array(2*l.length+2),u=new DataView(d.buffer);for(let e=0;e<l.length;e++)u.setUint16(2*e,l.charCodeAt(e),!1);u.setUint16(2*l.length,0,!1);let c=new Uint8Array(a).fill(3),h=new Uint8Array(r),g=new Uint8Array(a*Math.ceil(h.length/a)).map((e,A)=>h[A%h.length]),p=new Uint8Array(a*Math.ceil(d.length/a)).map((e,A)=>d[A%d.length]),C=new Uint8Array(g.length+p.length);C.set(g),C.set(p,g.length);let f=Math.ceil((A>>3)/n),I=[];for(let e=0;e<f;e++){let e=new Uint8Array(c.length+C.length);e.set(c),e.set(C,c.length);for(let A=0;A<i;A++)e=o(e);let A=new Uint8Array(a).map((A,t)=>e[t%e.length]),t=Math.ceil(h.length/a)+Math.ceil(d.length/a),r=[];for(let e=0;e<t;e++){let t=Array.from(C.slice(e*a,(e+1)*a)),i=511;for(let e=A.length-1;e>=0;e--)i>>=8,i+=A[e]+(t[e]||0),t[e]=255&i;r.push(...t)}C=new Uint8Array(r),I.push(...e)}return new Uint8Array(I.slice(0,A>>3)).buffer}class gA extends h7{async importKey(e,A,t,r,i){var n,a,o,s,l,d;let u={},c=function e(A){let t="string"==typeof A?{name:A}:A;return"hash"in t?{...t,hash:e(t.hash)}:t}(t);switch(e.toLowerCase()){case"raw":return this.subtle.importKey("raw",A,t,r,i);case"spki":{let e=AU(eV.toArrayBuffer(A));d$.assert(e,"keyData");let t=new hc;try{t.fromSchema(e.result)}catch{throw new dV("Incorrect keyData")}switch(c.name.toUpperCase()){case"RSA-PSS":if(i=["verify"],u.kty="RSA",u.ext=r,u.key_ops=i,!["1.2.840.113549.1.1.1","1.2.840.113549.1.1.10"].includes(t.algorithm.algorithmId))throw Error(`Incorrect public key algorithm: ${t.algorithm.algorithmId}`);if(!c.hash)throw new dW("hash","algorithm.hash","Incorrect hash algorithm: Hash algorithm is missed");switch(c.hash.name.toUpperCase()){case"SHA-1":u.alg="PS1";break;case"SHA-256":u.alg="PS256";break;case"SHA-384":u.alg="PS384";break;case"SHA-512":u.alg="PS512";break;default:throw Error(`Incorrect hash algorithm: ${c.hash.name.toUpperCase()}`)}Object.assign(u,t.toJSON());break;case"RSASSA-PKCS1-V1_5":if(i=["verify"],u.kty="RSA",u.ext=r,u.key_ops=i,"1.2.840.113549.1.1.1"!==t.algorithm.algorithmId)throw Error(`Incorrect public key algorithm: ${t.algorithm.algorithmId}`);if(!c.hash)throw new dW("hash","algorithm.hash","Incorrect hash algorithm: Hash algorithm is missed");switch(c.hash.name.toUpperCase()){case"SHA-1":u.alg="RS1";break;case"SHA-256":u.alg="RS256";break;case"SHA-384":u.alg="RS384";break;case"SHA-512":u.alg="RS512";break;default:throw Error(`Incorrect hash algorithm: ${c.hash.name.toUpperCase()}`)}Object.assign(u,t.toJSON());break;case"ECDSA":i=["verify"];case"ECDH":if(u={kty:"EC",ext:r,key_ops:i},"1.2.840.10045.2.1"!==t.algorithm.algorithmId)throw Error(`Incorrect public key algorithm: ${t.algorithm.algorithmId}`);Object.assign(u,t.toJSON());break;case"RSA-OAEP":if(u.kty="RSA",u.ext=r,u.key_ops=i,"safari"===this.name.toLowerCase())u.alg="RSA-OAEP";else{if(!c.hash)throw new dW("hash","algorithm.hash","Incorrect hash algorithm: Hash algorithm is missed");switch(c.hash.name.toUpperCase()){case"SHA-1":u.alg="RSA-OAEP";break;case"SHA-256":u.alg="RSA-OAEP-256";break;case"SHA-384":u.alg="RSA-OAEP-384";break;case"SHA-512":u.alg="RSA-OAEP-512";break;default:throw Error(`Incorrect hash algorithm: ${c.hash.name.toUpperCase()}`)}}Object.assign(u,t.toJSON());break;case"RSAES-PKCS1-V1_5":u.kty="RSA",u.ext=r,u.key_ops=i,u.alg="PS1",Object.assign(u,t.toJSON());break;default:throw Error(`Incorrect algorithm name: ${c.name.toUpperCase()}`)}}break;case"pkcs8":{let e=new hq,t=AU(eV.toArrayBuffer(A));d$.assert(t,"keyData");try{e.fromSchema(t.result)}catch{throw Error("Incorrect keyData")}if(!e.parsedKey)throw Error("Incorrect keyData");switch(c.name.toUpperCase()){case"RSA-PSS":switch(null==(n=c.hash)?void 0:n.name.toUpperCase()){case"SHA-1":u.alg="PS1";break;case"SHA-256":u.alg="PS256";break;case"SHA-384":u.alg="PS384";break;case"SHA-512":u.alg="PS512";break;default:throw Error(`Incorrect hash algorithm: ${null==(a=c.hash)?void 0:a.name.toUpperCase()}`)}case"RSASSA-PKCS1-V1_5":if(i=["sign"],u.kty="RSA",u.ext=r,u.key_ops=i,"1.2.840.113549.1.1.1"!==e.privateKeyAlgorithm.algorithmId)throw Error(`Incorrect private key algorithm: ${e.privateKeyAlgorithm.algorithmId}`);if("alg"in u==!1)switch(null==(o=c.hash)?void 0:o.name.toUpperCase()){case"SHA-1":u.alg="RS1";break;case"SHA-256":u.alg="RS256";break;case"SHA-384":u.alg="RS384";break;case"SHA-512":u.alg="RS512";break;default:throw Error(`Incorrect hash algorithm: ${null==(s=c.hash)?void 0:s.name.toUpperCase()}`)}Object.assign(u,e.toJSON());break;case"ECDSA":i=["sign"];case"ECDH":if(u={kty:"EC",ext:r,key_ops:i},"1.2.840.10045.2.1"!==e.privateKeyAlgorithm.algorithmId)throw Error(`Incorrect algorithm: ${e.privateKeyAlgorithm.algorithmId}`);Object.assign(u,e.toJSON());break;case"RSA-OAEP":if(u.kty="RSA",u.ext=r,u.key_ops=i,"safari"===this.name.toLowerCase())u.alg="RSA-OAEP";else switch(null==(l=c.hash)?void 0:l.name.toUpperCase()){case"SHA-1":u.alg="RSA-OAEP";break;case"SHA-256":u.alg="RSA-OAEP-256";break;case"SHA-384":u.alg="RSA-OAEP-384";break;case"SHA-512":u.alg="RSA-OAEP-512";break;default:throw Error(`Incorrect hash algorithm: ${null==(d=c.hash)?void 0:d.name.toUpperCase()}`)}Object.assign(u,e.toJSON());break;case"RSAES-PKCS1-V1_5":i=["decrypt"],u.kty="RSA",u.ext=r,u.key_ops=i,u.alg="PS1",Object.assign(u,e.toJSON());break;default:throw Error(`Incorrect algorithm name: ${c.name.toUpperCase()}`)}}break;case"jwk":u=A;break;default:throw Error(`Incorrect format: ${e}`)}if("safari"===this.name.toLowerCase())try{return this.subtle.importKey("jwk",As(JSON.stringify(u)),t,r,i)}catch{}return this.subtle.importKey("jwk",u,t,r,i)}async exportKey(e,A){let t=await this.subtle.exportKey("jwk",A);switch("safari"===this.name.toLowerCase()&&t instanceof ArrayBuffer&&(t=JSON.parse(Ao(t))),e.toLowerCase()){case"raw":return this.subtle.exportKey("raw",A);case"spki":{let e=new hc;try{e.fromJSON(t)}catch{throw Error("Incorrect key data")}return e.toSchema().toBER(!1)}case"pkcs8":{let e=new hq;try{e.fromJSON(t)}catch{throw Error("Incorrect key data")}return e.toSchema().toBER(!1)}case"jwk":return t;default:throw Error(`Incorrect format: ${e}`)}}async convert(e,A,t,r,i,n){if(e.toLowerCase()===A.toLowerCase())return t;let a=await this.importKey(e,t,r,i,n);return this.exportKey(A,a)}getAlgorithmByOID(e,A=!1,t){switch(e){case"1.2.840.113549.1.1.1":return{name:"RSAES-PKCS1-v1_5"};case"1.2.840.113549.1.1.5":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case"1.2.840.113549.1.1.11":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"1.2.840.113549.1.1.12":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case"1.2.840.113549.1.1.13":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case"1.2.840.113549.1.1.10":return{name:"RSA-PSS"};case"1.2.840.113549.1.1.7":return{name:"RSA-OAEP"};case"1.2.840.10045.2.1":case"1.2.840.10045.4.1":return{name:"ECDSA",hash:{name:"SHA-1"}};case"1.2.840.10045.4.3.2":return{name:"ECDSA",hash:{name:"SHA-256"}};case"1.2.840.10045.4.3.3":return{name:"ECDSA",hash:{name:"SHA-384"}};case"1.2.840.10045.4.3.4":return{name:"ECDSA",hash:{name:"SHA-512"}};case"1.3.133.16.840.63.0.2":return{name:"ECDH",kdf:"SHA-1"};case"1.3.132.1.11.1":return{name:"ECDH",kdf:"SHA-256"};case"1.3.132.1.11.2":return{name:"ECDH",kdf:"SHA-384"};case"1.3.132.1.11.3":return{name:"ECDH",kdf:"SHA-512"};case"2.16.840.1.101.3.4.1.2":return{name:"AES-CBC",length:128};case"2.16.840.1.101.3.4.1.22":return{name:"AES-CBC",length:192};case"2.16.840.1.101.3.4.1.42":return{name:"AES-CBC",length:256};case"2.16.840.1.101.3.4.1.6":return{name:"AES-GCM",length:128};case"2.16.840.1.101.3.4.1.26":return{name:"AES-GCM",length:192};case"2.16.840.1.101.3.4.1.46":return{name:"AES-GCM",length:256};case"2.16.840.1.101.3.4.1.4":return{name:"AES-CFB",length:128};case"2.16.840.1.101.3.4.1.24":return{name:"AES-CFB",length:192};case"2.16.840.1.101.3.4.1.44":return{name:"AES-CFB",length:256};case"2.16.840.1.101.3.4.1.5":return{name:"AES-KW",length:128};case"2.16.840.1.101.3.4.1.25":return{name:"AES-KW",length:192};case"2.16.840.1.101.3.4.1.45":return{name:"AES-KW",length:256};case"1.2.840.113549.2.7":return{name:"HMAC",hash:{name:"SHA-1"}};case"1.2.840.113549.2.9":return{name:"HMAC",hash:{name:"SHA-256"}};case"1.2.840.113549.2.10":return{name:"HMAC",hash:{name:"SHA-384"}};case"1.2.840.113549.2.11":return{name:"HMAC",hash:{name:"SHA-512"}};case"1.2.840.113549.1.9.16.3.5":return{name:"DH"};case"1.3.14.3.2.26":return{name:"SHA-1"};case"2.16.840.1.101.3.4.2.1":return{name:"SHA-256"};case"2.16.840.1.101.3.4.2.2":return{name:"SHA-384"};case"2.16.840.1.101.3.4.2.3":return{name:"SHA-512"};case"1.2.840.113549.1.5.12":return{name:"PBKDF2"};case"1.2.840.10045.3.1.7":return{name:"P-256"};case"1.3.132.0.34":return{name:"P-384"};case"1.3.132.0.35":return{name:"P-521"}}if(A)throw Error(`Unsupported algorithm identifier ${t?`for ${t} `:""}: ${e}`);return{}}getOIDByAlgorithm(e,A=!1,t){let r="";switch(e.name.toUpperCase()){case"RSAES-PKCS1-V1_5":r="1.2.840.113549.1.1.1";break;case"RSASSA-PKCS1-V1_5":switch(e.hash.name.toUpperCase()){case"SHA-1":r="1.2.840.113549.1.1.5";break;case"SHA-256":r="1.2.840.113549.1.1.11";break;case"SHA-384":r="1.2.840.113549.1.1.12";break;case"SHA-512":r="1.2.840.113549.1.1.13"}break;case"RSA-PSS":r="1.2.840.113549.1.1.10";break;case"RSA-OAEP":r="1.2.840.113549.1.1.7";break;case"ECDSA":switch(e.hash.name.toUpperCase()){case"SHA-1":r="1.2.840.10045.4.1";break;case"SHA-256":r="1.2.840.10045.4.3.2";break;case"SHA-384":r="1.2.840.10045.4.3.3";break;case"SHA-512":r="1.2.840.10045.4.3.4"}break;case"ECDH":switch(e.kdf.toUpperCase()){case"SHA-1":r="1.3.133.16.840.63.0.2";break;case"SHA-256":r="1.3.132.1.11.1";break;case"SHA-384":r="1.3.132.1.11.2";break;case"SHA-512":r="1.3.132.1.11.3"}break;case"AES-CTR":case"AES-CMAC":case"CONCAT":case"HKDF":break;case"AES-CBC":switch(e.length){case 128:r="2.16.840.1.101.3.4.1.2";break;case 192:r="2.16.840.1.101.3.4.1.22";break;case 256:r="2.16.840.1.101.3.4.1.42"}break;case"AES-GCM":switch(e.length){case 128:r="2.16.840.1.101.3.4.1.6";break;case 192:r="2.16.840.1.101.3.4.1.26";break;case 256:r="2.16.840.1.101.3.4.1.46"}break;case"AES-CFB":switch(e.length){case 128:r="2.16.840.1.101.3.4.1.4";break;case 192:r="2.16.840.1.101.3.4.1.24";break;case 256:r="2.16.840.1.101.3.4.1.44"}break;case"AES-KW":switch(e.length){case 128:r="2.16.840.1.101.3.4.1.5";break;case 192:r="2.16.840.1.101.3.4.1.25";break;case 256:r="2.16.840.1.101.3.4.1.45"}break;case"HMAC":switch(e.hash.name.toUpperCase()){case"SHA-1":r="1.2.840.113549.2.7";break;case"SHA-256":r="1.2.840.113549.2.9";break;case"SHA-384":r="1.2.840.113549.2.10";break;case"SHA-512":r="1.2.840.113549.2.11"}break;case"DH":r="1.2.840.113549.1.9.16.3.5";break;case"SHA-1":r="1.3.14.3.2.26";break;case"SHA-256":r="2.16.840.1.101.3.4.2.1";break;case"SHA-384":r="2.16.840.1.101.3.4.2.2";break;case"SHA-512":r="2.16.840.1.101.3.4.2.3";break;case"PBKDF2":r="1.2.840.113549.1.5.12";break;case"P-256":r="1.2.840.10045.3.1.7";break;case"P-384":r="1.3.132.0.34";break;case"P-521":r="1.3.132.0.35"}if(!r&&A)throw Error(`Unsupported algorithm ${t?`for ${t} `:""}: ${e.name}`);return r}getAlgorithmParameters(e,A){let t={algorithm:{},usages:[]};switch(e.toUpperCase()){case"RSAES-PKCS1-V1_5":case"RSASSA-PKCS1-V1_5":switch(A.toLowerCase()){case"generatekey":t={algorithm:{name:"RSASSA-PKCS1-v1_5",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},usages:["sign","verify"]};break;case"verify":case"sign":case"importkey":t={algorithm:{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},usages:["verify"]};break;default:return{algorithm:{name:"RSASSA-PKCS1-v1_5"},usages:[]}}break;case"RSA-PSS":switch(A.toLowerCase()){case"sign":case"verify":t={algorithm:{name:"RSA-PSS",hash:{name:"SHA-1"},saltLength:20},usages:["sign","verify"]};break;case"generatekey":t={algorithm:{name:"RSA-PSS",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-1"}},usages:["sign","verify"]};break;case"importkey":t={algorithm:{name:"RSA-PSS",hash:{name:"SHA-1"}},usages:["verify"]};break;default:return{algorithm:{name:"RSA-PSS"},usages:[]}}break;case"RSA-OAEP":switch(A.toLowerCase()){case"encrypt":case"decrypt":t={algorithm:{name:"RSA-OAEP"},usages:["encrypt","decrypt"]};break;case"generatekey":t={algorithm:{name:"RSA-OAEP",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},usages:["encrypt","decrypt","wrapKey","unwrapKey"]};break;case"importkey":t={algorithm:{name:"RSA-OAEP",hash:{name:"SHA-256"}},usages:["encrypt"]};break;default:return{algorithm:{name:"RSA-OAEP"},usages:[]}}break;case"ECDSA":switch(A.toLowerCase()){case"generatekey":t={algorithm:{name:"ECDSA",namedCurve:"P-256"},usages:["sign","verify"]};break;case"importkey":t={algorithm:{name:"ECDSA",namedCurve:"P-256"},usages:["verify"]};break;case"verify":case"sign":t={algorithm:{name:"ECDSA",hash:{name:"SHA-256"}},usages:["sign"]};break;default:return{algorithm:{name:"ECDSA"},usages:[]}}break;case"ECDH":switch(A.toLowerCase()){case"exportkey":case"importkey":case"generatekey":t={algorithm:{name:"ECDH",namedCurve:"P-256"},usages:["deriveKey","deriveBits"]};break;case"derivekey":case"derivebits":t={algorithm:{name:"ECDH",namedCurve:"P-256",public:[]},usages:["encrypt","decrypt"]};break;default:return{algorithm:{name:"ECDH"},usages:[]}}break;case"AES-CTR":switch(A.toLowerCase()){case"importkey":case"exportkey":case"generatekey":t={algorithm:{name:"AES-CTR",length:256},usages:["encrypt","decrypt","wrapKey","unwrapKey"]};break;case"decrypt":case"encrypt":t={algorithm:{name:"AES-CTR",counter:new Uint8Array(16),length:10},usages:["encrypt","decrypt","wrapKey","unwrapKey"]};break;default:return{algorithm:{name:"AES-CTR"},usages:[]}}break;case"AES-CBC":switch(A.toLowerCase()){case"importkey":case"exportkey":case"generatekey":t={algorithm:{name:"AES-CBC",length:256},usages:["encrypt","decrypt","wrapKey","unwrapKey"]};break;case"decrypt":case"encrypt":t={algorithm:{name:"AES-CBC",iv:this.getRandomValues(new Uint8Array(16))},usages:["encrypt","decrypt","wrapKey","unwrapKey"]};break;default:return{algorithm:{name:"AES-CBC"},usages:[]}}break;case"AES-GCM":switch(A.toLowerCase()){case"importkey":case"exportkey":case"generatekey":t={algorithm:{name:"AES-GCM",length:256},usages:["encrypt","decrypt","wrapKey","unwrapKey"]};break;case"decrypt":case"encrypt":t={algorithm:{name:"AES-GCM",iv:this.getRandomValues(new Uint8Array(16))},usages:["encrypt","decrypt","wrapKey","unwrapKey"]};break;default:return{algorithm:{name:"AES-GCM"},usages:[]}}break;case"AES-KW":switch(A.toLowerCase()){case"importkey":case"exportkey":case"generatekey":case"wrapkey":case"unwrapkey":t={algorithm:{name:"AES-KW",length:256},usages:["wrapKey","unwrapKey"]};break;default:return{algorithm:{name:"AES-KW"},usages:[]}}break;case"HMAC":switch(A.toLowerCase()){case"sign":case"verify":t={algorithm:{name:"HMAC"},usages:["sign","verify"]};break;case"importkey":case"exportkey":case"generatekey":t={algorithm:{name:"HMAC",length:32,hash:{name:"SHA-256"}},usages:["sign","verify"]};break;default:return{algorithm:{name:"HMAC"},usages:[]}}break;case"HKDF":if("derivekey"!==A.toLowerCase())return{algorithm:{name:"HKDF"},usages:[]};t={algorithm:{name:"HKDF",hash:"SHA-256",salt:new Uint8Array([]),info:new Uint8Array([])},usages:["encrypt","decrypt"]};break;case"PBKDF2":if("derivekey"!==A.toLowerCase())return{algorithm:{name:"PBKDF2"},usages:[]};t={algorithm:{name:"PBKDF2",hash:{name:"SHA-256"},salt:new Uint8Array([]),iterations:1e4},usages:["encrypt","decrypt"]}}return t}getHashAlgorithm(e){let A="";switch(e.algorithmId){case"1.2.840.10045.4.1":case"1.2.840.113549.1.1.5":A="SHA-1";break;case"1.2.840.10045.4.3.2":case"1.2.840.113549.1.1.11":A="SHA-256";break;case"1.2.840.10045.4.3.3":case"1.2.840.113549.1.1.12":A="SHA-384";break;case"1.2.840.10045.4.3.4":case"1.2.840.113549.1.1.13":A="SHA-512";break;case"1.2.840.113549.1.1.10":try{let t=new hX({schema:e.algorithmParams});if(t.hashAlgorithm){let e=this.getAlgorithmByOID(t.hashAlgorithm.algorithmId);if(!("name"in e))return"";A=e.name}else A="SHA-1"}catch{}}return A}async encryptEncryptedContentInfo(e){dW.assert(e,"password","contentEncryptionAlgorithm","hmacHashAlgorithm","iterationCount","contentToEncrypt","contentToEncrypt","contentType");let A=this.getOIDByAlgorithm(e.contentEncryptionAlgorithm,!0,"contentEncryptionAlgorithm"),t=this.getOIDByAlgorithm({name:"PBKDF2"},!0,"PBKDF2"),r=this.getOIDByAlgorithm({name:"HMAC",hash:{name:e.hmacHashAlgorithm}},!0,"hmacHashAlgorithm"),i=new ArrayBuffer(16),n=new Uint8Array(i);this.getRandomValues(n);let a=new ArrayBuffer(64),o=new Uint8Array(a);this.getRandomValues(o);let s=new Uint8Array(e.contentToEncrypt),l=new h2({salt:new Aj({valueHex:a}),iterationCount:e.iterationCount,prf:new uh({algorithmId:r,algorithmParams:new Aq})}),d=new Uint8Array(e.password),u=await this.importKey("raw",d,"PBKDF2",!1,["deriveKey"]),c=await this.deriveKey({name:"PBKDF2",hash:{name:e.hmacHashAlgorithm},salt:o,iterations:e.iterationCount},u,e.contentEncryptionAlgorithm,!1,["encrypt"]),h=await this.encrypt({name:e.contentEncryptionAlgorithm.name,iv:n},c,s),g=new h9({keyDerivationFunc:new uh({algorithmId:t,algorithmParams:l.toSchema()}),encryptionScheme:new uh({algorithmId:A,algorithmParams:new Aj({valueHex:i})})});return new hz({contentType:e.contentType,contentEncryptionAlgorithm:new uh({algorithmId:"1.2.840.113549.1.5.13",algorithmParams:g.toSchema()}),encryptedContent:new Aj({valueHex:h})})}async decryptEncryptedContentInfo(e){let A,t;if(dW.assert(e,"password","encryptedContentInfo"),"1.2.840.113549.1.5.13"!==e.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId)throw Error(`Unknown "contentEncryptionAlgorithm": ${e.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId}`);try{A=new h9({schema:e.encryptedContentInfo.contentEncryptionAlgorithm.algorithmParams})}catch{throw Error('Incorrectly encoded "pbes2Parameters"')}try{t=new h2({schema:A.keyDerivationFunc.algorithmParams})}catch{throw Error('Incorrectly encoded "pbkdf2Params"')}let r=this.getAlgorithmByOID(A.encryptionScheme.algorithmId,!0),i=new Uint8Array(A.encryptionScheme.algorithmParams.valueBlock.valueHex),n=new Uint8Array(t.salt.valueBlock.valueHex),a=t.iterationCount,o="SHA-1";t.prf&&(o=this.getAlgorithmByOID(t.prf.algorithmId,!0).hash.name);let s=await this.importKey("raw",e.password,"PBKDF2",!1,["deriveKey"]),l=await this.deriveKey({name:"PBKDF2",hash:{name:o},salt:n,iterations:a},s,r,!1,["decrypt"]),d=e.encryptedContentInfo.getEncryptedContent();return this.decrypt({name:r.name,iv:i},l,d)}async stampDataWithPassword(e){let A;if(e instanceof Object==!1)throw Error('Parameters must have type "Object"');switch(dW.assert(e,"password","hashAlgorithm","iterationCount","salt","contentToStamp"),e.hashAlgorithm.toLowerCase()){case"sha-1":A=160;break;case"sha-256":A=256;break;case"sha-384":A=384;break;case"sha-512":A=512;break;default:throw Error(`Incorrect "parameters.hashAlgorithm" parameter: ${e.hashAlgorithm}`)}let t={name:"HMAC",length:A,hash:{name:e.hashAlgorithm}},r=await ge(e.hashAlgorithm,A,e.password,e.salt,e.iterationCount),i=await this.importKey("raw",new Uint8Array(r),t,!1,["sign"]);return this.sign(t,i,new Uint8Array(e.contentToStamp))}async verifyDataStampedWithPassword(e){dW.assert(e,"password","hashAlgorithm","salt","iterationCount","contentToVerify","signatureToVerify");let A=0;switch(e.hashAlgorithm.toLowerCase()){case"sha-1":A=160;break;case"sha-256":A=256;break;case"sha-384":A=384;break;case"sha-512":A=512;break;default:throw Error(`Incorrect "parameters.hashAlgorithm" parameter: ${e.hashAlgorithm}`)}let t={name:"HMAC",length:A,hash:{name:e.hashAlgorithm}},r=await ge(e.hashAlgorithm,A,e.password,e.salt,e.iterationCount),i=await this.importKey("raw",new Uint8Array(r),t,!1,["verify"]);return this.verify(t,i,new Uint8Array(e.signatureToVerify),new Uint8Array(e.contentToVerify))}async getSignatureParameters(e,A="SHA-1"){this.getOIDByAlgorithm({name:A},!0,"hashAlgorithm");let t=new uh,r=this.getAlgorithmParameters(e.algorithm.name,"sign");if(!Object.keys(r.algorithm).length)throw Error("Parameter 'algorithm' is empty");let i=r.algorithm;switch("hash"in e.algorithm&&e.algorithm.hash&&e.algorithm.hash.name?i.hash.name=e.algorithm.hash.name:i.hash.name=A,e.algorithm.name.toUpperCase()){case"RSASSA-PKCS1-V1_5":case"ECDSA":t.algorithmId=this.getOIDByAlgorithm(i,!0);break;case"RSA-PSS":{switch(i.hash.name.toUpperCase()){case"SHA-256":i.saltLength=32;break;case"SHA-384":i.saltLength=48;break;case"SHA-512":i.saltLength=64}let e={};"SHA-1"!==i.hash.name.toUpperCase()&&(e.hashAlgorithm=new uh({algorithmId:this.getOIDByAlgorithm({name:i.hash.name},!0,"hashAlgorithm"),algorithmParams:new Aq}),e.maskGenAlgorithm=new uh({algorithmId:"1.2.840.113549.1.1.8",algorithmParams:e.hashAlgorithm.toSchema()})),20!==i.saltLength&&(e.saltLength=i.saltLength);let A=new hX(e);t.algorithmId="1.2.840.113549.1.1.10",t.algorithmParams=A.toSchema()}break;default:throw Error(`Unsupported signature algorithm: ${e.algorithm.name}`)}return{signatureAlgorithm:t,parameters:r}}async signWithPrivateKey(e,A,t){let r=await this.sign(t.algorithm,A,e);return"ECDSA"===t.algorithm.name?function(e){if(e.byteLength%2!=0)return dZ;let A=e.byteLength/2,t=new ArrayBuffer(A);new Uint8Array(t).set(new Uint8Array(e,0,A));let r=new AW({valueHex:t}),i=new ArrayBuffer(A);new Uint8Array(i).set(new Uint8Array(e,A,A));let n=new AW({valueHex:i});return new A6({value:[r.convertToDER(),n.convertToDER()]}).toBER(!1)}(r):r}fillPublicKeyParameters(e,A){let t,r={},i=this.getHashAlgorithm(A);if(""===i)throw Error(`Unsupported signature algorithm: ${A.algorithmId}`);t="1.2.840.113549.1.1.10"===A.algorithmId?A.algorithmId:e.algorithm.algorithmId;let n=this.getAlgorithmByOID(t,!0);if(r.algorithm=this.getAlgorithmParameters(n.name,"importKey"),"hash"in r.algorithm.algorithm&&(r.algorithm.algorithm.hash.name=i),"ECDSA"===n.name){let A=e.algorithm;if(!A.algorithmParams)throw Error("Algorithm parameters for ECDSA public key are missed");let t=A.algorithmParams;if("idBlock"in A.algorithmParams&&(1!==t.idBlock.tagClass||6!==t.idBlock.tagNumber))throw Error("Incorrect type for ECDSA public key parameters");let i=this.getAlgorithmByOID(t.valueBlock.toString(),!0);r.algorithm.algorithm.namedCurve=i.name}return r}async getPublicKey(e,A,t){t||(t=this.fillPublicKeyParameters(e,A));let r=e.toSchema().toBER(!1);return this.importKey("spki",r,t.algorithm.algorithm,!0,t.algorithm.usages)}async verifyWithPublicKey(e,A,t,r,i){let n;if(i){let e,A={};e="1.2.840.113549.1.1.10"===r.algorithmId?r.algorithmId:t.algorithm.algorithmId;let a=this.getAlgorithmByOID(e,!0);if(A.algorithm=this.getAlgorithmParameters(a.name,"importKey"),"hash"in A.algorithm.algorithm&&(A.algorithm.algorithm.hash.name=i),"ECDSA"===a.name){let e=!1;if("algorithmParams"in t.algorithm==!0&&"idBlock"in t.algorithm.algorithmParams&&1===t.algorithm.algorithmParams.idBlock.tagClass&&6===t.algorithm.algorithmParams.idBlock.tagNumber&&(e=!0),!1===e)throw Error("Incorrect type for ECDSA public key parameters");let r=this.getAlgorithmByOID(t.algorithm.algorithmParams.valueBlock.toString(),!0);A.algorithm.algorithm.namedCurve=r.name}n=await this.getPublicKey(t,null,A)}else{if(!(i=this.getHashAlgorithm(r)))throw Error(`Unsupported signature algorithm: ${r.algorithmId}`);n=await this.getPublicKey(t,r)}let a=this.getAlgorithmParameters(n.algorithm.name,"verify");"hash"in a.algorithm&&(a.algorithm.hash.name=i);let o=A.valueBlock.valueHexView;if("ECDSA"===n.algorithm.name){let e=ht.find(n.algorithm.namedCurve);if(!e)throw Error("Unsupported named curve in use");let A=AU(o);d$.assert(A,"Signature value"),o=function(e,A){if(!(e instanceof A6&&2===e.valueBlock.value.length&&e.valueBlock.value[0]instanceof AW&&e.valueBlock.value[1]instanceof AW))return dZ;let t=e.valueBlock.value[0].convertFromDER().valueBlock.valueHexView,r=e.valueBlock.value[1].convertFromDER().valueBlock.valueHexView,i=new Uint8Array(2*A);return i.set(t,A-t.byteLength),i.set(r,2*A-r.byteLength),i.buffer}(A.result,e.size)}if("RSA-PSS"===n.algorithm.name){let e=new hX({schema:r.algorithmParams});"saltLength"in e?a.algorithm.saltLength=e.saltLength:a.algorithm.saltLength=20;let A="SHA-1";"hashAlgorithm"in e&&(A=this.getAlgorithmByOID(e.hashAlgorithm.algorithmId,!0).name),a.algorithm.hash.name=A}return this.verify(a.algorithm,n,o,e)}}let gt={name:"none",crypto:null};function gr(e){return!!e&&"object"==typeof e&&"crypto"in e}function gi(A,...t){let r=null;if(t.length<2)r=t.length?t[0]:"u">typeof self&&self.crypto?new gA({name:"browser",crypto:self.crypto}):null;else{let e=t[0],A=t[1];gr(A)?r=A:gr(e)?r=e:"subtle"in e&&"getRandomValues"in e&&(r=new gA({crypto:e}))}if("u">typeof process&&"pid"in process){if(void 0===e.g[process.pid])e.g[process.pid]={};else if("object"!=typeof e.g[process.pid])throw Error(`Name global.${process.pid} already exists and it is not an object`);if(void 0===e.g[process.pid].pkijs)e.g[process.pid].pkijs={};else if("object"!=typeof e.g[process.pid].pkijs)throw Error(`Name global.${process.pid}.pkijs already exists and it is not an object`);e.g[process.pid].pkijs.engine={name:A,crypto:r}}else gt={name:A,crypto:r}}function gn(A=!1){let t=function(){if("u">typeof process&&"pid"in process){let A;try{A=e.g[process.pid].pkijs.engine}catch{throw Error("Please call 'setEngine' before call to 'getEngine'")}return A}return gt}();if(!t.crypto&&A)throw Error("Unable to create WebCrypto object");return t.crypto}async function ga(e,A,t,r,i){switch(e.toUpperCase()){case"SHA-1":case"SHA-256":case"SHA-384":case"SHA-512":break;default:throw new dV(`Unknown hash function: ${e}`)}if(dV.assert(A,"zBuffer","ArrayBuffer"),0===A.byteLength)throw new dV("'zBuffer' has zero length, error");if(dV.assert(r,"SharedInfo","ArrayBuffer"),t>255)throw new dV("Please set 'Counter' argument to value less or equal to 255");let n=new ArrayBuffer(4),a=new Uint8Array(n);a[0]=0,a[1]=0,a[2]=0,a[3]=t;let o=dZ;return o=e9(o,A),o=e9(o,n),o=e9(o,r),{counter:t,result:await i.digest({name:e},o)}}async function go(e,A,t,r,i=gn(!0)){let n=0,a=1;switch(e.toUpperCase()){case"SHA-1":n=160;break;case"SHA-256":n=256;break;case"SHA-384":n=384;break;case"SHA-512":n=512;break;default:throw new dV(`Unknown hash function: ${e}`)}if(dV.assert(A,"Zbuffer","ArrayBuffer"),0===A.byteLength)throw new dV("'Zbuffer' has zero length, error");dV.assert(r,"SharedInfo","ArrayBuffer");let o=t/n;Math.floor(o)>0&&(a=Math.floor(o),o-a>0&&a++);let s=[];for(let t=1;t<=a;t++)s.push(await ga(e,A,t,r,i));let l=dZ,d=1,u=!0;for(;u;){for(let e of(u=!1,s))if(e.counter===d){l=e9(l,e.result),u=!0;break}d++}if(t>>=3,l.byteLength>t){let e=new ArrayBuffer(t),A=new Uint8Array(e),r=new Uint8Array(l);for(let e=0;e<t;e++)A[e]=r[e];return e}return l}let gs="version",gl="logID",gd="extensions",gu="timestamp",gc="hashAlgorithm",gh="signatureAlgorithm",gg="signature",gp="none",gC="sha1",gf="sha224",gI="sha256",gw="sha384",gm="sha512",gE="anonymous",gy="ecdsa";class gB extends dX{constructor(e={}){super(),this.version=e2(e,gs,gB.defaultValues(gs)),this.logID=e2(e,gl,gB.defaultValues(gl)),this.timestamp=e2(e,gu,gB.defaultValues(gu)),this.extensions=e2(e,gd,gB.defaultValues(gd)),this.hashAlgorithm=e2(e,gc,gB.defaultValues(gc)),this.signatureAlgorithm=e2(e,gh,gB.defaultValues(gh)),this.signature=e2(e,gg,gB.defaultValues(gg)),"stream"in e&&e.stream&&this.fromStream(e.stream),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case gs:return 0;case gl:case gd:return dZ;case gu:return new Date(0);case gc:case gh:return"";case gg:return dZ;default:return super.defaultValues(e)}}fromSchema(e){if(e instanceof tD==!1)throw Error("Object's schema was not verified against input data for SignedCertificateTimestamp");let A=new di({stream:new dr({buffer:e.data})});this.fromStream(A)}fromStream(e){let A=e.getUint16();if(this.version=e.getBlock(1)[0],0===this.version){this.logID=new Uint8Array(e.getBlock(32)).buffer.slice(0),this.timestamp=new Date(e3(new Uint8Array(e.getBlock(8)),8));let t=e.getUint16();switch(this.extensions=new Uint8Array(e.getBlock(t)).buffer.slice(0),e.getBlock(1)[0]){case 0:this.hashAlgorithm=gp;break;case 1:this.hashAlgorithm="md5";break;case 2:this.hashAlgorithm=gC;break;case 3:this.hashAlgorithm=gf;break;case 4:this.hashAlgorithm=gI;break;case 5:this.hashAlgorithm=gw;break;case 6:this.hashAlgorithm=gm;break;default:throw Error("Object's stream was not correct for SignedCertificateTimestamp")}switch(e.getBlock(1)[0]){case 0:this.signatureAlgorithm=gE;break;case 1:this.signatureAlgorithm="rsa";break;case 2:this.signatureAlgorithm="dsa";break;case 3:this.signatureAlgorithm=gy;break;default:throw Error("Object's stream was not correct for SignedCertificateTimestamp")}let r=e.getUint16();if(this.signature=new Uint8Array(e.getBlock(r)).buffer.slice(0),A!==47+t+r)throw Error("Object's stream was not correct for SignedCertificateTimestamp")}}toSchema(){return new tD({data:this.toStream().stream.buffer})}toStream(){let e,A,t=new di;t.appendUint16(47+this.extensions.byteLength+this.signature.byteLength),t.appendChar(this.version),t.appendView(new Uint8Array(this.logID));let r=new Uint8Array(new ArrayBuffer(8)),i=e5(this.timestamp.valueOf(),8);switch(r.set(new Uint8Array(i),8-i.byteLength),t.appendView(r),t.appendUint16(this.extensions.byteLength),this.extensions.byteLength&&t.appendView(new Uint8Array(this.extensions)),this.hashAlgorithm.toLowerCase()){case gp:e=0;break;case"md5":e=1;break;case gC:e=2;break;case gf:e=3;break;case gI:e=4;break;case gw:e=5;break;case gm:e=6;break;default:throw Error(`Incorrect data for hashAlgorithm: ${this.hashAlgorithm}`)}switch(t.appendChar(e),this.signatureAlgorithm.toLowerCase()){case gE:A=0;break;case"rsa":A=1;break;case"dsa":A=2;break;case gy:A=3;break;default:throw Error(`Incorrect data for signatureAlgorithm: ${this.signatureAlgorithm}`)}return t.appendChar(A),t.appendUint16(this.signature.byteLength),t.appendView(new Uint8Array(this.signature)),t}toJSON(){return{version:this.version,logID:e6(this.logID),timestamp:this.timestamp,extensions:e6(this.extensions),hashAlgorithm:this.hashAlgorithm,signatureAlgorithm:this.signatureAlgorithm,signature:e6(this.signature)}}async verify(e,A,t=0,r=gn(!0)){let i=An(Ao(this.logID)),n=null,a=new di;for(let A of e)if(A.log_id===i){n=A.key;break}if(!n)throw Error(`Public key not found for CT with logId: ${i}`);let o=As(Aa(n)),s=hc.fromBER(o);a.appendChar(0),a.appendChar(0);let l=new Uint8Array(new ArrayBuffer(8)),d=e5(this.timestamp.valueOf(),8);return l.set(new Uint8Array(d),8-d.byteLength),a.appendView(l),a.appendUint16(t),0===t&&a.appendUint24(A.byteLength),a.appendView(new Uint8Array(A)),a.appendUint16(this.extensions.byteLength),0!==this.extensions.byteLength&&a.appendView(new Uint8Array(this.extensions)),r.verifyWithPublicKey(a.buffer.slice(0,a.length),new Aj({valueHex:this.signature}),s,{algorithmId:""},"SHA-256")}}gB.CLASS_NAME="SignedCertificateTimestamp";let gQ="timestamps";class gD extends dX{constructor(e={}){super(),this.timestamps=e2(e,gQ,gD.defaultValues(gQ)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e===gQ?[]:super.defaultValues(e)}static compareWithDefault(e,A){return e===gQ?0===A.length:super.defaultValues(e)}static schema(e={}){let A=e2(e,"names",{});return null!=A.optional||(A.optional=!1),new Aj({name:A.blockName||"SignedCertificateTimestampList",optional:A.optional})}fromSchema(e){if(e instanceof Aj==!1)throw Error("Object's schema was not verified against input data for SignedCertificateTimestampList");let A=new di({stream:new dr({buffer:e.valueBlock.valueHex})});if(A.getUint16()!==A.length)throw Error("Object's schema was not verified against input data for SignedCertificateTimestampList");for(;A.length;)this.timestamps.push(new gB({stream:A}))}toSchema(){let e=new di,A=0,t=[];for(let e of this.timestamps){let r=e.toStream();t.push(r),A+=r.stream.buffer.byteLength}for(let r of(e.appendUint16(A),t))e.appendView(r.stream.view);return new Aj({valueHex:e.stream.buffer.slice(0)})}toJSON(){return{timestamps:Array.from(this.timestamps,e=>e.toJSON())}}}gD.CLASS_NAME="SignedCertificateTimestampList";let gb="attributes",gS=[gb];class gk extends dX{constructor(e={}){super(),this.attributes=e2(e,gb,gk.defaultValues(gb)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e===gb?[]:super.defaultValues(e)}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new tQ({name:A.attributes||"",value:um.schema()})]})}fromSchema(e){Ad(e,gS);let A=tb(e,e,gk.schema({names:{attributes:gb}}));d$.assertSchema(A,this.className),this.attributes=Array.from(A.result.attributes,e=>new um({schema:e}))}toSchema(){return new A6({value:Array.from(this.attributes,e=>e.toSchema())})}toJSON(){return{attributes:Array.from(this.attributes,e=>e.toJSON())}}}gk.CLASS_NAME="SubjectDirectoryAttributes";class gR{static getItems(){return this.types||(this.types={},gR.register(uk,"SubjectAltName",uC),gR.register(uR,"IssuerAltName",uC),gR.register(ux,"AuthorityKeyIdentifier",u0),gR.register(uv,"BasicConstraints",u8),gR.register("1.3.6.1.4.1.311.21.1","MicrosoftCaVersion",u6),gR.register(uH,"CertificatePolicies",ca),gR.register("1.3.6.1.4.1.311.21.10","CertificatePoliciesMicrosoft",ca),gR.register("1.3.6.1.4.1.311.21.7","MicrosoftCertTemplateV2",cu),gR.register(uN,"CRLDistributionPoints",cE),gR.register(uO,"FreshestCRL",cE),gR.register("2.5.29.37","ExtKeyUsage",cQ),gR.register(uT,"CertificateIssuer",uS),gR.register(uP,"AuthorityInfoAccess",cb),gR.register("1.3.6.1.5.5.7.1.11","SubjectInfoAccess",cb),gR.register(uG,"IssuingDistributionPoint",cO),gR.register(uM,"NameConstraints",cJ),gR.register(uL,"PolicyConstraints",cY),gR.register(u_,"PolicyMappings",c1),gR.register("2.5.29.16","PrivateKeyUsagePeriod",c6),gR.register("1.3.6.1.5.5.7.1.3","QCStatements",hA),gR.register("1.3.6.1.4.1.11129.2.4.2","SignedCertificateTimestampList",gD),gR.register("2.5.29.9","SubjectDirectoryAttributes",gk)),this.types}static fromBER(e,A){let t=AU(A);if(-1===t.offset)return null;let r=this.find(e);if(r)try{return new r.type({schema:t.result})}catch{let A=new r.type;return A.parsingError=`Incorrectly formatted value of extension ${r.name} (${e})`,A}return t.result}static find(e){return this.getItems()[e]||null}static register(e,A,t){this.getItems()[e]={name:A,type:t}}}let gv="extnID",gG="critical",gT="extnValue",gM="parsedValue",gN=[gv,gG,gT];class gO extends dX{get parsedValue(){if(void 0===this._parsedValue){let e=gR.fromBER(this.extnID,this.extnValue.valueBlock.valueHexView);this._parsedValue=e}return this._parsedValue||void 0}set parsedValue(e){this._parsedValue=e}constructor(e={}){super(),this.extnID=e2(e,gv,gO.defaultValues(gv)),this.critical=e2(e,gG,gO.defaultValues(gG)),gT in e?this.extnValue=new Aj({valueHex:e.extnValue}):this.extnValue=gO.defaultValues(gT),gM in e&&(this.parsedValue=e2(e,gM,gO.defaultValues(gM))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case gv:return"";case gG:return!1;case gT:return new Aj;case gM:return{};default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new A1({name:A.extnID||""}),new AJ({name:A.critical||"",optional:!0}),new Aj({name:A.extnValue||""})]})}fromSchema(e){Ad(e,gN);let A=tb(e,e,gO.schema({names:{extnID:gv,critical:gG,extnValue:gT}}));d$.assertSchema(A,this.className),this.extnID=A.result.extnID.valueBlock.toString(),gG in A.result&&(this.critical=A.result.critical.valueBlock.value),this.extnValue=A.result.extnValue}toSchema(){let e=[];return e.push(new A1({value:this.extnID})),this.critical!==gO.defaultValues(gG)&&e.push(new AJ({value:this.critical})),e.push(this.extnValue),new A6({value:e})}toJSON(){let e={extnID:this.extnID,extnValue:this.extnValue.toJSON()};return this.critical!==gO.defaultValues(gG)&&(e.critical=this.critical),this.parsedValue&&this.parsedValue.toJSON&&(e.parsedValue=this.parsedValue.toJSON()),e}}gO.CLASS_NAME="Extension";let gH="extensions",gU=[gH];class g_ extends dX{constructor(e={}){super(),this.extensions=e2(e,gH,g_.defaultValues(gH)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e===gH?[]:super.defaultValues(e)}static schema(e={},A=!1){let t=e2(e,"names",{});return new A6({optional:A,name:t.blockName||"",value:[new tQ({name:t.extensions||"",value:gO.schema(t.extension||{})})]})}fromSchema(e){Ad(e,gU);let A=tb(e,e,g_.schema({names:{extensions:gH}}));d$.assertSchema(A,this.className),this.extensions=Array.from(A.result.extensions,e=>new gO({schema:e}))}toSchema(){return new A6({value:Array.from(this.extensions,e=>e.toSchema())})}toJSON(){return{extensions:this.extensions.map(e=>e.toJSON())}}}g_.CLASS_NAME="Extensions";let gx="issuer",gL="serialNumber",gP="issuerUID",gq=[gx,gL,gP];class gK extends dX{constructor(e={}){super(),this.issuer=e2(e,gx,gK.defaultValues(gx)),this.serialNumber=e2(e,gL,gK.defaultValues(gL)),gP in e&&(this.issuerUID=e2(e,gP,gK.defaultValues(gP))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case gx:return new uS;case gL:return new AW;case gP:return new AY;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[uS.schema(A.issuer||{}),new AW({name:A.serialNumber||""}),new AY({optional:!0,name:A.issuerUID||""})]})}fromSchema(e){Ad(e,gq);let A=tb(e,e,gK.schema({names:{issuer:{names:{blockName:gx}},serialNumber:gL,issuerUID:gP}}));d$.assertSchema(A,this.className),this.issuer=new uS({schema:A.result.issuer}),this.serialNumber=A.result.serialNumber,gP in A.result&&(this.issuerUID=A.result.issuerUID)}toSchema(){let e=new A6({value:[this.issuer.toSchema(),this.serialNumber]});return this.issuerUID&&e.valueBlock.value.push(this.issuerUID),e}toJSON(){let e={issuer:this.issuer.toJSON(),serialNumber:this.serialNumber.toJSON()};return this.issuerUID&&(e.issuerUID=this.issuerUID.toJSON()),e}}gK.CLASS_NAME="IssuerSerial";let gJ="version",gF="baseCertificateID",gj="subjectName",gz="issuer",gY="signature",gZ="serialNumber",gV="attrCertValidityPeriod",gW="attributes",g$="issuerUniqueID",gX="extensions",g0=[gJ,gF,gj,gz,gY,gZ,gV,gW,g$,gX];class g1 extends dX{constructor(e={}){super(),this.version=e2(e,gJ,g1.defaultValues(gJ)),gF in e&&(this.baseCertificateID=e2(e,gF,g1.defaultValues(gF))),gj in e&&(this.subjectName=e2(e,gj,g1.defaultValues(gj))),this.issuer=e2(e,gz,g1.defaultValues(gz)),this.signature=e2(e,gY,g1.defaultValues(gY)),this.serialNumber=e2(e,gZ,g1.defaultValues(gZ)),this.attrCertValidityPeriod=e2(e,gV,g1.defaultValues(gV)),this.attributes=e2(e,gW,g1.defaultValues(gW)),g$ in e&&(this.issuerUniqueID=e2(e,g$,g1.defaultValues(g$))),gX in e&&(this.extensions=e2(e,gX,g1.defaultValues(gX))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case gJ:return 0;case gF:return new gK;case gj:case gz:return new uS;case gY:return new uh;case gZ:return new AW;case gV:return new uQ;case gW:return[];case g$:return new AY;case gX:return new g_;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new AW({name:A.version||""}),new tB({value:[new Ax({name:A.baseCertificateID||"",idBlock:{tagClass:3,tagNumber:0},value:gK.schema().valueBlock.value}),new Ax({name:A.subjectName||"",idBlock:{tagClass:3,tagNumber:1},value:uS.schema().valueBlock.value})]}),uS.schema({names:{blockName:A.issuer||""}}),uh.schema(A.signature||{}),new AW({name:A.serialNumber||""}),uQ.schema(A.attrCertValidityPeriod||{}),new A6({name:A.attributes||"",value:[new tQ({value:um.schema()})]}),new AY({optional:!0,name:A.issuerUniqueID||""}),g_.schema(A.extensions||{},!0)]})}fromSchema(e){Ad(e,g0);let A=tb(e,e,g1.schema({names:{version:gJ,baseCertificateID:gF,subjectName:gj,issuer:gz,signature:{names:{blockName:gY}},serialNumber:gZ,attrCertValidityPeriod:{names:{blockName:gV}},attributes:gW,issuerUniqueID:g$,extensions:{names:{blockName:gX}}}}));d$.assertSchema(A,this.className),this.version=A.result.version.valueBlock.valueDec,gF in A.result&&(this.baseCertificateID=new gK({schema:new A6({value:A.result.baseCertificateID.valueBlock.value})})),gj in A.result&&(this.subjectName=new uS({schema:new A6({value:A.result.subjectName.valueBlock.value})})),this.issuer=A.result.issuer,this.signature=new uh({schema:A.result.signature}),this.serialNumber=A.result.serialNumber,this.attrCertValidityPeriod=new uQ({schema:A.result.attrCertValidityPeriod}),this.attributes=Array.from(A.result.attributes.valueBlock.value,e=>new um({schema:e})),g$ in A.result&&(this.issuerUniqueID=A.result.issuerUniqueID),gX in A.result&&(this.extensions=new g_({schema:A.result.extensions}))}toSchema(){let e=new A6({value:[new AW({value:this.version})]});return this.baseCertificateID&&e.valueBlock.value.push(new Ax({idBlock:{tagClass:3,tagNumber:0},value:this.baseCertificateID.toSchema().valueBlock.value})),this.subjectName&&e.valueBlock.value.push(new Ax({idBlock:{tagClass:3,tagNumber:1},value:this.subjectName.toSchema().valueBlock.value})),e.valueBlock.value.push(this.issuer.toSchema()),e.valueBlock.value.push(this.signature.toSchema()),e.valueBlock.value.push(this.serialNumber),e.valueBlock.value.push(this.attrCertValidityPeriod.toSchema()),e.valueBlock.value.push(new A6({value:Array.from(this.attributes,e=>e.toSchema())})),this.issuerUniqueID&&e.valueBlock.value.push(this.issuerUniqueID),this.extensions&&e.valueBlock.value.push(this.extensions.toSchema()),e}toJSON(){let e={version:this.version};return this.baseCertificateID&&(e.baseCertificateID=this.baseCertificateID.toJSON()),this.subjectName&&(e.subjectName=this.subjectName.toJSON()),e.issuer=this.issuer.toJSON(),e.signature=this.signature.toJSON(),e.serialNumber=this.serialNumber.toJSON(),e.attrCertValidityPeriod=this.attrCertValidityPeriod.toJSON(),e.attributes=Array.from(this.attributes,e=>e.toJSON()),this.issuerUniqueID&&(e.issuerUniqueID=this.issuerUniqueID.toJSON()),this.extensions&&(e.extensions=this.extensions.toJSON()),e}}g1.CLASS_NAME="AttributeCertificateInfoV1";let g8="acinfo",g4="signatureAlgorithm",g2="signatureValue",g6=[g8,g2,g4];class g3 extends dX{constructor(e={}){super(),this.acinfo=e2(e,g8,g3.defaultValues(g8)),this.signatureAlgorithm=e2(e,g4,g3.defaultValues(g4)),this.signatureValue=e2(e,g2,g3.defaultValues(g2)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case g8:return new g1;case g4:return new uh;case g2:return new AY;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[g1.schema(A.acinfo||{}),uh.schema(A.signatureAlgorithm||{}),new AY({name:A.signatureValue||""})]})}fromSchema(e){Ad(e,g6);let A=tb(e,e,g3.schema({names:{acinfo:{names:{blockName:g8}},signatureAlgorithm:{names:{blockName:g4}},signatureValue:g2}}));d$.assertSchema(A,this.className),this.acinfo=new g1({schema:A.result.acinfo}),this.signatureAlgorithm=new uh({schema:A.result.signatureAlgorithm}),this.signatureValue=A.result.signatureValue}toSchema(){return new A6({value:[this.acinfo.toSchema(),this.signatureAlgorithm.toSchema(),this.signatureValue]})}toJSON(){return{acinfo:this.acinfo.toJSON(),signatureAlgorithm:this.signatureAlgorithm.toJSON(),signatureValue:this.signatureValue.toJSON()}}}g3.CLASS_NAME="AttributeCertificateV1";let g5="digestedObjectType",g9="otherObjectTypeID",g7="digestAlgorithm",pe="objectDigest",pA=[g5,g9,g7,pe];class pt extends dX{constructor(e={}){super(),this.digestedObjectType=e2(e,g5,pt.defaultValues(g5)),g9 in e&&(this.otherObjectTypeID=e2(e,g9,pt.defaultValues(g9))),this.digestAlgorithm=e2(e,g7,pt.defaultValues(g7)),this.objectDigest=e2(e,pe,pt.defaultValues(pe)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case g5:return new A$;case g9:return new A1;case g7:return new uh;case pe:return new AY;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new A$({name:A.digestedObjectType||""}),new A1({optional:!0,name:A.otherObjectTypeID||""}),uh.schema(A.digestAlgorithm||{}),new AY({name:A.objectDigest||""})]})}fromSchema(e){Ad(e,pA);let A=tb(e,e,pt.schema({names:{digestedObjectType:g5,otherObjectTypeID:g9,digestAlgorithm:{names:{blockName:g7}},objectDigest:pe}}));d$.assertSchema(A,this.className),this.digestedObjectType=A.result.digestedObjectType,g9 in A.result&&(this.otherObjectTypeID=A.result.otherObjectTypeID),this.digestAlgorithm=new uh({schema:A.result.digestAlgorithm}),this.objectDigest=A.result.objectDigest}toSchema(){let e=new A6({value:[this.digestedObjectType]});return this.otherObjectTypeID&&e.valueBlock.value.push(this.otherObjectTypeID),e.valueBlock.value.push(this.digestAlgorithm.toSchema()),e.valueBlock.value.push(this.objectDigest),e}toJSON(){let e={digestedObjectType:this.digestedObjectType.toJSON(),digestAlgorithm:this.digestAlgorithm.toJSON(),objectDigest:this.objectDigest.toJSON()};return this.otherObjectTypeID&&(e.otherObjectTypeID=this.otherObjectTypeID.toJSON()),e}}pt.CLASS_NAME="ObjectDigestInfo";let pr="issuerName",pi="baseCertificateID",pn="objectDigestInfo",pa=[pr,pi,pn];class po extends dX{constructor(e={}){super(),pr in e&&(this.issuerName=e2(e,pr,po.defaultValues(pr))),pi in e&&(this.baseCertificateID=e2(e,pi,po.defaultValues(pi))),pn in e&&(this.objectDigestInfo=e2(e,pn,po.defaultValues(pn))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case pr:return new uS;case pi:return new gK;case pn:return new pt;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[uS.schema({names:{blockName:A.issuerName}},!0),new Ax({optional:!0,name:A.baseCertificateID||"",idBlock:{tagClass:3,tagNumber:0},value:gK.schema().valueBlock.value}),new Ax({optional:!0,name:A.objectDigestInfo||"",idBlock:{tagClass:3,tagNumber:1},value:pt.schema().valueBlock.value})]})}fromSchema(e){Ad(e,pa);let A=tb(e,e,po.schema({names:{issuerName:pr,baseCertificateID:pi,objectDigestInfo:pn}}));d$.assertSchema(A,this.className),pr in A.result&&(this.issuerName=new uS({schema:A.result.issuerName})),pi in A.result&&(this.baseCertificateID=new gK({schema:new A6({value:A.result.baseCertificateID.valueBlock.value})})),pn in A.result&&(this.objectDigestInfo=new pt({schema:new A6({value:A.result.objectDigestInfo.valueBlock.value})}))}toSchema(){let e=new A6;return this.issuerName&&e.valueBlock.value.push(this.issuerName.toSchema()),this.baseCertificateID&&e.valueBlock.value.push(new Ax({idBlock:{tagClass:3,tagNumber:0},value:this.baseCertificateID.toSchema().valueBlock.value})),this.objectDigestInfo&&e.valueBlock.value.push(new Ax({idBlock:{tagClass:3,tagNumber:1},value:this.objectDigestInfo.toSchema().valueBlock.value})),e}toJSON(){let e={};return this.issuerName&&(e.issuerName=this.issuerName.toJSON()),this.baseCertificateID&&(e.baseCertificateID=this.baseCertificateID.toJSON()),this.objectDigestInfo&&(e.objectDigestInfo=this.objectDigestInfo.toJSON()),e}}po.CLASS_NAME="V2Form";let ps="baseCertificateID",pl="entityName",pd="objectDigestInfo",pu=[ps,pl,pd];class pc extends dX{constructor(e={}){super(),ps in e&&(this.baseCertificateID=e2(e,ps,pc.defaultValues(ps))),pl in e&&(this.entityName=e2(e,pl,pc.defaultValues(pl))),pd in e&&(this.objectDigestInfo=e2(e,pd,pc.defaultValues(pd))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case ps:return new gK;case pl:return new uS;case pd:return new pt;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new Ax({optional:!0,name:A.baseCertificateID||"",idBlock:{tagClass:3,tagNumber:0},value:gK.schema().valueBlock.value}),new Ax({optional:!0,name:A.entityName||"",idBlock:{tagClass:3,tagNumber:1},value:uS.schema().valueBlock.value}),new Ax({optional:!0,name:A.objectDigestInfo||"",idBlock:{tagClass:3,tagNumber:2},value:pt.schema().valueBlock.value})]})}fromSchema(e){Ad(e,pu);let A=tb(e,e,pc.schema({names:{baseCertificateID:ps,entityName:pl,objectDigestInfo:pd}}));d$.assertSchema(A,this.className),ps in A.result&&(this.baseCertificateID=new gK({schema:new A6({value:A.result.baseCertificateID.valueBlock.value})})),pl in A.result&&(this.entityName=new uS({schema:new A6({value:A.result.entityName.valueBlock.value})})),pd in A.result&&(this.objectDigestInfo=new pt({schema:new A6({value:A.result.objectDigestInfo.valueBlock.value})}))}toSchema(){let e=new A6;return this.baseCertificateID&&e.valueBlock.value.push(new Ax({idBlock:{tagClass:3,tagNumber:0},value:this.baseCertificateID.toSchema().valueBlock.value})),this.entityName&&e.valueBlock.value.push(new Ax({idBlock:{tagClass:3,tagNumber:1},value:this.entityName.toSchema().valueBlock.value})),this.objectDigestInfo&&e.valueBlock.value.push(new Ax({idBlock:{tagClass:3,tagNumber:2},value:this.objectDigestInfo.toSchema().valueBlock.value})),e}toJSON(){let e={};return this.baseCertificateID&&(e.baseCertificateID=this.baseCertificateID.toJSON()),this.entityName&&(e.entityName=this.entityName.toJSON()),this.objectDigestInfo&&(e.objectDigestInfo=this.objectDigestInfo.toJSON()),e}}pc.CLASS_NAME="Holder";let ph="version",pg="holder",pp="issuer",pC="signature",pf="serialNumber",pI="attrCertValidityPeriod",pw="attributes",pm="issuerUniqueID",pE="extensions",py=[ph,pg,pp,pC,pf,pI,pw,pm,pE];class pB extends dX{constructor(e={}){super(),this.version=e2(e,ph,pB.defaultValues(ph)),this.holder=e2(e,pg,pB.defaultValues(pg)),this.issuer=e2(e,pp,pB.defaultValues(pp)),this.signature=e2(e,pC,pB.defaultValues(pC)),this.serialNumber=e2(e,pf,pB.defaultValues(pf)),this.attrCertValidityPeriod=e2(e,pI,pB.defaultValues(pI)),this.attributes=e2(e,pw,pB.defaultValues(pw)),pm in e&&(this.issuerUniqueID=e2(e,pm,pB.defaultValues(pm))),pE in e&&(this.extensions=e2(e,pE,pB.defaultValues(pE))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case ph:return 1;case pg:return new pc;case pp:return{};case pC:return new uh;case pf:return new AW;case pI:return new uQ;case pw:return[];case pm:return new AY;case pE:return new g_;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new AW({name:A.version||""}),pc.schema(A.holder||{}),new tB({value:[uS.schema({names:{blockName:A.issuer||""}}),new Ax({name:A.issuer||"",idBlock:{tagClass:3,tagNumber:0},value:po.schema().valueBlock.value})]}),uh.schema(A.signature||{}),new AW({name:A.serialNumber||""}),uQ.schema(A.attrCertValidityPeriod||{}),new A6({name:A.attributes||"",value:[new tQ({value:um.schema()})]}),new AY({optional:!0,name:A.issuerUniqueID||""}),g_.schema(A.extensions||{},!0)]})}fromSchema(e){Ad(e,py);let A=tb(e,e,pB.schema({names:{version:ph,holder:{names:{blockName:pg}},issuer:pp,signature:{names:{blockName:pC}},serialNumber:pf,attrCertValidityPeriod:{names:{blockName:pI}},attributes:pw,issuerUniqueID:pm,extensions:{names:{blockName:pE}}}}));if(d$.assertSchema(A,this.className),this.version=A.result.version.valueBlock.valueDec,this.holder=new pc({schema:A.result.holder}),3===A.result.issuer.idBlock.tagClass)this.issuer=new po({schema:new A6({value:A.result.issuer.valueBlock.value})});else throw Error("Incorrect value for 'issuer' in AttributeCertificateInfoV2");this.signature=new uh({schema:A.result.signature}),this.serialNumber=A.result.serialNumber,this.attrCertValidityPeriod=new uQ({schema:A.result.attrCertValidityPeriod}),this.attributes=Array.from(A.result.attributes.valueBlock.value,e=>new um({schema:e})),pm in A.result&&(this.issuerUniqueID=A.result.issuerUniqueID),pE in A.result&&(this.extensions=new g_({schema:A.result.extensions}))}toSchema(){let e=new A6({value:[new AW({value:this.version}),this.holder.toSchema(),new Ax({idBlock:{tagClass:3,tagNumber:0},value:this.issuer.toSchema().valueBlock.value}),this.signature.toSchema(),this.serialNumber,this.attrCertValidityPeriod.toSchema(),new A6({value:Array.from(this.attributes,e=>e.toSchema())})]});return this.issuerUniqueID&&e.valueBlock.value.push(this.issuerUniqueID),this.extensions&&e.valueBlock.value.push(this.extensions.toSchema()),e}toJSON(){let e={version:this.version,holder:this.holder.toJSON(),issuer:this.issuer.toJSON(),signature:this.signature.toJSON(),serialNumber:this.serialNumber.toJSON(),attrCertValidityPeriod:this.attrCertValidityPeriod.toJSON(),attributes:Array.from(this.attributes,e=>e.toJSON())};return this.issuerUniqueID&&(e.issuerUniqueID=this.issuerUniqueID.toJSON()),this.extensions&&(e.extensions=this.extensions.toJSON()),e}}pB.CLASS_NAME="AttributeCertificateInfoV2";let pQ="acinfo",pD="signatureAlgorithm",pb="signatureValue",pS=[pQ,pD,pb];class pk extends dX{constructor(e={}){super(),this.acinfo=e2(e,pQ,pk.defaultValues(pQ)),this.signatureAlgorithm=e2(e,pD,pk.defaultValues(pD)),this.signatureValue=e2(e,pb,pk.defaultValues(pb)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case pQ:return new pB;case pD:return new uh;case pb:return new AY;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[pB.schema(A.acinfo||{}),uh.schema(A.signatureAlgorithm||{}),new AY({name:A.signatureValue||""})]})}fromSchema(e){Ad(e,pS);let A=tb(e,e,pk.schema({names:{acinfo:{names:{blockName:pQ}},signatureAlgorithm:{names:{blockName:pD}},signatureValue:pb}}));d$.assertSchema(A,this.className),this.acinfo=new pB({schema:A.result.acinfo}),this.signatureAlgorithm=new uh({schema:A.result.signatureAlgorithm}),this.signatureValue=A.result.signatureValue}toSchema(){return new A6({value:[this.acinfo.toSchema(),this.signatureAlgorithm.toSchema(),this.signatureValue]})}toJSON(){return{acinfo:this.acinfo.toJSON(),signatureAlgorithm:this.signatureAlgorithm.toJSON(),signatureValue:this.signatureValue.toJSON()}}}pk.CLASS_NAME="AttributeCertificateV2";let pR="contentType",pv="content",pG=[pR,pv];class pT extends dX{constructor(e={}){super(),this.contentType=e2(e,pR,pT.defaultValues(pR)),this.content=e2(e,pv,pT.defaultValues(pv)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case pR:return"";case pv:return new ty;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case pR:return"string"==typeof A&&A===this.defaultValues(pR);case pv:return A instanceof ty;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return"optional"in A==!1&&(A.optional=!1),new A6({name:A.blockName||"ContentInfo",optional:A.optional,value:[new A1({name:A.contentType||pR}),new Ax({idBlock:{tagClass:3,tagNumber:0},value:[new ty({name:A.content||pv})]})]})}fromSchema(e){Ad(e,pG);let A=tb(e,e,pT.schema());d$.assertSchema(A,this.className),this.contentType=A.result.contentType.valueBlock.toString(),this.content=A.result.content}toSchema(){return new A6({value:[new A1({value:this.contentType}),new Ax({idBlock:{tagClass:3,tagNumber:0},value:[this.content]})]})}toJSON(){let e={contentType:this.contentType};return this.content instanceof ty||(e.content=this.content.toJSON()),e}}pT.CLASS_NAME="ContentInfo",pT.DATA=uq,pT.SIGNED_DATA=uK,pT.ENVELOPED_DATA=uJ,pT.ENCRYPTED_DATA=uF;let pM="type",pN="value",pO="utcTimeName",pH="generalTimeName",pU=[pO,pH];(w=ej||(ej={}))[w.UTCTime=0]="UTCTime",w[w.GeneralizedTime=1]="GeneralizedTime",w[w.empty=2]="empty";class p_ extends dX{constructor(e={}){super(),this.type=e2(e,pM,p_.defaultValues(pM)),this.value=e2(e,pN,p_.defaultValues(pN)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case pM:return 0;case pN:return new Date(0,0,0);default:return super.defaultValues(e)}}static schema(e={},A=!1){let t=e2(e,"names",{});return new tB({optional:A,value:[new tp({name:t.utcTimeName||""}),new tC({name:t.generalTimeName||""})]})}fromSchema(e){Ad(e,pU);let A=tb(e,e,p_.schema({names:{utcTimeName:pO,generalTimeName:pH}}));d$.assertSchema(A,this.className),pO in A.result&&(this.type=0,this.value=A.result.utcTimeName.toDate()),pH in A.result&&(this.type=1,this.value=A.result.generalTimeName.toDate())}toSchema(){return 0===this.type?new tp({valueDate:this.value}):1===this.type?new tC({valueDate:this.value}):{}}toJSON(){return{type:this.type,value:this.value}}}p_.CLASS_NAME="Time";let px="version",pL="serialNumber",pP="signature",pq="issuer",pK="notBefore",pJ="notAfter",pF="subject",pj="subjectPublicKeyInfo",pz="issuerUniqueID",pY="subjectUniqueID",pZ="extensions",pV="signatureAlgorithm",pW="signatureValue",p$="tbsCertificate",pX=`${p$}.${px}`,p0=`${p$}.${pL}`,p1=`${p$}.${pP}`,p8=`${p$}.${pq}`,p4=`${p$}.${pK}`,p2=`${p$}.${pJ}`,p6=`${p$}.${pF}`,p3=`${p$}.${pj}`,p5=`${p$}.${pz}`,p9=`${p$}.${pY}`,p7=`${p$}.${pZ}`,Ce=[p$,pX,p0,p1,p8,p4,p2,p6,p3,p5,p9,p7,pV,pW];class CA extends dX{get tbs(){return eV.toArrayBuffer(this.tbsView)}set tbs(e){this.tbsView=new Uint8Array(e)}constructor(e={}){super(),this.tbsView=new Uint8Array(e2(e,"tbs",CA.defaultValues("tbs"))),this.version=e2(e,px,CA.defaultValues(px)),this.serialNumber=e2(e,pL,CA.defaultValues(pL)),this.signature=e2(e,pP,CA.defaultValues(pP)),this.issuer=e2(e,pq,CA.defaultValues(pq)),this.notBefore=e2(e,pK,CA.defaultValues(pK)),this.notAfter=e2(e,pJ,CA.defaultValues(pJ)),this.subject=e2(e,pF,CA.defaultValues(pF)),this.subjectPublicKeyInfo=e2(e,pj,CA.defaultValues(pj)),pz in e&&(this.issuerUniqueID=e2(e,pz,CA.defaultValues(pz))),pY in e&&(this.subjectUniqueID=e2(e,pY,CA.defaultValues(pY))),pZ in e&&(this.extensions=e2(e,pZ,CA.defaultValues(pZ))),this.signatureAlgorithm=e2(e,pV,CA.defaultValues(pV)),this.signatureValue=e2(e,pW,CA.defaultValues(pW)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case"tbs":return dZ;case px:return 0;case pL:return new AW;case pP:return new uh;case pq:return new d3;case pK:case pJ:return new p_;case pF:return new d3;case pj:return new hc;case pz:case pY:return dZ;case pZ:return[];case pV:return new uh;case pW:return new AY;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[function(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||p$,value:[new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new AW({name:A.tbsCertificateVersion||pX})]}),new AW({name:A.tbsCertificateSerialNumber||p0}),uh.schema(A.signature||{names:{blockName:p1}}),d3.schema(A.issuer||{names:{blockName:p8}}),new A6({name:A.tbsCertificateValidity||"tbsCertificate.validity",value:[p_.schema(A.notBefore||{names:{utcTimeName:p4,generalTimeName:p4}}),p_.schema(A.notAfter||{names:{utcTimeName:p2,generalTimeName:p2}})]}),d3.schema(A.subject||{names:{blockName:p6}}),hc.schema(A.subjectPublicKeyInfo||{names:{blockName:p3}}),new AM({name:A.tbsCertificateIssuerUniqueID||p5,optional:!0,idBlock:{tagClass:3,tagNumber:1}}),new AM({name:A.tbsCertificateSubjectUniqueID||p9,optional:!0,idBlock:{tagClass:3,tagNumber:2}}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:3},value:[g_.schema(A.extensions||{names:{blockName:p7}})]})]})}(A.tbsCertificate),uh.schema(A.signatureAlgorithm||{names:{blockName:pV}}),new AY({name:A.signatureValue||pW})]})}fromSchema(e){Ad(e,Ce);let A=tb(e,e,CA.schema({names:{tbsCertificate:{names:{extensions:{names:{extensions:p7}}}}}}));d$.assertSchema(A,this.className),this.tbsView=A.result.tbsCertificate.valueBeforeDecodeView,pX in A.result&&(this.version=A.result[pX].valueBlock.valueDec),this.serialNumber=A.result[p0],this.signature=new uh({schema:A.result[p1]}),this.issuer=new d3({schema:A.result[p8]}),this.notBefore=new p_({schema:A.result[p4]}),this.notAfter=new p_({schema:A.result[p2]}),this.subject=new d3({schema:A.result[p6]}),this.subjectPublicKeyInfo=new hc({schema:A.result[p3]}),p5 in A.result&&(this.issuerUniqueID=A.result[p5].valueBlock.valueHex),p9 in A.result&&(this.subjectUniqueID=A.result[p9].valueBlock.valueHex),p7 in A.result&&(this.extensions=Array.from(A.result[p7],e=>new gO({schema:e}))),this.signatureAlgorithm=new uh({schema:A.result.signatureAlgorithm}),this.signatureValue=A.result.signatureValue}encodeTBS(){let e=[];return px in this&&this.version!==CA.defaultValues(px)&&e.push(new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new AW({value:this.version})]})),e.push(this.serialNumber),e.push(this.signature.toSchema()),e.push(this.issuer.toSchema()),e.push(new A6({value:[this.notBefore.toSchema(),this.notAfter.toSchema()]})),e.push(this.subject.toSchema()),e.push(this.subjectPublicKeyInfo.toSchema()),this.issuerUniqueID&&e.push(new AM({optional:!0,idBlock:{tagClass:3,tagNumber:1},valueHex:this.issuerUniqueID})),this.subjectUniqueID&&e.push(new AM({optional:!0,idBlock:{tagClass:3,tagNumber:2},valueHex:this.subjectUniqueID})),this.extensions&&e.push(new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:3},value:[new A6({value:Array.from(this.extensions,e=>e.toSchema())})]})),new A6({value:e})}toSchema(e=!1){let A;if(!1===e){if(!this.tbsView.byteLength)return CA.schema().value[0];let e=AU(this.tbsView);d$.assert(e,"TBS Certificate"),A=e.result}else A=this.encodeTBS();return new A6({value:[A,this.signatureAlgorithm.toSchema(),this.signatureValue]})}toJSON(){let e={tbs:e4.ToHex(this.tbsView),version:this.version,serialNumber:this.serialNumber.toJSON(),signature:this.signature.toJSON(),issuer:this.issuer.toJSON(),notBefore:this.notBefore.toJSON(),notAfter:this.notAfter.toJSON(),subject:this.subject.toJSON(),subjectPublicKeyInfo:this.subjectPublicKeyInfo.toJSON(),signatureAlgorithm:this.signatureAlgorithm.toJSON(),signatureValue:this.signatureValue.toJSON()};return px in this&&this.version!==CA.defaultValues(px)&&(e.version=this.version),this.issuerUniqueID&&(e.issuerUniqueID=e4.ToHex(this.issuerUniqueID)),this.subjectUniqueID&&(e.subjectUniqueID=e4.ToHex(this.subjectUniqueID)),this.extensions&&(e.extensions=Array.from(this.extensions,e=>e.toJSON())),e}async getPublicKey(e,A=gn(!0)){return A.getPublicKey(this.subjectPublicKeyInfo,this.signatureAlgorithm,e)}async getKeyHash(e="SHA-1",A=gn(!0)){return A.digest({name:e},this.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView)}async sign(e,A="SHA-1",t=gn(!0)){if(!e)throw Error("Need to provide a private key for signing");let r=await t.getSignatureParameters(e,A),i=r.parameters;this.signature=r.signatureAlgorithm,this.signatureAlgorithm=r.signatureAlgorithm,this.tbsView=new Uint8Array(this.encodeTBS().toBER());let n=await t.signWithPrivateKey(this.tbsView,e,i);this.signatureValue=new AY({valueHex:n})}async verify(e,A=gn(!0)){let t;if(e?t=e.subjectPublicKeyInfo:this.issuer.isEqual(this.subject)&&(t=this.subjectPublicKeyInfo),!(t instanceof hc))throw Error("Please provide issuer certificate as a parameter");return A.verifyWithPublicKey(this.tbsView,this.signatureValue,t,this.signatureAlgorithm)}}function Ct(e,A=null){if(A&&e.issuer.isEqual(A.issuer)&&e.serialNumber.isEqual(A.serialNumber))return null;let t=!1;if(e.extensions){for(let A of e.extensions)if(A.extnID===uv&&A.parsedValue instanceof u8&&A.parsedValue.cA){t=!0;break}}return t?e:null}CA.CLASS_NAME="Certificate";let Cr="certId",Ci="certValue",Cn="parsedValue",Ca=[Cr,Ci];class Co extends dX{constructor(e={}){super(),this.certId=e2(e,Cr,Co.defaultValues(Cr)),this.certValue=e2(e,Ci,Co.defaultValues(Ci)),Cn in e&&(this.parsedValue=e2(e,Cn,Co.defaultValues(Cn))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Cr:return"";case Ci:return new ty;case Cn:return{};default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case Cr:return""===A;case Ci:return A instanceof ty;case Cn:return A instanceof Object&&0===Object.keys(A).length;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new A1({name:A.id||"id"}),new Ax({idBlock:{tagClass:3,tagNumber:0},value:[new ty({name:A.value||"value"})]})]})}fromSchema(e){Ad(e,Ca);let A=tb(e,e,Co.schema({names:{id:Cr,value:Ci}}));d$.assertSchema(A,this.className),this.certId=A.result.certId.valueBlock.toString(),this.certValue=A.result.certValue;let t=this.certValue.valueBlock.valueHexView;switch(this.certId){case uj:try{this.parsedValue=CA.fromBER(t)}catch{pk.fromBER(t)}break;case uz:this.parsedValue=pk.fromBER(t);break;default:throw Error(`Incorrect CERT_ID value in CertBag: ${this.certId}`)}}toSchema(){return Cn in this&&("acinfo"in this.parsedValue?this.certId=uz:this.certId=uj,this.certValue=new Aj({valueHex:this.parsedValue.toSchema().toBER(!1)})),new A6({value:[new A1({value:this.certId}),new Ax({idBlock:{tagClass:3,tagNumber:0},value:["toSchema"in this.certValue?this.certValue.toSchema():this.certValue]})]})}toJSON(){return{certId:this.certId,certValue:this.certValue.toJSON()}}}Co.CLASS_NAME="CertBag";let Cs="userCertificate",Cl="revocationDate",Cd="crlEntryExtensions",Cu=[Cs,Cl,Cd];class Cc extends dX{constructor(e={}){super(),this.userCertificate=e2(e,Cs,Cc.defaultValues(Cs)),this.revocationDate=e2(e,Cl,Cc.defaultValues(Cl)),Cd in e&&(this.crlEntryExtensions=e2(e,Cd,Cc.defaultValues(Cd))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Cs:return new AW;case Cl:return new p_;case Cd:return new g_;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new AW({name:A.userCertificate||Cs}),p_.schema({names:{utcTimeName:A.revocationDate||Cl,generalTimeName:A.revocationDate||Cl}}),g_.schema({names:{blockName:A.crlEntryExtensions||Cd}},!0)]})}fromSchema(e){Ad(e,Cu);let A=tb(e,e,Cc.schema());d$.assertSchema(A,this.className),this.userCertificate=A.result.userCertificate,this.revocationDate=new p_({schema:A.result.revocationDate}),Cd in A.result&&(this.crlEntryExtensions=new g_({schema:A.result.crlEntryExtensions}))}toSchema(){let e=[this.userCertificate,this.revocationDate.toSchema()];return this.crlEntryExtensions&&e.push(this.crlEntryExtensions.toSchema()),new A6({value:e})}toJSON(){let e={userCertificate:this.userCertificate.toJSON(),revocationDate:this.revocationDate.toJSON()};return this.crlEntryExtensions&&(e.crlEntryExtensions=this.crlEntryExtensions.toJSON()),e}}Cc.CLASS_NAME="RevokedCertificate";let Ch="version",Cg="signature",Cp="issuer",CC="thisUpdate",Cf="nextUpdate",CI="revokedCertificates",Cw="crlExtensions",Cm="signatureAlgorithm",CE="signatureValue",Cy="tbsCertList",CB=`${Cy}.version`,CQ=`${Cy}.signature`,CD=`${Cy}.issuer`,Cb=`${Cy}.thisUpdate`,CS=`${Cy}.nextUpdate`,Ck=`${Cy}.revokedCertificates`,CR=`${Cy}.extensions`,Cv=[Cy,CB,CQ,CD,Cb,CS,Ck,CR,Cm,CE],CG=[ux,uR,"2.5.29.20","2.5.29.27",uG,uO,uP,"2.5.29.21","2.5.29.24",uT];class CT extends dX{get tbs(){return eV.toArrayBuffer(this.tbsView)}set tbs(e){this.tbsView=new Uint8Array(e)}constructor(e={}){super(),this.tbsView=new Uint8Array(e2(e,"tbs",CT.defaultValues("tbs"))),this.version=e2(e,Ch,CT.defaultValues(Ch)),this.signature=e2(e,Cg,CT.defaultValues(Cg)),this.issuer=e2(e,Cp,CT.defaultValues(Cp)),this.thisUpdate=e2(e,CC,CT.defaultValues(CC)),Cf in e&&(this.nextUpdate=e2(e,Cf,CT.defaultValues(Cf))),CI in e&&(this.revokedCertificates=e2(e,CI,CT.defaultValues(CI))),Cw in e&&(this.crlExtensions=e2(e,Cw,CT.defaultValues(Cw))),this.signatureAlgorithm=e2(e,Cm,CT.defaultValues(Cm)),this.signatureValue=e2(e,CE,CT.defaultValues(CE)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case"tbs":return dZ;case Ch:return 0;case Cg:return new uh;case Cp:return new d3;case CC:case Cf:return new p_;case CI:return[];case Cw:return new g_;case Cm:return new uh;case CE:return new AY;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"CertificateList",value:[function(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||Cy,value:[new AW({optional:!0,name:A.tbsCertListVersion||CB,value:2}),uh.schema(A.signature||{names:{blockName:CQ}}),d3.schema(A.issuer||{names:{blockName:CD}}),p_.schema(A.tbsCertListThisUpdate||{names:{utcTimeName:Cb,generalTimeName:Cb}}),p_.schema(A.tbsCertListNextUpdate||{names:{utcTimeName:CS,generalTimeName:CS}},!0),new A6({optional:!0,value:[new tQ({name:A.tbsCertListRevokedCertificates||Ck,value:new A6({value:[new AW,p_.schema(),g_.schema({},!0)]})})]}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[g_.schema(A.crlExtensions||{names:{blockName:CR}})]})]})}(e),uh.schema(A.signatureAlgorithm||{names:{blockName:Cm}}),new AY({name:A.signatureValue||CE})]})}fromSchema(e){Ad(e,Cv);let A=tb(e,e,CT.schema());d$.assertSchema(A,this.className),this.tbsView=A.result.tbsCertList.valueBeforeDecodeView,CB in A.result&&(this.version=A.result[CB].valueBlock.valueDec),this.signature=new uh({schema:A.result[CQ]}),this.issuer=new d3({schema:A.result[CD]}),this.thisUpdate=new p_({schema:A.result[Cb]}),CS in A.result&&(this.nextUpdate=new p_({schema:A.result[CS]})),Ck in A.result&&(this.revokedCertificates=Array.from(A.result[Ck],e=>new Cc({schema:e}))),CR in A.result&&(this.crlExtensions=new g_({schema:A.result[CR]})),this.signatureAlgorithm=new uh({schema:A.result.signatureAlgorithm}),this.signatureValue=A.result.signatureValue}encodeTBS(){let e=[];return this.version!==CT.defaultValues(Ch)&&e.push(new AW({value:this.version})),e.push(this.signature.toSchema()),e.push(this.issuer.toSchema()),e.push(this.thisUpdate.toSchema()),this.nextUpdate&&e.push(this.nextUpdate.toSchema()),this.revokedCertificates&&e.push(new A6({value:Array.from(this.revokedCertificates,e=>e.toSchema())})),this.crlExtensions&&e.push(new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[this.crlExtensions.toSchema()]})),new A6({value:e})}toSchema(e=!1){let A;if(e)A=this.encodeTBS();else{if(!this.tbsView.byteLength)return CT.schema();let e=AU(this.tbsView);d$.assert(e,"TBS Certificate Revocation List"),A=e.result}return new A6({value:[A,this.signatureAlgorithm.toSchema(),this.signatureValue]})}toJSON(){let e={tbs:e4.ToHex(this.tbsView),version:this.version,signature:this.signature.toJSON(),issuer:this.issuer.toJSON(),thisUpdate:this.thisUpdate.toJSON(),signatureAlgorithm:this.signatureAlgorithm.toJSON(),signatureValue:this.signatureValue.toJSON()};return this.version!==CT.defaultValues(Ch)&&(e.version=this.version),this.nextUpdate&&(e.nextUpdate=this.nextUpdate.toJSON()),this.revokedCertificates&&(e.revokedCertificates=Array.from(this.revokedCertificates,e=>e.toJSON())),this.crlExtensions&&(e.crlExtensions=this.crlExtensions.toJSON()),e}isCertificateRevoked(e){if(!this.issuer.isEqual(e.issuer)||!this.revokedCertificates)return!1;for(let A of this.revokedCertificates)if(A.userCertificate.isEqual(e.serialNumber))return!0;return!1}async sign(e,A="SHA-1",t=gn(!0)){if(!e)throw Error("Need to provide a private key for signing");let r=await t.getSignatureParameters(e,A),{parameters:i}=r;this.signature=r.signatureAlgorithm,this.signatureAlgorithm=r.signatureAlgorithm,this.tbsView=new Uint8Array(this.encodeTBS().toBER());let n=await t.signWithPrivateKey(this.tbsView,e,i);this.signatureValue=new AY({valueHex:n})}async verify(e={},A=gn(!0)){let t;if(e.issuerCertificate&&(t=e.issuerCertificate.subjectPublicKeyInfo,!this.issuer.isEqual(e.issuerCertificate.subject)))return!1;if(e.publicKeyInfo&&(t=e.publicKeyInfo),!t)throw Error("Issuer's certificate must be provided as an input parameter");if(this.crlExtensions){for(let e of this.crlExtensions.extensions)if(e.critical&&!CG.includes(e.extnID))return!1}return A.verifyWithPublicKey(this.tbsView,this.signatureValue,t,this.signatureAlgorithm)}}CT.CLASS_NAME="CertificateRevocationList";let CM="crlId",CN="crlValue",CO="parsedValue",CH=[CM,CN];class CU extends dX{constructor(e={}){super(),this.crlId=e2(e,CM,CU.defaultValues(CM)),this.crlValue=e2(e,CN,CU.defaultValues(CN)),CO in e&&(this.parsedValue=e2(e,CO,CU.defaultValues(CO))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case CM:return"";case CN:return new ty;case CO:return{};default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case CM:return""===A;case CN:return A instanceof ty;case CO:return A instanceof Object&&0===Object.keys(A).length;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new A1({name:A.id||"id"}),new Ax({idBlock:{tagClass:3,tagNumber:0},value:[new ty({name:A.value||"value"})]})]})}fromSchema(e){Ad(e,CH);let A=tb(e,e,CU.schema({names:{id:CM,value:CN}}));if(d$.assertSchema(A,this.className),this.crlId=A.result.crlId.valueBlock.toString(),this.crlValue=A.result.crlValue,this.crlId===uY)this.parsedValue=CT.fromBER(this.certValue.valueBlock.valueHex);else throw Error(`Incorrect CRL_ID value in CRLBag: ${this.crlId}`)}toSchema(){return this.parsedValue&&(this.crlId=uY,this.crlValue=new Aj({valueHex:this.parsedValue.toSchema().toBER(!1)})),new A6({value:[new A1({value:this.crlId}),new Ax({idBlock:{tagClass:3,tagNumber:0},value:[this.crlValue.toSchema()]})]})}toJSON(){return{crlId:this.crlId,crlValue:this.crlValue.toJSON()}}}CU.CLASS_NAME="CRLBag";let C_="version",Cx="encryptedContentInfo",CL="unprotectedAttrs",CP=[C_,Cx,CL];class Cq extends dX{constructor(e={}){super(),this.version=e2(e,C_,Cq.defaultValues(C_)),this.encryptedContentInfo=e2(e,Cx,Cq.defaultValues(Cx)),CL in e&&(this.unprotectedAttrs=e2(e,CL,Cq.defaultValues(CL))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case C_:return 0;case Cx:return new hz;case CL:return[];default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case C_:return 0===A;case Cx:return hz.compareWithDefault("contentType",A.contentType)&&hz.compareWithDefault("contentEncryptionAlgorithm",A.contentEncryptionAlgorithm)&&hz.compareWithDefault("encryptedContent",A.encryptedContent);case CL:return 0===A.length;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new AW({name:A.version||""}),hz.schema(A.encryptedContentInfo||{}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new tQ({name:A.unprotectedAttrs||"",value:um.schema()})]})]})}fromSchema(e){Ad(e,CP);let A=tb(e,e,Cq.schema({names:{version:C_,encryptedContentInfo:{names:{blockName:Cx}},unprotectedAttrs:CL}}));d$.assertSchema(A,this.className),this.version=A.result.version.valueBlock.valueDec,this.encryptedContentInfo=new hz({schema:A.result.encryptedContentInfo}),CL in A.result&&(this.unprotectedAttrs=Array.from(A.result.unprotectedAttrs,e=>new um({schema:e})))}toSchema(){let e=[];return e.push(new AW({value:this.version})),e.push(this.encryptedContentInfo.toSchema()),this.unprotectedAttrs&&e.push(new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:Array.from(this.unprotectedAttrs,e=>e.toSchema())})),new A6({value:e})}toJSON(){let e={version:this.version,encryptedContentInfo:this.encryptedContentInfo.toJSON()};return this.unprotectedAttrs&&(e.unprotectedAttrs=Array.from(this.unprotectedAttrs,e=>e.toJSON())),e}async encrypt(e,A=gn(!0)){dV.assert(e,"parameters","object");let t={...e,contentType:"1.2.840.113549.1.7.1"};this.encryptedContentInfo=await A.encryptEncryptedContentInfo(t)}async decrypt(e,A=gn(!0)){dV.assert(e,"parameters","object");let t={...e,encryptedContentInfo:this.encryptedContentInfo};return A.decryptEncryptedContentInfo(t)}}Cq.CLASS_NAME="EncryptedData";let CK="encryptionAlgorithm",CJ="encryptedData",CF="parsedValue",Cj=[CK,CJ];class Cz extends dX{constructor(e={}){super(),this.encryptionAlgorithm=e2(e,CK,Cz.defaultValues(CK)),this.encryptedData=e2(e,CJ,Cz.defaultValues(CJ)),CF in e&&(this.parsedValue=e2(e,CF,Cz.defaultValues(CF))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case CK:return new uh;case CJ:return new Aj;case CF:return{};default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case CK:return uh.compareWithDefault("algorithmId",A.algorithmId)&&"algorithmParams"in A==!1;case CJ:return A.isEqual(Cz.defaultValues(e));case CF:return A instanceof Object&&0===Object.keys(A).length;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[uh.schema(A.encryptionAlgorithm||{names:{blockName:CK}}),new tB({value:[new Aj({name:A.encryptedData||CJ}),new Aj({idBlock:{isConstructed:!0},name:A.encryptedData||CJ})]})]})}fromSchema(e){Ad(e,Cj);let A=tb(e,e,Cz.schema({names:{encryptionAlgorithm:{names:{blockName:CK}},encryptedData:CJ}}));d$.assertSchema(A,this.className),this.encryptionAlgorithm=new uh({schema:A.result.encryptionAlgorithm}),this.encryptedData=A.result.encryptedData}toSchema(){return new A6({value:[this.encryptionAlgorithm.toSchema(),this.encryptedData]})}toJSON(){return{encryptionAlgorithm:this.encryptionAlgorithm.toJSON(),encryptedData:this.encryptedData.toJSON()}}async parseInternalValues(e,A=gn(!0)){let t=new Cq({encryptedContentInfo:new hz({contentEncryptionAlgorithm:this.encryptionAlgorithm,encryptedContent:this.encryptedData})}),r=await t.decrypt(e,A);this.parsedValue=hq.fromBER(r)}async makeInternalValues(e,A=gn(!0)){if(!this.parsedValue)throw Error('Please initialize "parsedValue" first');let t=new Cq,r={...e,contentToEncrypt:this.parsedValue.toSchema().toBER(!1)};if(await t.encrypt(r,A),!t.encryptedContentInfo.encryptedContent)throw Error("The filed `encryptedContent` in EncryptedContentInfo is empty");this.encryptionAlgorithm=t.encryptedContentInfo.contentEncryptionAlgorithm,this.encryptedData=t.encryptedContentInfo.encryptedContent}}Cz.CLASS_NAME="PKCS8ShroudedKeyBag";let CY="secretTypeId",CZ="secretValue",CV=[CY,CZ];class CW extends dX{constructor(e={}){super(),this.secretTypeId=e2(e,CY,CW.defaultValues(CY)),this.secretValue=e2(e,CZ,CW.defaultValues(CZ)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case CY:return"";case CZ:return new ty;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case CY:return""===A;case CZ:return A instanceof ty;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new A1({name:A.id||"id"}),new Ax({idBlock:{tagClass:3,tagNumber:0},value:[new ty({name:A.value||"value"})]})]})}fromSchema(e){Ad(e,CV);let A=tb(e,e,CW.schema({names:{id:CY,value:CZ}}));d$.assertSchema(A,this.className),this.secretTypeId=A.result.secretTypeId.valueBlock.toString(),this.secretValue=A.result.secretValue}toSchema(){return new A6({value:[new A1({value:this.secretTypeId}),new Ax({idBlock:{tagClass:3,tagNumber:0},value:[this.secretValue.toSchema()]})]})}toJSON(){return{secretTypeId:this.secretTypeId,secretValue:this.secretValue.toJSON()}}}CW.CLASS_NAME="SecretBag";class C${static getItems(){return this.items||(this.items={},C$.register("1.2.840.113549.1.12.10.1.1",hq),C$.register("1.2.840.113549.1.12.10.1.2",Cz),C$.register("1.2.840.113549.1.12.10.1.3",Co),C$.register("1.2.840.113549.1.12.10.1.4",CU),C$.register("1.2.840.113549.1.12.10.1.5",CW),C$.register("1.2.840.113549.1.12.10.1.6",C6)),this.items}static register(e,A){this.getItems()[e]=A}static find(e){return this.getItems()[e]||null}}let CX="bagId",C0="bagValue",C1="bagAttributes",C8=[CX,C0,C1];class C4 extends dX{constructor(e={}){super(),this.bagId=e2(e,CX,C4.defaultValues(CX)),this.bagValue=e2(e,C0,C4.defaultValues(C0)),C1 in e&&(this.bagAttributes=e2(e,C1,C4.defaultValues(C1))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case CX:return"";case C0:return new ty;case C1:return[];default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case CX:return""===A;case C0:return A instanceof ty;case C1:return 0===A.length;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new A1({name:A.bagId||CX}),new Ax({idBlock:{tagClass:3,tagNumber:0},value:[new ty({name:A.bagValue||C0})]}),new A3({optional:!0,value:[new tQ({name:A.bagAttributes||C1,value:um.schema()})]})]})}fromSchema(e){Ad(e,C8);let A=tb(e,e,C4.schema({names:{bagId:CX,bagValue:C0,bagAttributes:C1}}));d$.assertSchema(A,this.className),this.bagId=A.result.bagId.valueBlock.toString();let t=C$.find(this.bagId);if(!t)throw Error(`Invalid BAG_ID for SafeBag: ${this.bagId}`);this.bagValue=new t({schema:A.result.bagValue}),C1 in A.result&&(this.bagAttributes=Array.from(A.result.bagAttributes,e=>new um({schema:e})))}toSchema(){let e=[new A1({value:this.bagId}),new Ax({idBlock:{tagClass:3,tagNumber:0},value:[this.bagValue.toSchema()]})];return this.bagAttributes&&e.push(new A3({value:Array.from(this.bagAttributes,e=>e.toSchema())})),new A6({value:e})}toJSON(){let e={bagId:this.bagId,bagValue:this.bagValue.toJSON()};return this.bagAttributes&&(e.bagAttributes=Array.from(this.bagAttributes,e=>e.toJSON())),e}}C4.CLASS_NAME="SafeBag";let C2="safeBags";class C6 extends dX{constructor(e={}){super(),this.safeBags=e2(e,C2,C6.defaultValues(C2)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e===C2?[]:super.defaultValues(e)}static compareWithDefault(e,A){return e===C2?0===A.length:super.defaultValues(e)}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new tQ({name:A.safeBags||"",value:C4.schema()})]})}fromSchema(e){Ad(e,[C2]);let A=tb(e,e,C6.schema({names:{safeBags:C2}}));d$.assertSchema(A,this.className),this.safeBags=Array.from(A.result.safeBags,e=>new C4({schema:e}))}toSchema(){return new A6({value:Array.from(this.safeBags,e=>e.toSchema())})}toJSON(){return{safeBags:Array.from(this.safeBags,e=>e.toJSON())}}}C6.CLASS_NAME="SafeContents";let C3="otherCertFormat",C5="otherCert",C9=[C3,C5];class C7 extends dX{constructor(e={}){super(),this.otherCertFormat=e2(e,C3,C7.defaultValues(C3)),this.otherCert=e2(e,C5,C7.defaultValues(C5)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case C3:return"";case C5:return new ty;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new A1({name:A.otherCertFormat||C3}),new ty({name:A.otherCert||C5})]})}fromSchema(e){Ad(e,C9);let A=tb(e,e,C7.schema());d$.assertSchema(A,this.className),this.otherCertFormat=A.result.otherCertFormat.valueBlock.toString(),this.otherCert=A.result.otherCert}toSchema(){return new A6({value:[new A1({value:this.otherCertFormat}),this.otherCert]})}toJSON(){let e={otherCertFormat:this.otherCertFormat};return this.otherCert instanceof ty||(e.otherCert=this.otherCert.toJSON()),e}}let fe="certificates",fA=[fe];class ft extends dX{constructor(e={}){super(),this.certificates=e2(e,fe,ft.defaultValues(fe)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e===fe?[]:super.defaultValues(e)}static schema(e={}){let A=e2(e,"names",{});return new A3({name:A.blockName||"",value:[new tQ({name:A.certificates||fe,value:new tB({value:[CA.schema(),new Ax({idBlock:{tagClass:3,tagNumber:0},value:[new ty]}),new Ax({idBlock:{tagClass:3,tagNumber:1},value:[new A6]}),new Ax({idBlock:{tagClass:3,tagNumber:2},value:pk.schema().valueBlock.value}),new Ax({idBlock:{tagClass:3,tagNumber:3},value:C7.schema().valueBlock.value})]})})]})}fromSchema(e){Ad(e,fA);let A=tb(e,e,ft.schema());d$.assertSchema(A,this.className),this.certificates=Array.from(A.result.certificates||[],e=>{let A=e.idBlock.tagNumber;if(1===e.idBlock.tagClass)return new CA({schema:e});let t=new A6({value:e.valueBlock.value});switch(A){case 1:if(1===t.valueBlock.value[0].valueBlock.value[0].valueBlock.valueDec)return new pk({schema:t});return new g3({schema:t});case 2:return new pk({schema:t});case 3:return new C7({schema:t})}return e})}toSchema(){return new A3({value:Array.from(this.certificates,e=>{switch(!0){case e instanceof CA:break;case e instanceof g3:return new Ax({idBlock:{tagClass:3,tagNumber:1},value:e.toSchema().valueBlock.value});case e instanceof pk:return new Ax({idBlock:{tagClass:3,tagNumber:2},value:e.toSchema().valueBlock.value});case e instanceof C7:return new Ax({idBlock:{tagClass:3,tagNumber:3},value:e.toSchema().valueBlock.value})}return e.toSchema()})})}toJSON(){return{certificates:Array.from(this.certificates,e=>e.toJSON())}}}ft.CLASS_NAME="CertificateSet";let fr="otherRevInfoFormat",fi="otherRevInfo",fn=[fr,fi];class fa extends dX{constructor(e={}){super(),this.otherRevInfoFormat=e2(e,fr,fa.defaultValues(fr)),this.otherRevInfo=e2(e,fi,fa.defaultValues(fi)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case fr:return"";case fi:return new ty;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new A1({name:A.otherRevInfoFormat||fr}),new ty({name:A.otherRevInfo||fi})]})}fromSchema(e){Ad(e,fn);let A=tb(e,e,fa.schema());d$.assertSchema(A,this.className),this.otherRevInfoFormat=A.result.otherRevInfoFormat.valueBlock.toString(),this.otherRevInfo=A.result.otherRevInfo}toSchema(){return new A6({value:[new A1({value:this.otherRevInfoFormat}),this.otherRevInfo]})}toJSON(){let e={otherRevInfoFormat:this.otherRevInfoFormat};return this.otherRevInfo instanceof ty||(e.otherRevInfo=this.otherRevInfo.toJSON()),e}}fa.CLASS_NAME="OtherRevocationInfoFormat";let fo="crls",fs="otherRevocationInfos",fl=[fo];class fd extends dX{constructor(e={}){super(),this.crls=e2(e,fo,fd.defaultValues(fo)),this.otherRevocationInfos=e2(e,fs,fd.defaultValues(fs)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case fo:case fs:return[];default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A3({name:A.blockName||"",value:[new tQ({name:A.crls||"",value:new tB({value:[CT.schema(),new Ax({idBlock:{tagClass:3,tagNumber:1},value:[new A1,new ty]})]})})]})}fromSchema(e){Ad(e,fl);let A=tb(e,e,fd.schema({names:{crls:fo}}));if(d$.assertSchema(A,this.className),A.result.crls)for(let e of A.result.crls)1===e.idBlock.tagClass?this.crls.push(new CT({schema:e})):this.otherRevocationInfos.push(new fa({schema:e}))}toSchema(){let e=[];return e.push(...Array.from(this.crls,e=>e.toSchema())),e.push(...Array.from(this.otherRevocationInfos,e=>{let A=e.toSchema();return A.idBlock.tagClass=3,A.idBlock.tagNumber=1,A})),new A3({value:e})}toJSON(){return{crls:Array.from(this.crls,e=>e.toJSON()),otherRevocationInfos:Array.from(this.otherRevocationInfos,e=>e.toJSON())}}}fd.CLASS_NAME="RevocationInfoChoices";let fu="certs",fc="crls",fh=[fu,fc];class fg extends dX{constructor(e={}){super(),this.crls=e2(e,fc,fg.defaultValues(fc)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case fu:return new ft;case fc:return new fd;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case fu:return 0===A.certificates.length;case fc:return 0===A.crls.length&&0===A.otherRevocationInfos.length;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new Ax({name:A.certs||"",optional:!0,idBlock:{tagClass:3,tagNumber:0},value:ft.schema().valueBlock.value}),new Ax({name:A.crls||"",optional:!0,idBlock:{tagClass:3,tagNumber:1},value:fd.schema().valueBlock.value})]})}fromSchema(e){Ad(e,fh);let A=tb(e,e,fg.schema({names:{certs:fu,crls:fc}}));d$.assertSchema(A,this.className),fu in A.result&&(this.certs=new ft({schema:new A3({value:A.result.certs.valueBlock.value})})),fc in A.result&&(this.crls=new fd({schema:new A3({value:A.result.crls.valueBlock.value})}))}toSchema(){let e=[];return this.certs&&e.push(new Ax({idBlock:{tagClass:3,tagNumber:0},value:this.certs.toSchema().valueBlock.value})),this.crls&&e.push(new Ax({idBlock:{tagClass:3,tagNumber:1},value:this.crls.toSchema().valueBlock.value})),new A6({value:e})}toJSON(){let e={};return this.certs&&(e.certs=this.certs.toJSON()),this.crls&&(e.crls=this.crls.toJSON()),e}}fg.CLASS_NAME="OriginatorInfo";let fp="issuer",fC="serialNumber",ff=[fp,fC];class fI extends dX{constructor(e={}){super(),this.issuer=e2(e,fp,fI.defaultValues(fp)),this.serialNumber=e2(e,fC,fI.defaultValues(fC)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case fp:return new d3;case fC:return new AW;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[d3.schema(A.issuer||{}),new AW({name:A.serialNumber||""})]})}fromSchema(e){Ad(e,ff);let A=tb(e,e,fI.schema({names:{issuer:{names:{blockName:fp}},serialNumber:fC}}));d$.assertSchema(A,this.className),this.issuer=new d3({schema:A.result.issuer}),this.serialNumber=A.result.serialNumber}toSchema(){return new A6({value:[this.issuer.toSchema(),this.serialNumber]})}toJSON(){return{issuer:this.issuer.toJSON(),serialNumber:this.serialNumber.toJSON()}}}fI.CLASS_NAME="IssuerAndSerialNumber";let fw="variant",fm="value",fE=["blockName"];class fy extends dX{constructor(e={}){super(),this.variant=e2(e,fw,fy.defaultValues(fw)),fm in e&&(this.value=e2(e,fm,fy.defaultValues(fm))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case fw:return -1;case fm:return{};default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case fw:return -1===A;case fm:return 0===Object.keys(A).length;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new tB({value:[fI.schema({names:{blockName:A.blockName||""}}),new AM({name:A.blockName||"",idBlock:{tagClass:3,tagNumber:0}})]})}fromSchema(e){Ad(e,fE);let A=tb(e,e,fy.schema({names:{blockName:"blockName"}}));d$.assertSchema(A,this.className),1===A.result.blockName.idBlock.tagClass?(this.variant=1,this.value=new fI({schema:A.result.blockName})):(this.variant=2,this.value=new Aj({valueHex:A.result.blockName.valueBlock.valueHex}))}toSchema(){switch(this.variant){case 1:if(!(this.value instanceof fI))throw Error("Incorrect type of RecipientIdentifier.value. It should be IssuerAndSerialNumber.");return this.value.toSchema();case 2:if(!(this.value instanceof Aj))throw Error("Incorrect type of RecipientIdentifier.value. It should be ASN.1 OctetString.");return new AM({idBlock:{tagClass:3,tagNumber:0},valueHex:this.value.valueBlock.valueHexView});default:return new ty}}toJSON(){let e={variant:this.variant};return(1===this.variant||2===this.variant)&&this.value&&(e.value=this.value.toJSON()),e}}fy.CLASS_NAME="RecipientIdentifier";let fB="version",fQ="keyEncryptionAlgorithm",fD="encryptedKey",fb="recipientCertificate",fS=[fB,"rid",fQ,fD];class fk extends dX{constructor(e={}){super(),this.version=e2(e,fB,fk.defaultValues(fB)),this.rid=e2(e,"rid",fk.defaultValues("rid")),this.keyEncryptionAlgorithm=e2(e,fQ,fk.defaultValues(fQ)),this.encryptedKey=e2(e,fD,fk.defaultValues(fD)),this.recipientCertificate=e2(e,fb,fk.defaultValues(fb)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case fB:return -1;case"rid":return{};case fQ:return new uh;case fD:return new Aj;case fb:return new CA;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case fB:return A===fk.defaultValues(fB);case"rid":return 0===Object.keys(A).length;case fQ:case fD:return A.isEqual(fk.defaultValues(e));case fb:return!1;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new AW({name:A.version||""}),fy.schema(A.rid||{}),uh.schema(A.keyEncryptionAlgorithm||{}),new Aj({name:A.encryptedKey||""})]})}fromSchema(e){Ad(e,fS);let A=tb(e,e,fk.schema({names:{version:fB,rid:{names:{blockName:"rid"}},keyEncryptionAlgorithm:{names:{blockName:fQ}},encryptedKey:fD}}));d$.assertSchema(A,this.className),this.version=A.result.version.valueBlock.valueDec,3===A.result.rid.idBlock.tagClass?this.rid=new Aj({valueHex:A.result.rid.valueBlock.valueHex}):this.rid=new fI({schema:A.result.rid}),this.keyEncryptionAlgorithm=new uh({schema:A.result.keyEncryptionAlgorithm}),this.encryptedKey=A.result.encryptedKey}toSchema(){let e=[];return this.rid instanceof fI?(this.version=0,e.push(new AW({value:this.version})),e.push(this.rid.toSchema())):(this.version=2,e.push(new AW({value:this.version})),e.push(new AM({idBlock:{tagClass:3,tagNumber:0},valueHex:this.rid.valueBlock.valueHexView}))),e.push(this.keyEncryptionAlgorithm.toSchema()),e.push(this.encryptedKey),new A6({value:e})}toJSON(){return{version:this.version,rid:this.rid.toJSON(),keyEncryptionAlgorithm:this.keyEncryptionAlgorithm.toJSON(),encryptedKey:this.encryptedKey.toJSON()}}}fk.CLASS_NAME="KeyTransRecipientInfo";let fR="algorithm",fv="publicKey",fG=[fR,fv];class fT extends dX{constructor(e={}){super(),this.algorithm=e2(e,fR,fT.defaultValues(fR)),this.publicKey=e2(e,fv,fT.defaultValues(fv)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case fR:return new uh;case fv:return new AY;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case fR:case fv:return A.isEqual(fT.defaultValues(e));default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[uh.schema(A.algorithm||{}),new AY({name:A.publicKey||""})]})}fromSchema(e){Ad(e,fG);let A=tb(e,e,fT.schema({names:{algorithm:{names:{blockName:fR}},publicKey:fv}}));d$.assertSchema(A,this.className),this.algorithm=new uh({schema:A.result.algorithm}),this.publicKey=A.result.publicKey}toSchema(){return new A6({value:[this.algorithm.toSchema(),this.publicKey]})}toJSON(){return{algorithm:this.algorithm.toJSON(),publicKey:this.publicKey.toJSON()}}}fT.CLASS_NAME="OriginatorPublicKey";let fM="variant",fN="value",fO=["blockName"];class fH extends dX{constructor(e={}){super(),this.variant=e2(e,fM,fH.defaultValues(fM)),fN in e&&(this.value=e2(e,fN,fH.defaultValues(fN))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case fM:return -1;case fN:return{};default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case fM:return -1===A;case fN:return 0===Object.keys(A).length;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new tB({value:[fI.schema({names:{blockName:A.blockName||""}}),new AM({idBlock:{tagClass:3,tagNumber:0},name:A.blockName||""}),new Ax({idBlock:{tagClass:3,tagNumber:1},name:A.blockName||"",value:fT.schema().valueBlock.value})]})}fromSchema(e){Ad(e,fO);let A=tb(e,e,fH.schema({names:{blockName:"blockName"}}));d$.assertSchema(A,this.className),1===A.result.blockName.idBlock.tagClass?(this.variant=1,this.value=new fI({schema:A.result.blockName})):0===A.result.blockName.idBlock.tagNumber?(A.result.blockName.idBlock.tagClass=1,A.result.blockName.idBlock.tagNumber=4,this.variant=2,this.value=A.result.blockName):(this.variant=3,this.value=new fT({schema:new A6({value:A.result.blockName.valueBlock.value})}))}toSchema(){switch(this.variant){case 1:return this.value.toSchema();case 2:return this.value.idBlock.tagClass=3,this.value.idBlock.tagNumber=0,this.value;case 3:{let e=this.value.toSchema();return e.idBlock.tagClass=3,e.idBlock.tagNumber=1,e}default:return new ty}}toJSON(){let e={variant:this.variant};return(1===this.variant||2===this.variant||3===this.variant)&&(e.value=this.value.toJSON()),e}}fH.CLASS_NAME="OriginatorIdentifierOrKey";let fU="keyAttrId",f_="keyAttr",fx=[fU,f_];class fL extends dX{constructor(e={}){super(),this.keyAttrId=e2(e,fU,fL.defaultValues(fU)),f_ in e&&(this.keyAttr=e2(e,f_,fL.defaultValues(f_))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case fU:return"";case f_:return{};default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case fU:return"string"==typeof A&&""===A;case f_:return 0===Object.keys(A).length;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({optional:A.optional||!0,name:A.blockName||"",value:[new A1({name:A.keyAttrId||""}),new ty({optional:!0,name:A.keyAttr||""})]})}fromSchema(e){Ad(e,fx);let A=tb(e,e,fL.schema({names:{keyAttrId:fU,keyAttr:f_}}));d$.assertSchema(A,this.className),this.keyAttrId=A.result.keyAttrId.valueBlock.toString(),f_ in A.result&&(this.keyAttr=A.result.keyAttr)}toSchema(){let e=[];return e.push(new A1({value:this.keyAttrId})),f_ in this&&e.push(this.keyAttr),new A6({value:e})}toJSON(){let e={keyAttrId:this.keyAttrId};return f_ in this&&(e.keyAttr=this.keyAttr.toJSON()),e}}fL.CLASS_NAME="OtherKeyAttribute";let fP="subjectKeyIdentifier",fq="date",fK="other",fJ=[fP,fq,fK];class fF extends dX{constructor(e={}){super(),this.subjectKeyIdentifier=e2(e,fP,fF.defaultValues(fP)),fq in e&&(this.date=e2(e,fq,fF.defaultValues(fq))),fK in e&&(this.other=e2(e,fK,fF.defaultValues(fK))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case fP:return new Aj;case fq:return new tC;case fK:return new fL;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case fP:return A.isEqual(fF.defaultValues(fP));case fq:return 0===A.year&&0===A.month&&0===A.day&&0===A.hour&&0===A.minute&&0===A.second&&0===A.millisecond;case fK:return""===A.keyAttrId&&"keyAttr"in A==!1;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new Aj({name:A.subjectKeyIdentifier||""}),new tC({optional:!0,name:A.date||""}),fL.schema(A.other||{})]})}fromSchema(e){Ad(e,fJ);let A=tb(e,e,fF.schema({names:{subjectKeyIdentifier:fP,date:fq,other:{names:{blockName:fK}}}}));d$.assertSchema(A,this.className),this.subjectKeyIdentifier=A.result.subjectKeyIdentifier,fq in A.result&&(this.date=A.result.date),fK in A.result&&(this.other=new fL({schema:A.result.other}))}toSchema(){let e=[];return e.push(this.subjectKeyIdentifier),this.date&&e.push(this.date),this.other&&e.push(this.other.toSchema()),new A6({value:e})}toJSON(){let e={subjectKeyIdentifier:this.subjectKeyIdentifier.toJSON()};return this.date&&(e.date=this.date.toJSON()),this.other&&(e.other=this.other.toJSON()),e}}fF.CLASS_NAME="RecipientKeyIdentifier";let fj="variant",fz="value",fY=["blockName"];class fZ extends dX{constructor(e={}){super(),this.variant=e2(e,fj,fZ.defaultValues(fj)),this.value=e2(e,fz,fZ.defaultValues(fz)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case fj:return -1;case fz:return{};default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case fj:return -1===A;case fz:return 0===Object.keys(A).length;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new tB({value:[fI.schema(A.issuerAndSerialNumber||{names:{blockName:A.blockName||""}}),new Ax({name:A.blockName||"",idBlock:{tagClass:3,tagNumber:0},value:fF.schema(A.rKeyId||{names:{blockName:A.blockName||""}}).valueBlock.value})]})}fromSchema(e){Ad(e,fY);let A=tb(e,e,fZ.schema({names:{blockName:"blockName"}}));d$.assertSchema(A,this.className),1===A.result.blockName.idBlock.tagClass?(this.variant=1,this.value=new fI({schema:A.result.blockName})):(this.variant=2,this.value=new fF({schema:new A6({value:A.result.blockName.valueBlock.value})}))}toSchema(){switch(this.variant){case 1:return this.value.toSchema();case 2:return new Ax({idBlock:{tagClass:3,tagNumber:0},value:this.value.toSchema().valueBlock.value});default:return new ty}}toJSON(){let e={variant:this.variant};return(1===this.variant||2===this.variant)&&(e.value=this.value.toJSON()),e}}fZ.CLASS_NAME="KeyAgreeRecipientIdentifier";let fV="encryptedKey",fW=["rid",fV];class f$ extends dX{constructor(e={}){super(),this.rid=e2(e,"rid",f$.defaultValues("rid")),this.encryptedKey=e2(e,fV,f$.defaultValues(fV)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case"rid":return new fZ;case fV:return new Aj;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case"rid":return -1===A.variant&&"value"in A==!1;case fV:return A.isEqual(f$.defaultValues(fV));default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[fZ.schema(A.rid||{}),new Aj({name:A.encryptedKey||""})]})}fromSchema(e){Ad(e,fW);let A=tb(e,e,f$.schema({names:{rid:{names:{blockName:"rid"}},encryptedKey:fV}}));d$.assertSchema(A,this.className),this.rid=new fZ({schema:A.result.rid}),this.encryptedKey=A.result.encryptedKey}toSchema(){return new A6({value:[this.rid.toSchema(),this.encryptedKey]})}toJSON(){return{rid:this.rid.toJSON(),encryptedKey:this.encryptedKey.toJSON()}}}f$.CLASS_NAME="RecipientEncryptedKey";let fX="encryptedKeys",f0="RecipientEncryptedKeys",f1=[f0];class f8 extends dX{constructor(e={}){super(),this.encryptedKeys=e2(e,fX,f8.defaultValues(fX)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){return e===fX?[]:super.defaultValues(e)}static compareWithDefault(e,A){return e===fX?0===A.length:super.defaultValues(e)}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new tQ({name:A.RecipientEncryptedKeys||"",value:f$.schema()})]})}fromSchema(e){Ad(e,f1);let A=tb(e,e,f8.schema({names:{RecipientEncryptedKeys:f0}}));d$.assertSchema(A,this.className),this.encryptedKeys=Array.from(A.result.RecipientEncryptedKeys,e=>new f$({schema:e}))}toSchema(){return new A6({value:Array.from(this.encryptedKeys,e=>e.toSchema())})}toJSON(){return{encryptedKeys:Array.from(this.encryptedKeys,e=>e.toJSON())}}}f8.CLASS_NAME="RecipientEncryptedKeys";let f4="version",f2="originator",f6="keyEncryptionAlgorithm",f3="recipientEncryptedKeys",f5="recipientCertificate",f9="recipientPublicKey",f7=[f4,f2,"ukm",f6,f3];class Ie extends dX{constructor(e={}){super(),this.version=e2(e,f4,Ie.defaultValues(f4)),this.originator=e2(e,f2,Ie.defaultValues(f2)),"ukm"in e&&(this.ukm=e2(e,"ukm",Ie.defaultValues("ukm"))),this.keyEncryptionAlgorithm=e2(e,f6,Ie.defaultValues(f6)),this.recipientEncryptedKeys=e2(e,f3,Ie.defaultValues(f3)),this.recipientCertificate=e2(e,f5,Ie.defaultValues(f5)),this.recipientPublicKey=e2(e,f9,Ie.defaultValues(f9)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case f4:return 0;case f2:return new fH;case"ukm":return new Aj;case f6:return new uh;case f3:return new f8;case f5:return new CA;case f9:return null;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case f4:return 0===A;case f2:return -1===A.variant&&"value"in A==!1;case"ukm":return A.isEqual(Ie.defaultValues("ukm"));case f6:return""===A.algorithmId&&"algorithmParams"in A==!1;case f3:return 0===A.encryptedKeys.length;case f5:case f9:return!1;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new AW({name:A.version||""}),new Ax({idBlock:{tagClass:3,tagNumber:0},value:[fH.schema(A.originator||{})]}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new Aj({name:A.ukm||""})]}),uh.schema(A.keyEncryptionAlgorithm||{}),f8.schema(A.recipientEncryptedKeys||{})]})}fromSchema(e){Ad(e,f7);let A=tb(e,e,Ie.schema({names:{version:f4,originator:{names:{blockName:f2}},ukm:"ukm",keyEncryptionAlgorithm:{names:{blockName:f6}},recipientEncryptedKeys:{names:{blockName:f3}}}}));d$.assertSchema(A,this.className),this.version=A.result.version.valueBlock.valueDec,this.originator=new fH({schema:A.result.originator}),"ukm"in A.result&&(this.ukm=A.result.ukm),this.keyEncryptionAlgorithm=new uh({schema:A.result.keyEncryptionAlgorithm}),this.recipientEncryptedKeys=new f8({schema:A.result.recipientEncryptedKeys})}toSchema(){let e=[];return e.push(new AW({value:this.version})),e.push(new Ax({idBlock:{tagClass:3,tagNumber:0},value:[this.originator.toSchema()]})),this.ukm&&e.push(new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[this.ukm]})),e.push(this.keyEncryptionAlgorithm.toSchema()),e.push(this.recipientEncryptedKeys.toSchema()),new A6({value:e})}toJSON(){let e={version:this.version,originator:this.originator.toJSON(),keyEncryptionAlgorithm:this.keyEncryptionAlgorithm.toJSON(),recipientEncryptedKeys:this.recipientEncryptedKeys.toJSON()};return this.ukm&&(e.ukm=this.ukm.toJSON()),e}}Ie.CLASS_NAME="KeyAgreeRecipientInfo";let IA="keyIdentifier",It="date",Ir="other",Ii=[IA,It,Ir];class In extends dX{constructor(e={}){super(),this.keyIdentifier=e2(e,IA,In.defaultValues(IA)),It in e&&(this.date=e2(e,It,In.defaultValues(It))),Ir in e&&(this.other=e2(e,Ir,In.defaultValues(Ir))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case IA:return new Aj;case It:return new tC;case Ir:return new fL;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case IA:return A.isEqual(In.defaultValues(IA));case It:return 0===A.year&&0===A.month&&0===A.day&&0===A.hour&&0===A.minute&&0===A.second&&0===A.millisecond;case Ir:return A.compareWithDefault("keyAttrId",A.keyAttrId)&&"keyAttr"in A==!1;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new Aj({name:A.keyIdentifier||""}),new tC({optional:!0,name:A.date||""}),fL.schema(A.other||{})]})}fromSchema(e){Ad(e,Ii);let A=tb(e,e,In.schema({names:{keyIdentifier:IA,date:It,other:{names:{blockName:Ir}}}}));d$.assertSchema(A,this.className),this.keyIdentifier=A.result.keyIdentifier,It in A.result&&(this.date=A.result.date),Ir in A.result&&(this.other=new fL({schema:A.result.other}))}toSchema(){let e=[];return e.push(this.keyIdentifier),this.date&&e.push(this.date),this.other&&e.push(this.other.toSchema()),new A6({value:e})}toJSON(){let e={keyIdentifier:this.keyIdentifier.toJSON()};return this.date&&(e.date=this.date),this.other&&(e.other=this.other.toJSON()),e}}In.CLASS_NAME="KEKIdentifier";let Ia="version",Io="kekid",Is="keyEncryptionAlgorithm",Il="encryptedKey",Id="preDefinedKEK",Iu=[Ia,Io,Is,Il];class Ic extends dX{constructor(e={}){super(),this.version=e2(e,Ia,Ic.defaultValues(Ia)),this.kekid=e2(e,Io,Ic.defaultValues(Io)),this.keyEncryptionAlgorithm=e2(e,Is,Ic.defaultValues(Is)),this.encryptedKey=e2(e,Il,Ic.defaultValues(Il)),this.preDefinedKEK=e2(e,Id,Ic.defaultValues(Id)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Ia:return 0;case Io:return new In;case Is:return new uh;case Il:return new Aj;case Id:return dZ;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case"KEKRecipientInfo":return A===Ic.defaultValues(Ia);case Io:return A.compareWithDefault("keyIdentifier",A.keyIdentifier)&&"date"in A==!1&&"other"in A==!1;case Is:return""===A.algorithmId&&"algorithmParams"in A==!1;case Il:return A.isEqual(Ic.defaultValues(Il));case Id:return 0===A.byteLength;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new AW({name:A.version||""}),In.schema(A.kekid||{}),uh.schema(A.keyEncryptionAlgorithm||{}),new Aj({name:A.encryptedKey||""})]})}fromSchema(e){Ad(e,Iu);let A=tb(e,e,Ic.schema({names:{version:Ia,kekid:{names:{blockName:Io}},keyEncryptionAlgorithm:{names:{blockName:Is}},encryptedKey:Il}}));d$.assertSchema(A,this.className),this.version=A.result.version.valueBlock.valueDec,this.kekid=new In({schema:A.result.kekid}),this.keyEncryptionAlgorithm=new uh({schema:A.result.keyEncryptionAlgorithm}),this.encryptedKey=A.result.encryptedKey}toSchema(){return new A6({value:[new AW({value:this.version}),this.kekid.toSchema(),this.keyEncryptionAlgorithm.toSchema(),this.encryptedKey]})}toJSON(){return{version:this.version,kekid:this.kekid.toJSON(),keyEncryptionAlgorithm:this.keyEncryptionAlgorithm.toJSON(),encryptedKey:this.encryptedKey.toJSON()}}}Ic.CLASS_NAME="KEKRecipientInfo";let Ih="version",Ig="keyDerivationAlgorithm",Ip="keyEncryptionAlgorithm",IC="encryptedKey",If="password",II=[Ih,Ig,Ip,IC];class Iw extends dX{constructor(e={}){super(),this.version=e2(e,Ih,Iw.defaultValues(Ih)),Ig in e&&(this.keyDerivationAlgorithm=e2(e,Ig,Iw.defaultValues(Ig))),this.keyEncryptionAlgorithm=e2(e,Ip,Iw.defaultValues(Ip)),this.encryptedKey=e2(e,IC,Iw.defaultValues(IC)),this.password=e2(e,If,Iw.defaultValues(If)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Ih:return -1;case Ig:case Ip:return new uh;case IC:return new Aj;case If:return dZ;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case Ih:return -1===A;case Ig:case Ip:return""===A.algorithmId&&"algorithmParams"in A==!1;case IC:return A.isEqual(Iw.defaultValues(IC));case If:return 0===A.byteLength;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new AW({name:A.version||""}),new Ax({name:A.keyDerivationAlgorithm||"",optional:!0,idBlock:{tagClass:3,tagNumber:0},value:uh.schema().valueBlock.value}),uh.schema(A.keyEncryptionAlgorithm||{}),new Aj({name:A.encryptedKey||""})]})}fromSchema(e){Ad(e,II);let A=tb(e,e,Iw.schema({names:{version:Ih,keyDerivationAlgorithm:Ig,keyEncryptionAlgorithm:{names:{blockName:Ip}},encryptedKey:IC}}));d$.assertSchema(A,this.className),this.version=A.result.version.valueBlock.valueDec,Ig in A.result&&(this.keyDerivationAlgorithm=new uh({schema:new A6({value:A.result.keyDerivationAlgorithm.valueBlock.value})})),this.keyEncryptionAlgorithm=new uh({schema:A.result.keyEncryptionAlgorithm}),this.encryptedKey=A.result.encryptedKey}toSchema(){let e=[];return e.push(new AW({value:this.version})),this.keyDerivationAlgorithm&&e.push(new Ax({idBlock:{tagClass:3,tagNumber:0},value:this.keyDerivationAlgorithm.toSchema().valueBlock.value})),e.push(this.keyEncryptionAlgorithm.toSchema()),e.push(this.encryptedKey),new A6({value:e})}toJSON(){let e={version:this.version,keyEncryptionAlgorithm:this.keyEncryptionAlgorithm.toJSON(),encryptedKey:this.encryptedKey.toJSON()};return this.keyDerivationAlgorithm&&(e.keyDerivationAlgorithm=this.keyDerivationAlgorithm.toJSON()),e}}Iw.CLASS_NAME="PasswordRecipientInfo";let Im="oriType",IE="oriValue",Iy=[Im,IE];class IB extends dX{constructor(e={}){super(),this.oriType=e2(e,Im,IB.defaultValues(Im)),this.oriValue=e2(e,IE,IB.defaultValues(IE)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Im:return"";case IE:return{};default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case Im:return""===A;case IE:return 0===Object.keys(A).length;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new A1({name:A.oriType||""}),new ty({name:A.oriValue||""})]})}fromSchema(e){Ad(e,Iy);let A=tb(e,e,IB.schema({names:{oriType:Im,oriValue:IE}}));d$.assertSchema(A,this.className),this.oriType=A.result.oriType.valueBlock.toString(),this.oriValue=A.result.oriValue}toSchema(){return new A6({value:[new A1({value:this.oriType}),this.oriValue]})}toJSON(){let e={oriType:this.oriType};return IB.compareWithDefault(IE,this.oriValue)||(e.oriValue=this.oriValue.toJSON()),e}}IB.CLASS_NAME="OtherRecipientInfo";let IQ="variant",ID="value",Ib=["blockName"];class IS extends dX{constructor(e={}){super(),this.variant=e2(e,IQ,IS.defaultValues(IQ)),ID in e&&(this.value=e2(e,ID,IS.defaultValues(ID))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case IQ:return -1;case ID:return{};default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case IQ:return A===IS.defaultValues(e);case ID:return 0===Object.keys(A).length;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new tB({value:[fk.schema({names:{blockName:A.blockName||""}}),new Ax({name:A.blockName||"",idBlock:{tagClass:3,tagNumber:1},value:Ie.schema().valueBlock.value}),new Ax({name:A.blockName||"",idBlock:{tagClass:3,tagNumber:2},value:Ic.schema().valueBlock.value}),new Ax({name:A.blockName||"",idBlock:{tagClass:3,tagNumber:3},value:Iw.schema().valueBlock.value}),new Ax({name:A.blockName||"",idBlock:{tagClass:3,tagNumber:4},value:IB.schema().valueBlock.value})]})}fromSchema(e){Ad(e,Ib);let A=tb(e,e,IS.schema({names:{blockName:"blockName"}}));if(d$.assertSchema(A,this.className),1===A.result.blockName.idBlock.tagClass)this.variant=1,this.value=new fk({schema:A.result.blockName});else{let e=new A6({value:A.result.blockName.valueBlock.value});switch(A.result.blockName.idBlock.tagNumber){case 1:this.variant=2,this.value=new Ie({schema:e});break;case 2:this.variant=3,this.value=new Ic({schema:e});break;case 3:this.variant=4,this.value=new Iw({schema:e});break;case 4:this.variant=5,this.value=new IB({schema:e});break;default:throw Error("Incorrect structure of RecipientInfo block")}}}toSchema(){dW.assertEmpty(this.value,"value","RecipientInfo");let e=this.value.toSchema();switch(this.variant){case 1:return e;case 2:case 3:case 4:return e.idBlock.tagClass=3,e.idBlock.tagNumber=this.variant-1,e;default:return new ty}}toJSON(){let e={variant:this.variant};return this.value&&this.variant>=1&&this.variant<=4&&(e.value=this.value.toJSON()),e}}IS.CLASS_NAME="RecipientInfo";let Ik="hashAlgorithm",IR="maskGenAlgorithm",Iv="pSourceAlgorithm",IG=[Ik,IR,Iv];class IT extends dX{constructor(e={}){super(),this.hashAlgorithm=e2(e,Ik,IT.defaultValues(Ik)),this.maskGenAlgorithm=e2(e,IR,IT.defaultValues(IR)),this.pSourceAlgorithm=e2(e,Iv,IT.defaultValues(Iv)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Ik:return new uh({algorithmId:"1.3.14.3.2.26",algorithmParams:new Aq});case IR:return new uh({algorithmId:"1.2.840.113549.1.1.8",algorithmParams:new uh({algorithmId:"1.3.14.3.2.26",algorithmParams:new Aq}).toSchema()});case Iv:return new uh({algorithmId:"1.2.840.113549.1.1.9",algorithmParams:new Aj({valueHex:new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer})});default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new Ax({idBlock:{tagClass:3,tagNumber:0},optional:!0,value:[uh.schema(A.hashAlgorithm||{})]}),new Ax({idBlock:{tagClass:3,tagNumber:1},optional:!0,value:[uh.schema(A.maskGenAlgorithm||{})]}),new Ax({idBlock:{tagClass:3,tagNumber:2},optional:!0,value:[uh.schema(A.pSourceAlgorithm||{})]})]})}fromSchema(e){Ad(e,IG);let A=tb(e,e,IT.schema({names:{hashAlgorithm:{names:{blockName:Ik}},maskGenAlgorithm:{names:{blockName:IR}},pSourceAlgorithm:{names:{blockName:Iv}}}}));d$.assertSchema(A,this.className),Ik in A.result&&(this.hashAlgorithm=new uh({schema:A.result.hashAlgorithm})),IR in A.result&&(this.maskGenAlgorithm=new uh({schema:A.result.maskGenAlgorithm})),Iv in A.result&&(this.pSourceAlgorithm=new uh({schema:A.result.pSourceAlgorithm}))}toSchema(){let e=[];return this.hashAlgorithm.isEqual(IT.defaultValues(Ik))||e.push(new Ax({idBlock:{tagClass:3,tagNumber:0},value:[this.hashAlgorithm.toSchema()]})),this.maskGenAlgorithm.isEqual(IT.defaultValues(IR))||e.push(new Ax({idBlock:{tagClass:3,tagNumber:1},value:[this.maskGenAlgorithm.toSchema()]})),this.pSourceAlgorithm.isEqual(IT.defaultValues(Iv))||e.push(new Ax({idBlock:{tagClass:3,tagNumber:2},value:[this.pSourceAlgorithm.toSchema()]})),new A6({value:e})}toJSON(){let e={};return this.hashAlgorithm.isEqual(IT.defaultValues(Ik))||(e.hashAlgorithm=this.hashAlgorithm.toJSON()),this.maskGenAlgorithm.isEqual(IT.defaultValues(IR))||(e.maskGenAlgorithm=this.maskGenAlgorithm.toJSON()),this.pSourceAlgorithm.isEqual(IT.defaultValues(Iv))||(e.pSourceAlgorithm=this.pSourceAlgorithm.toJSON()),e}}IT.CLASS_NAME="RSAESOAEPParams";let IM="keyInfo",IN="entityUInfo",IO="suppPubInfo",IH=[IM,IN,IO];class IU extends dX{constructor(e={}){super(),this.keyInfo=e2(e,IM,IU.defaultValues(IM)),IN in e&&(this.entityUInfo=e2(e,IN,IU.defaultValues(IN))),this.suppPubInfo=e2(e,IO,IU.defaultValues(IO)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case IM:return new uh;case IN:case IO:return new Aj;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case IM:case IN:case IO:return A.isEqual(IU.defaultValues(e));default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[uh.schema(A.keyInfo||{}),new Ax({name:A.entityUInfo||"",idBlock:{tagClass:3,tagNumber:0},optional:!0,value:[new Aj]}),new Ax({name:A.suppPubInfo||"",idBlock:{tagClass:3,tagNumber:2},value:[new Aj]})]})}fromSchema(e){Ad(e,IH);let A=tb(e,e,IU.schema({names:{keyInfo:{names:{blockName:IM}},entityUInfo:IN,suppPubInfo:IO}}));d$.assertSchema(A,this.className),this.keyInfo=new uh({schema:A.result.keyInfo}),IN in A.result&&(this.entityUInfo=A.result.entityUInfo.valueBlock.value[0]),this.suppPubInfo=A.result.suppPubInfo.valueBlock.value[0]}toSchema(){let e=[];return e.push(this.keyInfo.toSchema()),this.entityUInfo&&e.push(new Ax({idBlock:{tagClass:3,tagNumber:0},value:[this.entityUInfo]})),e.push(new Ax({idBlock:{tagClass:3,tagNumber:2},value:[this.suppPubInfo]})),new A6({value:e})}toJSON(){let e={keyInfo:this.keyInfo.toJSON(),suppPubInfo:this.suppPubInfo.toJSON()};return this.entityUInfo&&(e.entityUInfo=this.entityUInfo.toJSON()),e}}IU.CLASS_NAME="ECCCMSSharedInfo";let I_="version",Ix="originatorInfo",IL="recipientInfos",IP="encryptedContentInfo",Iq="unprotectedAttrs",IK=[I_,Ix,IL,IP,Iq],IJ={kdfAlgorithm:"SHA-512",kekEncryptionLength:256},IF={"P-256":256,"P-384":384,"P-521":528};class Ij extends dX{constructor(e={}){super(),this.version=e2(e,I_,Ij.defaultValues(I_)),Ix in e&&(this.originatorInfo=e2(e,Ix,Ij.defaultValues(Ix))),this.recipientInfos=e2(e,IL,Ij.defaultValues(IL)),this.encryptedContentInfo=e2(e,IP,Ij.defaultValues(IP)),Iq in e&&(this.unprotectedAttrs=e2(e,Iq,Ij.defaultValues(Iq))),this.policy={disableSplit:!!e.disableSplit},e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case I_:return 0;case Ix:return new fg;case IL:return[];case IP:return new hz;case Iq:return[];default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case I_:return A===Ij.defaultValues(e);case Ix:return 0===A.certs.certificates.length&&0===A.crls.crls.length;case IL:case Iq:return 0===A.length;case IP:return hz.compareWithDefault("contentType",A.contentType)&&hz.compareWithDefault("contentEncryptionAlgorithm",A.contentEncryptionAlgorithm)&&hz.compareWithDefault("encryptedContent",A.encryptedContent);default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new AW({name:A.version||""}),new Ax({name:A.originatorInfo||"",optional:!0,idBlock:{tagClass:3,tagNumber:0},value:fg.schema().valueBlock.value}),new A3({value:[new tQ({name:A.recipientInfos||"",value:IS.schema()})]}),hz.schema(A.encryptedContentInfo||{}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new tQ({name:A.unprotectedAttrs||"",value:um.schema()})]})]})}fromSchema(e){Ad(e,IK);let A=tb(e,e,Ij.schema({names:{version:I_,originatorInfo:Ix,recipientInfos:IL,encryptedContentInfo:{names:{blockName:IP}},unprotectedAttrs:Iq}}));d$.assertSchema(A,this.className),this.version=A.result.version.valueBlock.valueDec,Ix in A.result&&(this.originatorInfo=new fg({schema:new A6({value:A.result.originatorInfo.valueBlock.value})})),this.recipientInfos=Array.from(A.result.recipientInfos,e=>new IS({schema:e})),this.encryptedContentInfo=new hz({schema:A.result.encryptedContentInfo}),Iq in A.result&&(this.unprotectedAttrs=Array.from(A.result.unprotectedAttrs,e=>new um({schema:e})))}toSchema(){let e=[];return e.push(new AW({value:this.version})),this.originatorInfo&&e.push(new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:this.originatorInfo.toSchema().valueBlock.value})),e.push(new A3({value:Array.from(this.recipientInfos,e=>e.toSchema())})),e.push(this.encryptedContentInfo.toSchema()),this.unprotectedAttrs&&e.push(new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:Array.from(this.unprotectedAttrs,e=>e.toSchema())})),new A6({value:e})}toJSON(){let e={version:this.version,recipientInfos:Array.from(this.recipientInfos,e=>e.toJSON()),encryptedContentInfo:this.encryptedContentInfo.toJSON()};return this.originatorInfo&&(e.originatorInfo=this.originatorInfo.toJSON()),this.unprotectedAttrs&&(e.unprotectedAttrs=Array.from(this.unprotectedAttrs,e=>e.toJSON())),e}addRecipientByCertificate(e,A,t,r=gn(!0)){let i=Object.assign({useOAEP:!0,oaepHashAlgorithm:"SHA-512"},IJ,A||{});if(-1!==e.subjectPublicKeyInfo.algorithm.algorithmId.indexOf("1.2.840.113549"))t=1;else if(-1!==e.subjectPublicKeyInfo.algorithm.algorithmId.indexOf("1.2.840.10045"))t=2;else throw Error(`Unknown type of certificate's public key: ${e.subjectPublicKeyInfo.algorithm.algorithmId}`);switch(t){case 1:{let A,t;if(!0===i.useOAEP){A=r.getOIDByAlgorithm({name:"RSA-OAEP"},!0,"keyEncryptionAlgorithm");let e=new uh({algorithmId:r.getOIDByAlgorithm({name:i.oaepHashAlgorithm},!0,"RSAES-OAEP-params"),algorithmParams:new Aq});t=new IT({hashAlgorithm:e,maskGenAlgorithm:new uh({algorithmId:"1.2.840.113549.1.1.8",algorithmParams:e.toSchema()})}).toSchema()}else{if(""===(A=r.getOIDByAlgorithm({name:"RSAES-PKCS1-v1_5"})))throw Error("Can not find OID for RSAES-PKCS1-v1_5");t=new Aq}let n=new fk({version:0,rid:new fI({issuer:e.issuer,serialNumber:e.serialNumber}),keyEncryptionAlgorithm:new uh({algorithmId:A,algorithmParams:t}),recipientCertificate:e});this.recipientInfos.push(new IS({variant:1,value:n}))}break;case 2:{let A=new fZ({variant:1,value:new fI({issuer:e.issuer,serialNumber:e.serialNumber})});this._addKeyAgreeRecipientInfo(A,i,{recipientCertificate:e},r)}break;default:throw Error(`Unknown "variant" value: ${t}`)}return!0}addRecipientByPreDefinedData(e,A={},t,r=gn(!0)){if(dV.assert(e,"preDefinedData","ArrayBuffer"),!e.byteLength)throw Error("Pre-defined data could have zero length");if(!A.keyIdentifier){let e=new ArrayBuffer(16),t=new Uint8Array(e);r.getRandomValues(t),A.keyIdentifier=e}switch(!A.hmacHashAlgorithm&&(A.hmacHashAlgorithm="SHA-512"),void 0===A.iterationCount&&(A.iterationCount=2048),!A.keyEncryptionAlgorithm&&(A.keyEncryptionAlgorithm={name:"AES-KW",length:256}),!A.keyEncryptionAlgorithmParams&&(A.keyEncryptionAlgorithmParams=new Aq),t){case 1:{let t=r.getOIDByAlgorithm(A.keyEncryptionAlgorithm,!0,"keyEncryptionAlgorithm"),i=new Ic({version:4,kekid:new In({keyIdentifier:new Aj({valueHex:A.keyIdentifier})}),keyEncryptionAlgorithm:new uh({algorithmId:t,algorithmParams:A.keyEncryptionAlgorithmParams}),preDefinedKEK:e});this.recipientInfos.push(new IS({variant:3,value:i}))}break;case 2:{let t=r.getOIDByAlgorithm({name:"PBKDF2"},!0,"keyDerivationAlgorithm"),i=new ArrayBuffer(64),n=new Uint8Array(i);r.getRandomValues(n);let a=r.getOIDByAlgorithm({name:"HMAC",hash:{name:A.hmacHashAlgorithm}},!0,"hmacHashAlgorithm"),o=new h2({salt:new Aj({valueHex:i}),iterationCount:A.iterationCount,prf:new uh({algorithmId:a,algorithmParams:new Aq})}),s=r.getOIDByAlgorithm(A.keyEncryptionAlgorithm,!0,"keyEncryptionAlgorithm"),l=new Iw({version:0,keyDerivationAlgorithm:new uh({algorithmId:t,algorithmParams:o.toSchema()}),keyEncryptionAlgorithm:new uh({algorithmId:s,algorithmParams:A.keyEncryptionAlgorithmParams}),password:e});this.recipientInfos.push(new IS({variant:4,value:l}))}break;default:throw Error(`Unknown value for "variant": ${t}`)}}addRecipientByKeyIdentifier(e,A,t,r=gn(!0)){let i=Object.assign({},IJ,t||{}),n=new fZ({variant:2,value:new fF({subjectKeyIdentifier:new Aj({valueHex:A})})});this._addKeyAgreeRecipientInfo(n,i,{recipientPublicKey:e},r)}_addKeyAgreeRecipientInfo(e,A,t,r=gn(!0)){let i=new f$({rid:e}),n=new uh({algorithmId:r.getOIDByAlgorithm({name:"AES-KW",length:A.kekEncryptionLength},!0,"keyEncryptionAlgorithm")}),a=r.getOIDByAlgorithm({name:"ECDH",kdf:A.kdfAlgorithm},!0,"KeyAgreeRecipientInfo"),o=new ArrayBuffer(64),s=new Uint8Array(o);r.getRandomValues(s);let l=new Ie(Object.assign({version:3,ukm:new Aj({valueHex:o}),keyEncryptionAlgorithm:new uh({algorithmId:a,algorithmParams:n.toSchema()}),recipientEncryptedKeys:new f8({encryptedKeys:[i]})},t));this.recipientInfos.push(new IS({variant:2,value:l}))}async encrypt(e,A,t=gn(!0)){let r=new ArrayBuffer(16),i=new Uint8Array(r);t.getRandomValues(i);let n=new Uint8Array(A),a=t.getOIDByAlgorithm(e,!0,"contentEncryptionAlgorithm"),o=await t.generateKey(e,!0,["encrypt"]),s=await t.encrypt({name:e.name,iv:i},o,n),l=await t.exportKey("raw",o);this.version=2,this.encryptedContentInfo=new hz({disableSplit:this.policy.disableSplit,contentType:"1.2.840.113549.1.7.1",contentEncryptionAlgorithm:new uh({algorithmId:a,algorithmParams:new Aj({valueHex:r})}),encryptedContent:new Aj({valueHex:s})});let d=async e=>{let A,r,i=this.recipientInfos[e].value;if(i.recipientPublicKey)A=i.recipientPublicKey.algorithm.namedCurve,r=i.recipientPublicKey;else if(i.recipientCertificate){let n=i.recipientCertificate.subjectPublicKeyInfo.algorithm.algorithmParams;if(n.constructor.blockName()!==A1.blockName())throw Error(`Incorrect "recipientCertificate" for index ${e}`);switch(n.valueBlock.toString()){case"1.2.840.10045.3.1.7":A="P-256";break;case"1.3.132.0.34":A="P-384";break;case"1.3.132.0.35":A="P-521";break;default:throw Error(`Incorrect curve OID for index ${e}`)}r=await i.recipientCertificate.getPublicKey({algorithm:{algorithm:{name:"ECDH",namedCurve:A},usages:[]}},t)}else throw Error("Unsupported RecipientInfo");let n=IF[A],a=await t.generateKey({name:"ECDH",namedCurve:A},!0,["deriveBits"]),s=await t.exportKey("spki",a.publicKey),l=await t.deriveBits({name:"ECDH",public:r},a.privateKey,n),d=new uh({schema:i.keyEncryptionAlgorithm.algorithmParams}),u=t.getAlgorithmByOID(d.algorithmId,!0,"aesKWAlgorithm"),c=u.length,h=new ArrayBuffer(4),g=new Uint8Array(h);for(let e=3;e>=0;e--)g[e]=c,c>>=8;let p=new IU({keyInfo:new uh({algorithmId:d.algorithmId}),entityUInfo:i.ukm,suppPubInfo:new Aj({valueHex:h})}).toSchema().toBER(!1),C=t.getAlgorithmByOID(i.keyEncryptionAlgorithm.algorithmId,!0,"ecdhAlgorithm"),f=await go(C.kdf,l,u.length,p,t),I=await t.importKey("raw",f,{name:"AES-KW"},!0,["wrapKey"]),w=await t.wrapKey("raw",o,I,{name:"AES-KW"}),m=new fH;return m.variant=3,m.value=fT.fromBER(s),i.originator=m,i.recipientEncryptedKeys.encryptedKeys[0].encryptedKey=new Aj({valueHex:w}),{ecdhPrivateKey:a.privateKey}},u=async e=>{let A=this.recipientInfos[e].value,r=t.getAlgorithmByOID(A.keyEncryptionAlgorithm.algorithmId,!0,"keyEncryptionAlgorithm");if("RSA-OAEP"===r.name){let e=new IT({schema:A.keyEncryptionAlgorithm.algorithmParams});if(r.hash=t.getAlgorithmByOID(e.hashAlgorithm.algorithmId),"name"in r.hash==!1)throw Error(`Incorrect OID for hash algorithm: ${e.hashAlgorithm.algorithmId}`)}try{let e=await A.recipientCertificate.getPublicKey({algorithm:{algorithm:r,usages:["encrypt","wrapKey"]}},t),i=await t.encrypt(e.algorithm,e,l);A.encryptedKey=new Aj({valueHex:i})}catch{}},c=async e=>{let A=this.recipientInfos[e].value,r=t.getAlgorithmByOID(A.keyEncryptionAlgorithm.algorithmId,!0,"kekAlgorithm"),i=await t.importKey("raw",new Uint8Array(A.preDefinedKEK),r,!0,["wrapKey"]);A.encryptedKey=new Aj({valueHex:await t.wrapKey("raw",o,i,r)})},h=async e=>{let A,r=this.recipientInfos[e].value;if(!r.keyDerivationAlgorithm)throw Error('Please append encoded "keyDerivationAlgorithm"');if(!r.keyDerivationAlgorithm.algorithmParams)throw Error('Incorrectly encoded "keyDerivationAlgorithm"');try{A=new h2({schema:r.keyDerivationAlgorithm.algorithmParams})}catch{throw Error('Incorrectly encoded "keyDerivationAlgorithm"')}let i=new Uint8Array(r.password),n=await t.importKey("raw",i,"PBKDF2",!1,["deriveKey"]),a=t.getAlgorithmByOID(r.keyEncryptionAlgorithm.algorithmId,!0,"kekAlgorithm"),s="SHA-1";A.prf&&(s=t.getAlgorithmByOID(A.prf.algorithmId,!0,"prfAlgorithm").hash.name);let l=new Uint8Array(A.salt.valueBlock.valueHex),d=A.iterationCount,u=await t.deriveKey({name:"PBKDF2",hash:{name:s},salt:l,iterations:d},n,a,!0,["wrapKey"]);r.encryptedKey=new Aj({valueHex:await t.wrapKey("raw",o,u,a)})},g=[];for(let e=0;e<this.recipientInfos.length;e++)switch(this.recipientInfos[e].variant){case 1:g.push(await u(e));break;case 2:g.push(await d(e));break;case 3:g.push(await c(e));break;case 4:g.push(await h(e));break;default:throw Error(`Unknown recipient type in array with index ${e}`)}return g}async decrypt(e,A,t=gn(!0)){let r,i=A||{};if(e+1>this.recipientInfos.length)throw Error(`Maximum value for "index" is: ${this.recipientInfos.length-1}`);let n=async e=>{let A,r,n,a,o=this.recipientInfos[e].value,s=o.originator;if(i.recipientCertificate){let t=i.recipientCertificate.subjectPublicKeyInfo.algorithm.algorithmParams;if(t.constructor.blockName()!==A1.blockName())throw Error(`Incorrect "recipientCertificate" for index ${e}`);A=t.valueBlock.toString()}else if(s.value.algorithm.algorithmParams){let t=s.value.algorithm.algorithmParams;if(t.constructor.blockName()!==A1.blockName())throw Error(`Incorrect originator for index ${e}`);A=t.valueBlock.toString()}else throw Error('Parameter "recipientCertificate" is mandatory for "KeyAgreeRecipientInfo" if algorithm params are missing from originator');if(!i.recipientPrivateKey)throw Error('Parameter "recipientPrivateKey" is mandatory for "KeyAgreeRecipientInfo"');switch(A){case"1.2.840.10045.3.1.7":r="P-256",n=256;break;case"1.3.132.0.34":r="P-384",n=384;break;case"1.3.132.0.35":r="P-521",n=528;break;default:throw Error(`Incorrect curve OID for index ${e}`)}let l=t;eV.isBufferSource(i.recipientPrivateKey)?a=await t.importKey("pkcs8",i.recipientPrivateKey,{name:"ECDH",namedCurve:r},!0,["deriveBits"]):(a=i.recipientPrivateKey,"crypto"in i&&i.crypto&&(l=i.crypto.subtle)),"algorithmParams"in s.value.algorithm==!1&&(s.value.algorithm.algorithmParams=new A1({value:A}));let d=s.value.toSchema().toBER(!1),u=await t.importKey("spki",d,{name:"ECDH",namedCurve:r},!0,[]),c=await l.deriveBits({name:"ECDH",public:u},a,n);async function h(e){e=e||!1;let A=new uh({schema:o.keyEncryptionAlgorithm.algorithmParams}),r=t.getAlgorithmByOID(A.algorithmId,!0,"kwAlgorithm"),i=r.length,n=new ArrayBuffer(4),a=new Uint8Array(n);for(let e=3;e>=0;e--)a[e]=i,i>>=8;let s={algorithmId:A.algorithmId};e&&(s.algorithmParams=new Aq);let l=new IU({keyInfo:new uh(s),entityUInfo:o.ukm,suppPubInfo:new Aj({valueHex:n})}).toSchema().toBER(!1),d=t.getAlgorithmByOID(o.keyEncryptionAlgorithm.algorithmId,!0,"ecdhAlgorithm");if(!d.name)throw Error(`Incorrect OID for key encryption algorithm: ${o.keyEncryptionAlgorithm.algorithmId}`);return go(d.kdf,c,r.length,l,t)}let g=await h(),p=async e=>t.importKey("raw",e,{name:"AES-KW"},!0,["unwrapKey"]),C=await p(g),f=async e=>{let A=this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId,r=t.getAlgorithmByOID(A,!0,"contentEncryptionAlgorithm");return t.unwrapKey("raw",o.recipientEncryptedKeys.encryptedKeys[0].encryptedKey.valueBlock.valueHexView,e,{name:"AES-KW"},r,!0,["decrypt"])};try{return await f(C)}catch{let e=await h(!0);return f(await p(e))}},a=async e=>{let A,r=this.recipientInfos[e].value;if(!i.recipientPrivateKey)throw Error('Parameter "recipientPrivateKey" is mandatory for "KeyTransRecipientInfo"');let n=t.getAlgorithmByOID(r.keyEncryptionAlgorithm.algorithmId,!0,"keyEncryptionAlgorithm");if("RSA-OAEP"===n.name){let e=new IT({schema:r.keyEncryptionAlgorithm.algorithmParams});if(n.hash=t.getAlgorithmByOID(e.hashAlgorithm.algorithmId),"name"in n.hash==!1)throw Error(`Incorrect OID for hash algorithm: ${e.hashAlgorithm.algorithmId}`)}let a=t;eV.isBufferSource(i.recipientPrivateKey)?A=await t.importKey("pkcs8",i.recipientPrivateKey,n,!0,["decrypt"]):(A=i.recipientPrivateKey,"crypto"in i&&i.crypto&&(a=i.crypto.subtle));let o=await a.decrypt(A.algorithm,A,r.encryptedKey.valueBlock.valueHexView),s=this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId,l=t.getAlgorithmByOID(s,!0,"contentEncryptionAlgorithm");if("name"in l==!1)throw Error(`Incorrect "contentEncryptionAlgorithm": ${s}`);return t.importKey("raw",o,l,!0,["decrypt"])},o=async e=>{let A=this.recipientInfos[e].value;if(!i.preDefinedData)throw Error('Parameter "preDefinedData" is mandatory for "KEKRecipientInfo"');let r=t.getAlgorithmByOID(A.keyEncryptionAlgorithm.algorithmId,!0,"kekAlgorithm"),n=await t.importKey("raw",i.preDefinedData,r,!0,["unwrapKey"]),a=this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId,o=t.getAlgorithmByOID(a,!0,"contentEncryptionAlgorithm");if(!o.name)throw Error(`Incorrect "contentEncryptionAlgorithm": ${a}`);return t.unwrapKey("raw",A.encryptedKey.valueBlock.valueHexView,n,r,o,!0,["decrypt"])},s=async e=>{let A,r=this.recipientInfos[e].value;if(!i.preDefinedData)throw Error('Parameter "preDefinedData" is mandatory for "KEKRecipientInfo"');if(!r.keyDerivationAlgorithm)throw Error('Please append encoded "keyDerivationAlgorithm"');if(!r.keyDerivationAlgorithm.algorithmParams)throw Error('Incorrectly encoded "keyDerivationAlgorithm"');try{A=new h2({schema:r.keyDerivationAlgorithm.algorithmParams})}catch{throw Error('Incorrectly encoded "keyDerivationAlgorithm"')}let n=await t.importKey("raw",i.preDefinedData,"PBKDF2",!1,["deriveKey"]),a=t.getAlgorithmByOID(r.keyEncryptionAlgorithm.algorithmId,!0,"keyEncryptionAlgorithm"),o=A.prf?t.getAlgorithmByOID(A.prf.algorithmId,!0,"prfAlgorithm").hash.name:"SHA-1",s=new Uint8Array(A.salt.valueBlock.valueHex),l=A.iterationCount,d=await t.deriveKey({name:"PBKDF2",hash:{name:o},salt:s,iterations:l},n,a,!0,["unwrapKey"]),u=this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId,c=t.getAlgorithmByOID(u,!0,"contentEncryptionAlgorithm");return t.unwrapKey("raw",r.encryptedKey.valueBlock.valueHexView,d,a,c,!0,["decrypt"])};switch(this.recipientInfos[e].variant){case 1:r=await a(e);break;case 2:r=await n(e);break;case 3:r=await o(e);break;case 4:r=await s(e);break;default:throw Error(`Unknown recipient type in array with index ${e}`)}let l=this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmId,d=t.getAlgorithmByOID(l,!0,"contentEncryptionAlgorithm"),u=new Uint8Array(this.encryptedContentInfo.contentEncryptionAlgorithm.algorithmParams.valueBlock.valueHex);if(!this.encryptedContentInfo.encryptedContent)throw Error("Required property `encryptedContent` is empty");let c=this.encryptedContentInfo.getEncryptedContent();return t.decrypt({name:d.name,iv:u},r,c)}}Ij.CLASS_NAME="EnvelopedData";let Iz="safeContents",IY="parsedValue",IZ="contentInfos";class IV extends dX{constructor(e={}){super(),this.safeContents=e2(e,Iz,IV.defaultValues(Iz)),IY in e&&(this.parsedValue=e2(e,IY,IV.defaultValues(IY))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Iz:return[];case IY:return{};default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case Iz:return 0===A.length;case IY:return A instanceof Object&&0===Object.keys(A).length;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new tQ({name:A.contentInfos||"",value:pT.schema()})]})}fromSchema(e){Ad(e,[IZ]);let A=tb(e,e,IV.schema({names:{contentInfos:IZ}}));d$.assertSchema(A,this.className),this.safeContents=Array.from(A.result.contentInfos,e=>new pT({schema:e}))}toSchema(){return new A6({value:Array.from(this.safeContents,e=>e.toSchema())})}toJSON(){return{safeContents:Array.from(this.safeContents,e=>e.toJSON())}}async parseInternalValues(e,A=gn(!0)){if(dW.assert(e,Iz),dV.assert(e.safeContents,Iz,"Array"),e.safeContents.length!==this.safeContents.length)throw new dV('Length of "parameters.safeContents" must be equal to "this.safeContents.length"');for(let[t,r]of(this.parsedValue={safeContents:[]},this.safeContents.entries())){let i=e.safeContents[t],n=`parameters.safeContents[${t}]`;switch(r.contentType){case uq:{dV.assert(r.content,"this.safeContents[j].content",Aj);let e=r.content.getValue();this.parsedValue.safeContents.push({privacyMode:0,value:C6.fromBER(e)})}break;case uJ:{let e=new Ij({schema:r.content});dW.assert(n,i,"recipientCertificate","recipientKey");let t=i.recipientCertificate,a=i.recipientKey,o=await e.decrypt(0,{recipientCertificate:t,recipientPrivateKey:a},A);this.parsedValue.safeContents.push({privacyMode:2,value:C6.fromBER(o)})}break;case uF:{let e=new Cq({schema:r.content});dW.assert(n,i,"password");let t=i.password,a=await e.decrypt({password:t},A);this.parsedValue.safeContents.push({privacyMode:1,value:C6.fromBER(a)})}break;default:throw Error(`Unknown "contentType" for AuthenticatedSafe: " ${r.contentType}`)}}}async makeInternalValues(e,A=gn(!0)){if(!this.parsedValue)throw Error('Please run "parseValues" first or add "parsedValue" manually');if(dV.assert(this.parsedValue,"this.parsedValue","object"),dV.assert(this.parsedValue.safeContents,"this.parsedValue.safeContents","Array"),dV.assert(e,"parameters","object"),dW.assert(e,"safeContents"),dV.assert(e.safeContents,"parameters.safeContents","Array"),e.safeContents.length!==this.parsedValue.safeContents.length)throw new dV('Length of "parameters.safeContents" must be equal to "this.parsedValue.safeContents"');for(let[t,r]of(this.safeContents=[],this.parsedValue.safeContents.entries()))switch(dW.assert("content",r,"privacyMode","value"),dV.assert(r.value,"content.value",C6),r.privacyMode){case 0:{let e=r.value.toSchema().toBER(!1);this.safeContents.push(new pT({contentType:"1.2.840.113549.1.7.1",content:new Aj({valueHex:e})}))}break;case 1:{let i=new Cq,n=e.safeContents[t];n.contentToEncrypt=r.value.toSchema().toBER(!1),await i.encrypt(n,A),this.safeContents.push(new pT({contentType:"1.2.840.113549.1.7.6",content:i.toSchema()}))}break;case 2:{let i=new Ij,n=r.value.toSchema().toBER(!1),a=e.safeContents[t];switch(dW.assert(`parameters.safeContents[${t}]`,a,"encryptingCertificate","encryptionAlgorithm"),!0){case"aes-cbc"===a.encryptionAlgorithm.name.toLowerCase():case"aes-gcm"===a.encryptionAlgorithm.name.toLowerCase():break;default:throw Error(`Incorrect parameter "encryptionAlgorithm" in "parameters.safeContents[i]": ${a.encryptionAlgorithm}`)}switch(!0){case 128===a.encryptionAlgorithm.length:case 192===a.encryptionAlgorithm.length:case 256===a.encryptionAlgorithm.length:break;default:throw Error(`Incorrect parameter "encryptionAlgorithm.length" in "parameters.safeContents[i]": ${a.encryptionAlgorithm.length}`)}let o=a.encryptionAlgorithm;i.addRecipientByCertificate(a.encryptingCertificate,{},void 0,A),await i.encrypt(o,n,A),this.safeContents.push(new pT({contentType:"1.2.840.113549.1.7.3",content:i.toSchema()}))}break;default:throw Error(`Incorrect value for "content.privacyMode": ${r.privacyMode}`)}return this}}IV.CLASS_NAME="AuthenticatedSafe";let IW="hashAlgorithm",I$="issuerNameHash",IX="issuerKeyHash",I0="serialNumber",I1=[IW,I$,IX,I0];class I8 extends dX{static async create(e,A,t=gn(!0)){let r=new I8;return await r.createForCertificate(e,A,t),r}constructor(e={}){super(),this.hashAlgorithm=e2(e,IW,I8.defaultValues(IW)),this.issuerNameHash=e2(e,I$,I8.defaultValues(I$)),this.issuerKeyHash=e2(e,IX,I8.defaultValues(IX)),this.serialNumber=e2(e,I0,I8.defaultValues(I0)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case IW:return new uh;case I$:case IX:return new Aj;case I0:return new AW;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case IW:return""===A.algorithmId&&"algorithmParams"in A==!1;case I$:case IX:case I0:return A.isEqual(I8.defaultValues(I0));default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[uh.schema(A.hashAlgorithmObject||{names:{blockName:A.hashAlgorithm||""}}),new Aj({name:A.issuerNameHash||""}),new Aj({name:A.issuerKeyHash||""}),new AW({name:A.serialNumber||""})]})}fromSchema(e){Ad(e,I1);let A=tb(e,e,I8.schema({names:{hashAlgorithm:IW,issuerNameHash:I$,issuerKeyHash:IX,serialNumber:I0}}));d$.assertSchema(A,this.className),this.hashAlgorithm=new uh({schema:A.result.hashAlgorithm}),this.issuerNameHash=A.result.issuerNameHash,this.issuerKeyHash=A.result.issuerKeyHash,this.serialNumber=A.result.serialNumber}toSchema(){return new A6({value:[this.hashAlgorithm.toSchema(),this.issuerNameHash,this.issuerKeyHash,this.serialNumber]})}toJSON(){return{hashAlgorithm:this.hashAlgorithm.toJSON(),issuerNameHash:this.issuerNameHash.toJSON(),issuerKeyHash:this.issuerKeyHash.toJSON(),serialNumber:this.serialNumber.toJSON()}}isEqual(e){return this.hashAlgorithm.algorithmId===e.hashAlgorithm.algorithmId&&!!eV.isEqual(this.issuerNameHash.valueBlock.valueHexView,e.issuerNameHash.valueBlock.valueHexView)&&!!eV.isEqual(this.issuerKeyHash.valueBlock.valueHexView,e.issuerKeyHash.valueBlock.valueHexView)&&!!this.serialNumber.isEqual(e.serialNumber)}async createForCertificate(e,A,t=gn(!0)){dW.assert(A,IW,"issuerCertificate");let r=t.getOIDByAlgorithm({name:A.hashAlgorithm},!0,"hashAlgorithm");this.hashAlgorithm=new uh({algorithmId:r,algorithmParams:new Aq});let i=A.issuerCertificate;this.serialNumber=e.serialNumber;let n=await t.digest({name:A.hashAlgorithm},i.subject.toSchema().toBER(!1));this.issuerNameHash=new Aj({valueHex:n});let a=i.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView,o=await t.digest({name:A.hashAlgorithm},a);this.issuerKeyHash=new Aj({valueHex:o})}}I8.CLASS_NAME="CertID";let I4="certID",I2="certStatus",I6="thisUpdate",I3="nextUpdate",I5="singleExtensions",I9=[I4,I2,I6,I3,I5];class I7 extends dX{constructor(e={}){super(),this.certID=e2(e,I4,I7.defaultValues(I4)),this.certStatus=e2(e,I2,I7.defaultValues(I2)),this.thisUpdate=e2(e,I6,I7.defaultValues(I6)),I3 in e&&(this.nextUpdate=e2(e,I3,I7.defaultValues(I3))),I5 in e&&(this.singleExtensions=e2(e,I5,I7.defaultValues(I5))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case I4:return new I8;case I2:return{};case I6:case I3:return new Date(0,0,0);case I5:return[];default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case I4:return I8.compareWithDefault("hashAlgorithm",A.hashAlgorithm)&&I8.compareWithDefault("issuerNameHash",A.issuerNameHash)&&I8.compareWithDefault("issuerKeyHash",A.issuerKeyHash)&&I8.compareWithDefault("serialNumber",A.serialNumber);case I2:return 0===Object.keys(A).length;case I6:case I3:return A===I7.defaultValues(e);default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[I8.schema(A.certID||{}),new tB({value:[new AM({name:A.certStatus||"",idBlock:{tagClass:3,tagNumber:0}}),new Ax({name:A.certStatus||"",idBlock:{tagClass:3,tagNumber:1},value:[new tC,new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new A$]})]}),new AM({name:A.certStatus||"",idBlock:{tagClass:3,tagNumber:2},lenBlock:{length:1}})]}),new tC({name:A.thisUpdate||""}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new tC({name:A.nextUpdate||""})]}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[g_.schema(A.singleExtensions||{})]})]})}fromSchema(e){Ad(e,I9);let A=tb(e,e,I7.schema({names:{certID:{names:{blockName:I4}},certStatus:I2,thisUpdate:I6,nextUpdate:I3,singleExtensions:{names:{blockName:I5}}}}));d$.assertSchema(A,this.className),this.certID=new I8({schema:A.result.certID}),this.certStatus=A.result.certStatus,this.thisUpdate=A.result.thisUpdate.toDate(),I3 in A.result&&(this.nextUpdate=A.result.nextUpdate.toDate()),I5 in A.result&&(this.singleExtensions=Array.from(A.result.singleExtensions.valueBlock.value,e=>new gO({schema:e})))}toSchema(){let e=[];return e.push(this.certID.toSchema()),e.push(this.certStatus),e.push(new tC({valueDate:this.thisUpdate})),this.nextUpdate&&e.push(new Ax({idBlock:{tagClass:3,tagNumber:0},value:[new tC({valueDate:this.nextUpdate})]})),this.singleExtensions&&e.push(new Ax({idBlock:{tagClass:3,tagNumber:1},value:[new A6({value:Array.from(this.singleExtensions,e=>e.toSchema())})]})),new A6({value:e})}toJSON(){let e={certID:this.certID.toJSON(),certStatus:this.certStatus.toJSON(),thisUpdate:this.thisUpdate};return this.nextUpdate&&(e.nextUpdate=this.nextUpdate),this.singleExtensions&&(e.singleExtensions=Array.from(this.singleExtensions,e=>e.toJSON())),e}}I7.CLASS_NAME="SingleResponse";let we="version",wA="responderID",wt="producedAt",wr="responses",wi="responseExtensions",wn="ResponseData",wa=`${wn}.${we}`,wo=`${wn}.${wA}`,ws=`${wn}.${wt}`,wl=`${wn}.${wr}`,wd=`${wn}.${wi}`,wu=[wn,wa,wo,ws,wl,wd];class wc extends dX{get tbs(){return eV.toArrayBuffer(this.tbsView)}set tbs(e){this.tbsView=new Uint8Array(e)}constructor(e={}){super(),this.tbsView=new Uint8Array(e2(e,"tbs",wc.defaultValues("tbs"))),we in e&&(this.version=e2(e,we,wc.defaultValues(we))),this.responderID=e2(e,wA,wc.defaultValues(wA)),this.producedAt=e2(e,wt,wc.defaultValues(wt)),this.responses=e2(e,wr,wc.defaultValues(wr)),wi in e&&(this.responseExtensions=e2(e,wi,wc.defaultValues(wi))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case we:return 0;case"tbs":return dZ;case wA:return{};case wt:return new Date(0,0,0);case wr:case wi:return[];default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case"tbs":return 0===A.byteLength;case wA:return 0===Object.keys(A).length;case wt:return A===wc.defaultValues(e);case wr:case wi:return 0===A.length;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||wn,value:[new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new AW({name:A.version||wa})]}),new tB({value:[new Ax({name:A.responderID||wo,idBlock:{tagClass:3,tagNumber:1},value:[d3.schema(A.ResponseDataByName||{names:{blockName:"ResponseData.byName"}})]}),new Ax({name:A.responderID||wo,idBlock:{tagClass:3,tagNumber:2},value:[new Aj({name:A.ResponseDataByKey||"ResponseData.byKey"})]})]}),new tC({name:A.producedAt||ws}),new A6({value:[new tQ({name:wl,value:I7.schema(A.response||{})})]}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[g_.schema(A.extensions||{names:{blockName:wd}})]})]})}fromSchema(e){Ad(e,wu);let A=tb(e,e,wc.schema());d$.assertSchema(A,this.className),this.tbsView=A.result.ResponseData.valueBeforeDecodeView,wa in A.result&&(this.version=A.result[wa].valueBlock.valueDec),1===A.result[wo].idBlock.tagNumber?this.responderID=new d3({schema:A.result[wo].valueBlock.value[0]}):this.responderID=A.result[wo].valueBlock.value[0],this.producedAt=A.result[ws].toDate(),this.responses=Array.from(A.result[wl],e=>new I7({schema:e})),wd in A.result&&(this.responseExtensions=Array.from(A.result[wd].valueBlock.value,e=>new gO({schema:e})))}toSchema(e=!1){let A;if(!1===e){if(!this.tbsView.byteLength)return wc.schema();let e=AU(this.tbsView);d$.assert(e,"TBS Response Data"),A=e.result}else{let e=[];we in this&&e.push(new Ax({idBlock:{tagClass:3,tagNumber:0},value:[new AW({value:this.version})]})),this.responderID instanceof d3?e.push(new Ax({idBlock:{tagClass:3,tagNumber:1},value:[this.responderID.toSchema()]})):e.push(new Ax({idBlock:{tagClass:3,tagNumber:2},value:[this.responderID]})),e.push(new tC({valueDate:this.producedAt})),e.push(new A6({value:Array.from(this.responses,e=>e.toSchema())})),this.responseExtensions&&e.push(new Ax({idBlock:{tagClass:3,tagNumber:1},value:[new A6({value:Array.from(this.responseExtensions,e=>e.toSchema())})]})),A=new A6({value:e})}return A}toJSON(){let e={};return we in this&&(e.version=this.version),this.responderID&&(e.responderID=this.responderID),this.producedAt&&(e.producedAt=this.producedAt),this.responses&&(e.responses=Array.from(this.responses,e=>e.toJSON())),this.responseExtensions&&(e.responseExtensions=Array.from(this.responseExtensions,e=>e.toJSON())),e}}wc.CLASS_NAME="ResponseData";let wh="trustedCerts",wg="certs",wp="crls",wC="ocsps",wf="checkDate",wI="findOrigin",ww="findIssuer";(m=ez||(ez={}))[m.unknown=-1]="unknown",m[m.success=0]="success",m[m.noRevocation=11]="noRevocation",m[m.noPath=60]="noPath",m[m.noValidPath=97]="noValidPath";class wm extends Error{constructor(e,A){super(A),this.name=wm.NAME,this.code=e,this.message=A}}wm.NAME="ChainValidationError";class wE{constructor(e={}){this.trustedCerts=e2(e,wh,this.defaultValues(wh)),this.certs=e2(e,wg,this.defaultValues(wg)),this.crls=e2(e,wp,this.defaultValues(wp)),this.ocsps=e2(e,wC,this.defaultValues(wC)),this.checkDate=e2(e,wf,this.defaultValues(wf)),this.findOrigin=e2(e,wI,this.defaultValues(wI)),this.findIssuer=e2(e,ww,this.defaultValues(ww))}static defaultFindOrigin(e,A){for(let t of(0===e.tbsView.byteLength&&(e.tbsView=new Uint8Array(e.encodeTBS().toBER())),A.certs))if(0===t.tbsView.byteLength&&(t.tbsView=new Uint8Array(t.encodeTBS().toBER())),eV.isEqual(e.tbsView,t.tbsView))return"Intermediate Certificates";for(let t of A.trustedCerts)if(0===t.tbsView.byteLength&&(t.tbsView=new Uint8Array(t.encodeTBS().toBER())),eV.isEqual(e.tbsView,t.tbsView))return"Trusted Certificates";return"Unknown"}async defaultFindIssuer(e,A,t=gn(!0)){let r=[],i=null,n=null,a=null;if(e.subject.isEqual(e.issuer))try{if(await e.verify(void 0,t))return[e]}catch{}if(e.extensions){for(let A of e.extensions)if(A.extnID===ux&&A.parsedValue instanceof u0){A.parsedValue.keyIdentifier?i=A.parsedValue.keyIdentifier:(A.parsedValue.authorityCertIssuer&&(n=A.parsedValue.authorityCertIssuer),A.parsedValue.authorityCertSerialNumber&&(a=A.parsedValue.authorityCertSerialNumber));break}}function o(A){if(null!==i&&A.extensions){let e=!1;for(let t of A.extensions)if("2.5.29.14"===t.extnID&&t.parsedValue){e=!0,eV.isEqual(t.parsedValue.valueBlock.valueHex,i.valueBlock.valueHexView)&&r.push(A);break}if(e)return}let t=!1;null!==a&&(t=A.serialNumber.isEqual(a)),null!==n?A.subject.isEqual(n)&&t&&r.push(A):e.issuer.isEqual(A.subject)&&r.push(A)}for(let e of A.trustedCerts)o(e);for(let e of A.certs)o(e);for(let A=r.length-1;A>=0;A--)try{let i=await e.verify(r[A],t);!1===i&&r.splice(A,1)}catch{r.splice(A,1)}return r}defaultValues(e){switch(e){case wh:case wg:case wp:case wC:return[];case wf:return new Date;case wI:return wE.defaultFindOrigin;case ww:return this.defaultFindIssuer;default:throw Error(`Invalid member name for CertificateChainValidationEngine class: ${e}`)}}async sort(e=!1,A=gn(!0)){let t,r=[],i=async(e,A)=>{let t=[];if(function(e,A){for(let t=0;t<A.length;t++)if(eV.isEqual(e.tbsView,A[t].tbsView))return!0;return!1}(e,this.trustedCerts))return[[e]];let r=await this.findIssuer(e,this,A);if(0===r.length)throw Error("No valid certificate paths found");for(let n=0;n<r.length;n++){if(eV.isEqual(r[n].tbsView,e.tbsView)){t.push([r[n]]);continue}let a=await i(r[n],A);for(let e=0;e<a.length;e++){let A=a[e].slice();A.splice(0,0,r[n]),function(e){let A=!0;for(let t=0;t<e.length;t++){for(let r=0;r<e.length;r++)if(r!==t&&e[t]===e[r]){A=!1;break}if(!A)break}return A}(A)?t.push(A):t.push(a[e])}}return t},n=async e=>{let t=[],i=[],n=[];if(t.push(...r.filter(A=>e.issuer.isEqual(A.subject))),0===t.length)return{status:1,statusMessage:"No certificate's issuers"};if(i.push(...this.crls.filter(A=>A.issuer.isEqual(e.issuer))),0===i.length)return{status:2,statusMessage:"No CRLs for specific certificate issuer"};for(let e=0;e<i.length;e++){let r=i[e];if(!r.nextUpdate||!(r.nextUpdate.value<this.checkDate))for(let r=0;r<t.length;r++)try{if(await i[e].verify({issuerCertificate:t[r]},A)){n.push({crl:i[e],certificate:t[r]});break}}catch{}}return n.length?{status:0,statusMessage:"",result:n}:{status:3,statusMessage:"No valid CRLs found"}},a=async(e,t)=>{let r=A.getAlgorithmByOID(e.signatureAlgorithm.algorithmId);if(!r.name||!r.hash)return 1;for(let r=0;r<this.ocsps.length;r++){let i=this.ocsps[r],n=await i.getCertificateStatus(e,t,A);if(n.isForCertificate){if(0===n.status)return 0;return 1}}return 2};async function o(e,A=!1){let t=!1,r=!1,i=!1,n=!1;if(e.extensions){for(let A=0;A<e.extensions.length;A++){let a=e.extensions[A];if(a.critical&&!a.parsedValue)return{result:!1,resultCode:6,resultMessage:`Unable to parse critical certificate extension: ${a.extnID}`};if("2.5.29.15"===a.extnID){i=!0;let e=new Uint8Array(a.parsedValue.valueBlock.valueHex);(4&e[0])==4&&(r=!0),(2&e[0])==2&&(n=!0)}a.extnID===uv&&"cA"in a.parsedValue&&!0===a.parsedValue.cA&&(t=!0)}if(!0===r&&!1===t)return{result:!1,resultCode:3,resultMessage:'Unable to build certificate chain - using "keyCertSign" flag set without BasicConstraints'};if(!0===i&&!0===t&&!1===r)return{result:!1,resultCode:4,resultMessage:'Unable to build certificate chain - "keyCertSign" flag was not set'};if(!0===t&&!0===i&&A&&!1===n)return{result:!1,resultCode:5,resultMessage:'Unable to build certificate chain - intermediate certificate must have "cRLSign" key usage flag'}}return!1===t?{result:!1,resultCode:7,resultMessage:"Unable to build certificate chain - more than one possible end-user certificate"}:{result:!0,resultCode:0,resultMessage:""}}let s=async(A,t)=>{for(let e=0;e<A.length;e++)if(A[e].notBefore.value>t||A[e].notAfter.value<t)return{result:!1,resultCode:8,resultMessage:"The certificate is either not yet valid or expired"};if(A.length<2)return{result:!1,resultCode:9,resultMessage:"Too short certificate path"};for(let e=A.length-2;e>=0;e--)if(!1===A[e].issuer.isEqual(A[e].subject)&&!1===A[e].issuer.isEqual(A[e+1].subject))return{result:!1,resultCode:10,resultMessage:"Incorrect name chaining"};if(0!==this.crls.length||0!==this.ocsps.length)for(let t=0;t<A.length-1;t++){let r=2,i={status:0,statusMessage:""};if(0!==this.ocsps.length)switch(r=await a(A[t],A[t+1])){case 0:continue;case 1:return{result:!1,resultCode:12,resultMessage:"One of certificates was revoked via OCSP response"}}if(0!==this.crls.length){if(0===(i=await n(A[t])).status&&i.result)for(let e=0;e<i.result.length;e++){if(i.result[e].crl.isCertificateRevoked(A[t]))return{result:!1,resultCode:12,resultMessage:"One of certificates had been revoked"};if(!1===(await o(i.result[e].certificate,!0)).result)return{result:!1,resultCode:13,resultMessage:"CRL issuer certificate is not a CA certificate or does not have crlSign flag"}}else if(!1===e)throw new wm(ez.noRevocation,`No revocation values found for one of certificates: ${i.statusMessage}`)}else if(2===r)return{result:!1,resultCode:11,resultMessage:"No revocation values found for one of certificates"};if(2===r&&2===i.status&&e){let e=A[t+1],r=!1;if(e.extensions)for(let A of e.extensions)switch(A.extnID){case uN:case uO:case uP:r=!0}if(r)throw new wm(ez.noRevocation,`No revocation values found for one of certificates: ${i.statusMessage}`)}}for(let[e,t]of A.entries())if(e&&!(await o(t)).result)return{result:!1,resultCode:14,resultMessage:"One of intermediate certificates is not a CA certificate"};return{result:!0}};r.push(...this.trustedCerts),r.push(...this.certs);for(let e=0;e<r.length;e++)for(let A=0;A<r.length;A++)if(e!==A&&eV.isEqual(r[e].tbsView,r[A].tbsView)){r.splice(A,1),e=0;break}let l=r[r.length-1],d=[l];if(0===(t=await i(l,A)).length)throw new wm(ez.noPath,"Unable to find certificate path");for(let e=t.length-1;e>=0;e--){let A=!1;for(let r=0;r<t[e].length;r++){let i=t[e][r];for(let e=0;e<this.trustedCerts.length;e++)if(eV.isEqual(i.tbsView,this.trustedCerts[e].tbsView)){A=!0;break}if(A)break}A||t.splice(e,1)}if(0===t.length)throw new wm(ez.noValidPath,"No valid certificate paths found");let u=t[0].length,c=0;for(let e=0;e<t.length;e++)t[e].length<u&&(u=t[e].length,c=e);for(let e=0;e<t[c].length;e++)d.push(t[c][e]);if(!1===(t=await s(d,this.checkDate)).result)throw t;return d}async verify(e={},A=gn(!0)){function t(e,A){let t=d0(e),r=d0(A),i=t.split("."),n=r.split("."),a=i.length,o=n.length;if(0===a||0===o||a<o)return!1;for(let e=0;e<a;e++)if(0===i[e].length)return!1;for(let e=0;e<o;e++)if(0===n[e].length){if(0===e){if(1===o)return!1;continue}return!1}for(let e=0;e<o;e++)if(0!==n[o-1-e].length&&0!==i[a-1-e].localeCompare(n[o-1-e]))return!1;return!0}function r(e,A){let r=d0(e),i=d0(A),n=r.split("@"),a=i.split("@");if(0===n.length||0===a.length||n.length<a.length)return!1;if(1===a.length){if(t(n[1],a[0])){let e=n[1].split("."),A=a[0].split(".");return 0===A[0].length||e.length===A.length}return!1}return 0===r.localeCompare(i)}function i(e,A){let r=d0(e),i=d0(A),n=r.split("/");if(i.split("/").length>1)return!1;if(n.length>1){for(let e=0;e<n.length;e++)if(n[e].length>0&&":"!==n[e].charAt(n[e].length-1)){r=n[e].split(":")[0];break}}if(t(r,i)){let e=r.split("."),A=i.split(".");return 0===A[0].length||e.length===A.length}return!1}function n(e,A){let t=e.valueBlock.valueHexView,r=A.valueBlock.valueHexView;if(4===t.length&&8===r.length){for(let e=0;e<4;e++)if((t[e]^r[e])&r[e+4])return!1;return!0}if(16===t.length&&32===r.length){for(let e=0;e<16;e++)if((t[e]^r[e])&r[e+16])return!1;return!0}return!1}function a(e,A){if(0===e.typesAndValues.length||0===A.typesAndValues.length)return!0;if(e.typesAndValues.length<A.typesAndValues.length)return!1;let t=!0,r=0;for(let i=0;i<A.typesAndValues.length;i++){let n=!1;for(let a=r;a<e.typesAndValues.length;a++)if(n=e.typesAndValues[a].isEqual(A.typesAndValues[i]),e.typesAndValues[a].type===A.typesAndValues[i].type&&(t=t&&n),!0===n)if(0!==r&&r!==a)return!1;else{r=a+1;break}if(!1===n)return!1}return 0!==r&&t}try{if(0===this.certs.length)throw Error("Empty certificate array");let o=e.passedWhenNotRevValues||!1,s=e.initialPolicySet||[uU],l=e.initialExplicitPolicy||!1,d=e.initialPolicyMappingInhibit||!1,u=e.initialInhibitPolicy||!1,c=e.initialPermittedSubtreesSet||[],h=e.initialExcludedSubtreesSet||[],g=e.initialRequiredNameForms||[],p=l,C=d,f=u,I=[!1,!1,!1],w=0,m=0,E=0,y=c,B=h,Q=1;this.certs=await this.sort(o,A);let D=[];D.push(uU);let b=[],S=Array(this.certs.length-1);for(let e=0;e<this.certs.length-1;e++)S[e]=!0;b.push(S);let k=Array(this.certs.length-1),R=Array(this.certs.length-1),v=p?this.certs.length-1:-1;for(let e=this.certs.length-2;e>=0;e--,Q++){let A=this.certs[e];if(A.extensions){for(let t=0;t<A.extensions.length;t++){let r=A.extensions[t];if(r.extnID===uH){R[e]=r.parsedValue;for(let A=0;A<D.length;A++)if(D[A]===uU){delete b[A][e];break}for(let A=0;A<r.parsedValue.certificatePolicies.length;A++){let t=-1,i=r.parsedValue.certificatePolicies[A].policyIdentifier;for(let e=0;e<D.length;e++)if(i===D[e]){t=e;break}if(-1===t){D.push(i);let A=Array(this.certs.length-1);A[e]=!0,b.push(A)}else b[t][e]=!0}}if(r.extnID===u_){if(C)return{result:!1,resultCode:98,resultMessage:"Policy mapping prohibited"};k[e]=r.parsedValue}r.extnID===uL&&!1===p&&(0===r.parsedValue.requireExplicitPolicy?(p=!0,v=e):!1===I[0]?(I[0]=!0,w=r.parsedValue.requireExplicitPolicy):w=w>r.parsedValue.requireExplicitPolicy?r.parsedValue.requireExplicitPolicy:w,0===r.parsedValue.inhibitPolicyMapping?C=!0:!1===I[1]?(I[1]=!0,m=r.parsedValue.inhibitPolicyMapping+1):m=m>r.parsedValue.inhibitPolicyMapping+1?r.parsedValue.inhibitPolicyMapping+1:m),"2.5.29.54"===r.extnID&&!1===f&&(0===r.parsedValue.valueBlock.valueDec?f=!0:!1===I[2]?(I[2]=!0,E=r.parsedValue.valueBlock.valueDec):E=E>r.parsedValue.valueBlock.valueDec?r.parsedValue.valueBlock.valueDec:E)}if(!0===f){let A=-1;for(let e=0;e<D.length;e++)if(D[e]===uU){A=e;break}-1!==A&&delete b[0][e]}!1===p&&!0===I[0]&&(w--,0===w&&(p=!0,v=e,I[0]=!1)),!1===C&&!0===I[1]&&(m--,0===m&&(C=!0,I[1]=!1)),!1===f&&!0===I[2]&&(E--,0===E&&(f=!0,I[2]=!1))}}for(let e=0;e<this.certs.length-1;e++)if(e<this.certs.length-2&&void 0!==k[e+1])for(let A=0;A<k[e+1].mappings.length;A++){if(k[e+1].mappings[A].issuerDomainPolicy===uU||k[e+1].mappings[A].subjectDomainPolicy===uU)return{result:!1,resultCode:99,resultMessage:'The "anyPolicy" should not be a part of policy mapping scheme'};let t=-1,r=-1;for(let i=0;i<D.length;i++)D[i]===k[e+1].mappings[A].issuerDomainPolicy&&(t=i),D[i]===k[e+1].mappings[A].subjectDomainPolicy&&(r=i);void 0!==b[t][e]&&delete b[t][e];for(let i=0;i<R[e].certificatePolicies.length;i++)if(k[e+1].mappings[A].subjectDomainPolicy===R[e].certificatePolicies[i].policyIdentifier&&-1!==t&&-1!==r)for(let A=0;A<=e;A++)void 0!==b[r][A]&&(b[t][A]=!0,delete b[r][A])}for(let e=0;e<D.length;e++)if(D[e]===uU)for(let A=0;A<v;A++)delete b[e][A];let G=[];for(let e=0;e<b.length;e++){let A=!0;for(let t=0;t<this.certs.length-1;t++){let r=!1;if(t<v&&D[e]===uU&&D.length>1){A=!1;break}if(void 0===b[e][t]){if(t>=v){for(let e=0;e<D.length;e++)if(D[e]===uU){!0===b[e][t]&&(r=!0);break}}if(!r){A=!1;break}}}!0===A&&G.push(D[e])}let T=[];if(1===s.length&&s[0]===uU&&!1===p)T=s;else if(1===G.length&&G[0]===uU)T=s;else for(let e=0;e<G.length;e++)for(let A=0;A<s.length;A++)if(s[A]===G[e]||s[A]===uU){T.push(G[e]);break}let M={result:T.length>0,resultCode:0,resultMessage:T.length>0?"":'Zero "userConstrPolicies" array, no intersections with "authConstrPolicies"',authConstrPolicies:G,userConstrPolicies:T,explicitPolicyIndicator:p,policyMappings:k,certificatePath:this.certs};if(0===T.length||!1===M.result)return M;Q=1;for(let e=this.certs.length-2;e>=0;e--,Q++){let A=this.certs[e],o=[],s=[],l=[];if(A.extensions)for(let e=0;e<A.extensions.length;e++){let t=A.extensions[e];t.extnID===uM&&("permittedSubtrees"in t.parsedValue&&(s=s.concat(t.parsedValue.permittedSubtrees)),"excludedSubtrees"in t.parsedValue&&(l=l.concat(t.parsedValue.excludedSubtrees))),t.extnID===uk&&(o=o.concat(t.parsedValue.altNames))}let d=g.length<=0;for(let e=0;e<g.length;e++)if(4===g[e].base.type){if(g[e].base.value.typesAndValues.length!==A.subject.typesAndValues.length)continue;d=!0;for(let t=0;t<A.subject.typesAndValues.length;t++)if(A.subject.typesAndValues[t].type!==g[e].base.value.typesAndValues[t].type){d=!1;break}}if(!1===d)throw M.result=!1,M.resultCode=21,M.resultMessage="No necessary name form found",M;let u=[[],[],[],[],[]];for(let e=0;e<y.length;e++)switch(y[e].base.type){case 1:u[0].push(y[e]);break;case 2:u[1].push(y[e]);break;case 4:u[2].push(y[e]);break;case 6:u[3].push(y[e]);break;case 7:u[4].push(y[e])}for(let e=0;e<5;e++){let s=!1,l=!1,d=u[e];for(let u=0;u<d.length;u++){switch(e){case 0:if(o.length>0)for(let e=0;e<o.length;e++)1===o[e].type&&(l=!0,s=s||r(o[e].value,d[u].base.value));else for(let e=0;e<A.subject.typesAndValues.length;e++)("1.2.840.113549.1.9.1"===A.subject.typesAndValues[e].type||"0.9.2342.19200300.100.1.3"===A.subject.typesAndValues[e].type)&&(l=!0,s=s||r(A.subject.typesAndValues[e].value.valueBlock.value,d[u].base.value));break;case 1:if(o.length>0)for(let e=0;e<o.length;e++)2===o[e].type&&(l=!0,s=s||t(o[e].value,d[u].base.value));break;case 2:l=!0,s=a(A.subject,d[u].base.value);break;case 3:if(o.length>0)for(let e=0;e<o.length;e++)6===o[e].type&&(l=!0,s=s||i(o[e].value,d[u].base.value));break;case 4:if(o.length>0)for(let e=0;e<o.length;e++)7===o[e].type&&(l=!0,s=s||n(o[e].value,d[u].base.value))}if(s)break}if(!1===s&&d.length>0&&l)throw M.result=!1,M.resultCode=41,M.resultMessage='Failed to meet "permitted sub-trees" name constraint',M}let c=!1;for(let e=0;e<B.length;e++){switch(B[e].base.type){case 1:if(o.length>=0)for(let A=0;A<o.length;A++)1===o[A].type&&(c=c||r(o[A].value,B[e].base.value));else for(let t=0;t<A.subject.typesAndValues.length;t++)("1.2.840.113549.1.9.1"===A.subject.typesAndValues[t].type||"0.9.2342.19200300.100.1.3"===A.subject.typesAndValues[t].type)&&(c=c||r(A.subject.typesAndValues[t].value.valueBlock.value,B[e].base.value));break;case 2:if(o.length>0)for(let A=0;A<o.length;A++)2===o[A].type&&(c=c||t(o[A].value,B[e].base.value));break;case 4:c=c||a(A.subject,B[e].base.value);break;case 6:if(o.length>0)for(let A=0;A<o.length;A++)6===o[A].type&&(c=c||i(o[A].value,B[e].base.value));break;case 7:if(o.length>0)for(let A=0;A<o.length;A++)7===o[A].type&&(c=c||n(o[A].value,B[e].base.value))}if(c)break}if(!0===c)throw M.result=!1,M.resultCode=42,M.resultMessage='Failed to meet "excluded sub-trees" name constraint',M;y=y.concat(s),B=B.concat(l)}return M}catch(e){if(e instanceof Error){if(e instanceof wm)return{result:!1,resultCode:e.code,resultMessage:e.message,error:e};return{result:!1,resultCode:ez.unknown,resultMessage:e.message,error:e}}if(e&&"object"==typeof e&&"resultMessage"in e)return e;return{result:!1,resultCode:-1,resultMessage:`${e}`}}}}let wy="tbsResponseData",wB="signatureAlgorithm",wQ="signature",wD="certs",wb="BasicOCSPResponse",wS=`${wb}.${wy}`,wk=`${wb}.${wB}`,wR=`${wb}.${wQ}`,wv=`${wb}.${wD}`,wG=[wS,wk,wR,wv];class wT extends dX{constructor(e={}){super(),this.tbsResponseData=e2(e,wy,wT.defaultValues(wy)),this.signatureAlgorithm=e2(e,wB,wT.defaultValues(wB)),this.signature=e2(e,wQ,wT.defaultValues(wQ)),wD in e&&(this.certs=e2(e,wD,wT.defaultValues(wD))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case wy:return new wc;case wB:return new uh;case wQ:return new AY;case wD:return[];default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case"type":{let e=wc.compareWithDefault("tbs",A.tbs)&&wc.compareWithDefault("responderID",A.responderID)&&wc.compareWithDefault("producedAt",A.producedAt)&&wc.compareWithDefault("responses",A.responses);return"responseExtensions"in A&&(e=e&&wc.compareWithDefault("responseExtensions",A.responseExtensions)),e}case wB:return""===A.algorithmId&&"algorithmParams"in A==!1;case wQ:return A.isEqual(wT.defaultValues(e));case wD:return 0===A.length;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||wb,value:[wc.schema(A.tbsResponseData||{names:{blockName:wS}}),uh.schema(A.signatureAlgorithm||{names:{blockName:wk}}),new AY({name:A.signature||wR}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new A6({value:[new tQ({name:wv,value:CA.schema(A.certs||{})})]})]})]})}fromSchema(e){Ad(e,wG);let A=tb(e,e,wT.schema());d$.assertSchema(A,this.className),this.tbsResponseData=new wc({schema:A.result[wS]}),this.signatureAlgorithm=new uh({schema:A.result[wk]}),this.signature=A.result[wR],wv in A.result&&(this.certs=Array.from(A.result[wv],e=>new CA({schema:e})))}toSchema(){let e=[];return e.push(this.tbsResponseData.toSchema()),e.push(this.signatureAlgorithm.toSchema()),e.push(this.signature),this.certs&&e.push(new Ax({idBlock:{tagClass:3,tagNumber:0},value:[new A6({value:Array.from(this.certs,e=>e.toSchema())})]})),new A6({value:e})}toJSON(){let e={tbsResponseData:this.tbsResponseData.toJSON(),signatureAlgorithm:this.signatureAlgorithm.toJSON(),signature:this.signature.toJSON()};return this.certs&&(e.certs=Array.from(this.certs,e=>e.toJSON())),e}async getCertificateStatus(e,A,t=gn(!0)){let r={isForCertificate:!1,status:2},i={},n=[];for(let r of this.tbsResponseData.responses){let a=t.getAlgorithmByOID(r.certID.hashAlgorithm.algorithmId,!0,"CertID.hashAlgorithm");if(!i[a.name]){i[a.name]=1;let r=new I8;n.push(r),await r.createForCertificate(e,{hashAlgorithm:a.name,issuerCertificate:A},t)}}for(let e of this.tbsResponseData.responses)for(let A of n)if(e.certID.isEqual(A)){r.isForCertificate=!0;try{switch(e.certStatus.idBlock.isConstructed){case!0:1===e.certStatus.idBlock.tagNumber&&(r.status=1);break;case!1:switch(e.certStatus.idBlock.tagNumber){case 0:r.status=0;break;case 2:r.status=2}}}catch{}return r}return r}async sign(e,A="SHA-1",t=gn(!0)){if(!e)throw Error("Need to provide a private key for signing");let r=await t.getSignatureParameters(e,A),i=r.parameters.algorithm;if(!("name"in i))throw Error("Empty algorithm");this.signatureAlgorithm=r.signatureAlgorithm,this.tbsResponseData.tbsView=new Uint8Array(this.tbsResponseData.toSchema(!0).toBER());let n=await t.signWithPrivateKey(this.tbsResponseData.tbsView,e,{algorithm:i});this.signature=new AY({valueHex:n})}async verify(e={},A=gn(!0)){let t=null,r=-1,i=e.trustedCerts||[];if(!this.certs)throw Error("No certificates attached to the BasicOCSPResponse");switch(!0){case this.tbsResponseData.responderID instanceof d3:for(let[e,A]of this.certs.entries())if(A.subject.isEqual(this.tbsResponseData.responderID)){r=e;break}break;case this.tbsResponseData.responderID instanceof Aj:for(let[e,t]of this.certs.entries())if(AA(await A.digest({name:"sha-1"},t.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView),this.tbsResponseData.responderID.valueBlock.valueHex)){r=e;break}break;default:throw Error("Wrong value for responderID")}if(-1===r)throw Error("Correct certificate was not found in OCSP response");let n=[t=this.certs[r]];for(let e of this.certs){let A=await Ct(e,t);A&&n.push(A)}let a=new wE({certs:n,trustedCerts:i});if(!(await a.verify({},A)).result)throw Error("Validation of signer's certificate failed");return A.verifyWithPublicKey(this.tbsResponseData.tbsView,this.signature,this.certs[r].subjectPublicKeyInfo,this.signatureAlgorithm)}}wT.CLASS_NAME="BasicOCSPResponse";let wM="version",wN="subject",wO="subjectPublicKeyInfo",wH="attributes",wU="signatureAlgorithm",w_="signatureValue",wx="CertificationRequestInfo",wL=`${wx}.version`,wP=`${wx}.subject`,wq=`${wx}.subjectPublicKeyInfo`,wK=`${wx}.attributes`,wJ=[wx,wL,wP,wq,wK,wU,w_];class wF extends dX{get tbs(){return eV.toArrayBuffer(this.tbsView)}set tbs(e){this.tbsView=new Uint8Array(e)}constructor(e={}){super(),this.tbsView=new Uint8Array(e2(e,"tbs",wF.defaultValues("tbs"))),this.version=e2(e,wM,wF.defaultValues(wM)),this.subject=e2(e,wN,wF.defaultValues(wN)),this.subjectPublicKeyInfo=e2(e,wO,wF.defaultValues(wO)),wH in e&&(this.attributes=e2(e,wH,wF.defaultValues(wH))),this.signatureAlgorithm=e2(e,wU,wF.defaultValues(wU)),this.signatureValue=e2(e,w_,wF.defaultValues(w_)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case"tbs":return dZ;case wM:return 0;case wN:return new d3;case wO:return new hc;case wH:return[];case wU:return new uh;case w_:return new AY;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({value:[function(e={}){let A=e2(e,"names",{});return new A6({name:A.CertificationRequestInfo||wx,value:[new AW({name:A.CertificationRequestInfoVersion||wL}),d3.schema(A.subject||{names:{blockName:wP}}),hc.schema({names:{blockName:wq}}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new tQ({optional:!0,name:A.CertificationRequestInfoAttributes||wK,value:um.schema(A.attributes||{})})]})]})}(A.certificationRequestInfo||{}),new A6({name:A.signatureAlgorithm||wU,value:[new A1,new ty({optional:!0})]}),new AY({name:A.signatureValue||w_})]})}fromSchema(e){Ad(e,wJ);let A=tb(e,e,wF.schema());d$.assertSchema(A,this.className),this.tbsView=A.result.CertificationRequestInfo.valueBeforeDecodeView,this.version=A.result[wL].valueBlock.valueDec,this.subject=new d3({schema:A.result[wP]}),this.subjectPublicKeyInfo=new hc({schema:A.result[wq]}),wK in A.result&&(this.attributes=Array.from(A.result[wK],e=>new um({schema:e}))),this.signatureAlgorithm=new uh({schema:A.result.signatureAlgorithm}),this.signatureValue=A.result.signatureValue}encodeTBS(){let e=[new AW({value:this.version}),this.subject.toSchema(),this.subjectPublicKeyInfo.toSchema()];return wH in this&&e.push(new Ax({idBlock:{tagClass:3,tagNumber:0},value:Array.from(this.attributes||[],e=>e.toSchema())})),new A6({value:e})}toSchema(e=!1){let A;if(!1===e){if(0===this.tbsView.byteLength)return wF.schema();let e=AU(this.tbsView);d$.assert(e,"PKCS#10 Certificate Request"),A=e.result}else A=this.encodeTBS();return new A6({value:[A,this.signatureAlgorithm.toSchema(),this.signatureValue]})}toJSON(){let e={tbs:e4.ToHex(this.tbsView),version:this.version,subject:this.subject.toJSON(),subjectPublicKeyInfo:this.subjectPublicKeyInfo.toJSON(),signatureAlgorithm:this.signatureAlgorithm.toJSON(),signatureValue:this.signatureValue.toJSON()};return wH in this&&(e.attributes=Array.from(this.attributes||[],e=>e.toJSON())),e}async sign(e,A="SHA-1",t=gn(!0)){if(!e)throw Error("Need to provide a private key for signing");let r=await t.getSignatureParameters(e,A),i=r.parameters;this.signatureAlgorithm=r.signatureAlgorithm,this.tbsView=new Uint8Array(this.encodeTBS().toBER());let n=await t.signWithPrivateKey(this.tbsView,e,i);this.signatureValue=new AY({valueHex:n})}async verify(e=gn(!0)){return e.verifyWithPublicKey(this.tbsView,this.signatureValue,this.subjectPublicKeyInfo,this.signatureAlgorithm)}async getPublicKey(e,A=gn(!0)){return A.getPublicKey(this.subjectPublicKeyInfo,this.signatureAlgorithm,e)}}wF.CLASS_NAME="CertificationRequest";let wj="digestAlgorithm",wz="digest",wY=[wj,wz];class wZ extends dX{constructor(e={}){super(),this.digestAlgorithm=e2(e,wj,wZ.defaultValues(wj)),this.digest=e2(e,wz,wZ.defaultValues(wz)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case wj:return new uh;case wz:return new Aj;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case wj:return uh.compareWithDefault("algorithmId",A.algorithmId)&&"algorithmParams"in A==!1;case wz:return A.isEqual(wZ.defaultValues(e));default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[uh.schema(A.digestAlgorithm||{names:{blockName:wj}}),new Aj({name:A.digest||wz})]})}fromSchema(e){Ad(e,wY);let A=tb(e,e,wZ.schema({names:{digestAlgorithm:{names:{blockName:wj}},digest:wz}}));d$.assertSchema(A,this.className),this.digestAlgorithm=new uh({schema:A.result.digestAlgorithm}),this.digest=A.result.digest}toSchema(){return new A6({value:[this.digestAlgorithm.toSchema(),this.digest]})}toJSON(){return{digestAlgorithm:this.digestAlgorithm.toJSON(),digest:this.digest.toJSON()}}}wZ.CLASS_NAME="DigestInfo";let wV="eContentType",wW="eContent",w$=[wV,wW];class wX extends dX{constructor(e={}){if(super(),this.eContentType=e2(e,wV,wX.defaultValues(wV)),wW in e&&(this.eContent=e2(e,wW,wX.defaultValues(wW)),1===this.eContent.idBlock.tagClass&&4===this.eContent.idBlock.tagNumber&&!1===this.eContent.idBlock.isConstructed)){const e=new Aj({idBlock:{isConstructed:!0},isConstructed:!0});let A=0;const t=this.eContent.valueBlock.valueHexView.slice().buffer;let r=t.byteLength;for(;r>0;){const i=new Uint8Array(t,A,A+65536>t.byteLength?t.byteLength-A:65536),n=new ArrayBuffer(i.length),a=new Uint8Array(n);for(let e=0;e<a.length;e++)a[e]=i[e];e.valueBlock.value.push(new Aj({valueHex:n})),r-=i.length,A+=i.length}this.eContent=e}e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case wV:return"";case wW:return new Aj;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case wV:return""===A;case wW:if(1===A.idBlock.tagClass&&4===A.idBlock.tagNumber)return A.isEqual(wX.defaultValues(wW));return!1;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new A1({name:A.eContentType||""}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new ty({name:A.eContent||""})]})]})}fromSchema(e){Ad(e,w$);let A=tb(e,e,wX.schema({names:{eContentType:wV,eContent:wW}}));d$.assertSchema(A,this.className),this.eContentType=A.result.eContentType.valueBlock.toString(),wW in A.result&&(this.eContent=A.result.eContent)}toSchema(){let e=[];return e.push(new A1({value:this.eContentType})),this.eContent&&!1===wX.compareWithDefault(wW,this.eContent)&&e.push(new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[this.eContent]})),new A6({value:e})}toJSON(){let e={eContentType:this.eContentType};return this.eContent&&!1===wX.compareWithDefault(wW,this.eContent)&&(e.eContent=this.eContent.toJSON()),e}}wX.CLASS_NAME="EncapsulatedContentInfo";let w0="macSalt",w1="iterations",w8=["mac",w0,w1];class w4 extends dX{constructor(e={}){super(),this.mac=e2(e,"mac",w4.defaultValues("mac")),this.macSalt=e2(e,w0,w4.defaultValues(w0)),w1 in e&&(this.iterations=e2(e,w1,w4.defaultValues(w1))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case"mac":return new wZ;case w0:return new Aj;case w1:return 1;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case"mac":return wZ.compareWithDefault("digestAlgorithm",A.digestAlgorithm)&&wZ.compareWithDefault("digest",A.digest);case w0:return A.isEqual(w4.defaultValues(e));case w1:return A===w4.defaultValues(e);default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",optional:A.optional||!0,value:[wZ.schema(A.mac||{names:{blockName:"mac"}}),new Aj({name:A.macSalt||w0}),new AW({optional:!0,name:A.iterations||w1})]})}fromSchema(e){Ad(e,w8);let A=tb(e,e,w4.schema({names:{mac:{names:{blockName:"mac"}},macSalt:w0,iterations:w1}}));d$.assertSchema(A,this.className),this.mac=new wZ({schema:A.result.mac}),this.macSalt=A.result.macSalt,w1 in A.result&&(this.iterations=A.result.iterations.valueBlock.valueDec)}toSchema(){let e=[this.mac.toSchema(),this.macSalt];return void 0!==this.iterations&&e.push(new AW({value:this.iterations})),new A6({value:e})}toJSON(){let e={mac:this.mac.toJSON(),macSalt:this.macSalt.toJSON()};return void 0!==this.iterations&&(e.iterations=this.iterations),e}}w4.CLASS_NAME="MacData";let w2="hashAlgorithm",w6="hashedMessage",w3=[w2,w6];class w5 extends dX{static async create(e,A,t=gn(!0)){let r=t.getOIDByAlgorithm({name:e},!0,"hashAlgorithm"),i=await t.digest(e,A);return new w5({hashAlgorithm:new uh({algorithmId:r,algorithmParams:new Aq}),hashedMessage:new Aj({valueHex:i})})}constructor(e={}){super(),this.hashAlgorithm=e2(e,w2,w5.defaultValues(w2)),this.hashedMessage=e2(e,w6,w5.defaultValues(w6)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case w2:return new uh;case w6:return new Aj;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case w2:return""===A.algorithmId&&"algorithmParams"in A==!1;case w6:return 0===A.isEqual(w5.defaultValues(e));default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[uh.schema(A.hashAlgorithm||{}),new Aj({name:A.hashedMessage||""})]})}fromSchema(e){Ad(e,w3);let A=tb(e,e,w5.schema({names:{hashAlgorithm:{names:{blockName:w2}},hashedMessage:w6}}));d$.assertSchema(A,this.className),this.hashAlgorithm=new uh({schema:A.result.hashAlgorithm}),this.hashedMessage=A.result.hashedMessage}toSchema(){return new A6({value:[this.hashAlgorithm.toSchema(),this.hashedMessage]})}toJSON(){return{hashAlgorithm:this.hashAlgorithm.toJSON(),hashedMessage:this.hashedMessage.toJSON()}}}w5.CLASS_NAME="MessageImprint";let w9="reqCert",w7="singleRequestExtensions",me=[w9,w7];class mA extends dX{constructor(e={}){super(),this.reqCert=e2(e,w9,mA.defaultValues(w9)),w7 in e&&(this.singleRequestExtensions=e2(e,w7,mA.defaultValues(w7))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case w9:return new I8;case w7:return[];default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case w9:return A.isEqual(mA.defaultValues(e));case w7:return 0===A.length;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[I8.schema(A.reqCert||{}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[g_.schema(A.extensions||{names:{blockName:A.singleRequestExtensions||""}})]})]})}fromSchema(e){Ad(e,me);let A=tb(e,e,mA.schema({names:{reqCert:{names:{blockName:w9}},extensions:{names:{blockName:w7}}}}));d$.assertSchema(A,this.className),this.reqCert=new I8({schema:A.result.reqCert}),w7 in A.result&&(this.singleRequestExtensions=Array.from(A.result.singleRequestExtensions.valueBlock.value,e=>new gO({schema:e})))}toSchema(){let e=[];return e.push(this.reqCert.toSchema()),this.singleRequestExtensions&&e.push(new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new A6({value:Array.from(this.singleRequestExtensions,e=>e.toSchema())})]})),new A6({value:e})}toJSON(){let e={reqCert:this.reqCert.toJSON()};return this.singleRequestExtensions&&(e.singleRequestExtensions=Array.from(this.singleRequestExtensions,e=>e.toJSON())),e}}mA.CLASS_NAME="Request";let mt="version",mr="requestorName",mi="requestList",mn="requestExtensions",ma="TBSRequest",mo=`${ma}.${mt}`,ms=`${ma}.${mr}`,ml=`${ma}.requests`,md=`${ma}.${mn}`,mu=[ma,mo,ms,ml,md];class mc extends dX{get tbs(){return eV.toArrayBuffer(this.tbsView)}set tbs(e){this.tbsView=new Uint8Array(e)}constructor(e={}){super(),this.tbsView=new Uint8Array(e2(e,"tbs",mc.defaultValues("tbs"))),mt in e&&(this.version=e2(e,mt,mc.defaultValues(mt))),mr in e&&(this.requestorName=e2(e,mr,mc.defaultValues(mr))),this.requestList=e2(e,mi,mc.defaultValues(mi)),mn in e&&(this.requestExtensions=e2(e,mn,mc.defaultValues(mn))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case"tbs":return dZ;case mt:return 0;case mr:return new d7;case mi:case mn:return[];default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case"tbs":return 0===A.byteLength;case mt:return A===mc.defaultValues(e);case mr:return A.type===d7.defaultValues("type")&&0===Object.keys(A.value).length;case mi:case mn:return 0===A.length;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||ma,value:[new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new AW({name:A.TBSRequestVersion||mo})]}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[d7.schema(A.requestorName||{names:{blockName:ms}})]}),new A6({name:A.requestList||"TBSRequest.requestList",value:[new tQ({name:A.requests||ml,value:mA.schema(A.requestNames||{})})]}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:2},value:[g_.schema(A.extensions||{names:{blockName:A.requestExtensions||md}})]})]})}fromSchema(e){Ad(e,mu);let A=tb(e,e,mc.schema());d$.assertSchema(A,this.className),this.tbsView=A.result.TBSRequest.valueBeforeDecodeView,mo in A.result&&(this.version=A.result[mo].valueBlock.valueDec),ms in A.result&&(this.requestorName=new d7({schema:A.result[ms]})),this.requestList=Array.from(A.result[ml],e=>new mA({schema:e})),md in A.result&&(this.requestExtensions=Array.from(A.result[md].valueBlock.value,e=>new gO({schema:e})))}toSchema(e=!1){let A;if(!1===e){if(0===this.tbsView.byteLength)return mc.schema();let e=AU(this.tbsView);if(d$.assert(e,"TBS Request"),!(e.result instanceof A6))throw Error("ASN.1 result should be SEQUENCE");A=e.result}else{let e=[];void 0!==this.version&&e.push(new Ax({idBlock:{tagClass:3,tagNumber:0},value:[new AW({value:this.version})]})),this.requestorName&&e.push(new Ax({idBlock:{tagClass:3,tagNumber:1},value:[this.requestorName.toSchema()]})),e.push(new A6({value:Array.from(this.requestList,e=>e.toSchema())})),this.requestExtensions&&e.push(new Ax({idBlock:{tagClass:3,tagNumber:2},value:[new A6({value:Array.from(this.requestExtensions,e=>e.toSchema())})]})),A=new A6({value:e})}return A}toJSON(){let e={};return void 0!=this.version&&(e.version=this.version),this.requestorName&&(e.requestorName=this.requestorName.toJSON()),e.requestList=Array.from(this.requestList,e=>e.toJSON()),this.requestExtensions&&(e.requestExtensions=Array.from(this.requestExtensions,e=>e.toJSON())),e}}mc.CLASS_NAME="TBSRequest";let mh="signatureAlgorithm",mg="signature",mp="certs";class mC extends dX{constructor(e={}){super(),this.signatureAlgorithm=e2(e,mh,mC.defaultValues(mh)),this.signature=e2(e,mg,mC.defaultValues(mg)),mp in e&&(this.certs=e2(e,mp,mC.defaultValues(mp))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case mh:return new uh;case mg:return new AY;case mp:return[];default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case mh:return""===A.algorithmId&&"algorithmParams"in A==!1;case mg:return A.isEqual(mC.defaultValues(e));case mp:return 0===A.length;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[uh.schema(A.signatureAlgorithm||{}),new AY({name:A.signature||""}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new A6({value:[new tQ({name:A.certs||"",value:CA.schema({})})]})]})]})}fromSchema(e){Ad(e,[mh,mg,mp]);let A=tb(e,e,mC.schema({names:{signatureAlgorithm:{names:{blockName:mh}},signature:mg,certs:mp}}));d$.assertSchema(A,this.className),this.signatureAlgorithm=new uh({schema:A.result.signatureAlgorithm}),this.signature=A.result.signature,mp in A.result&&(this.certs=Array.from(A.result.certs,e=>new CA({schema:e})))}toSchema(){let e=[];return e.push(this.signatureAlgorithm.toSchema()),e.push(this.signature),this.certs&&e.push(new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new A6({value:Array.from(this.certs,e=>e.toSchema())})]})),new A6({value:e})}toJSON(){let e={signatureAlgorithm:this.signatureAlgorithm.toJSON(),signature:this.signature.toJSON()};return this.certs&&(e.certs=Array.from(this.certs,e=>e.toJSON())),e}}mC.CLASS_NAME="Signature";let mf="tbsRequest",mI="optionalSignature",mw=[mf,mI];class mm extends dX{constructor(e={}){super(),this.tbsRequest=e2(e,mf,mm.defaultValues(mf)),mI in e&&(this.optionalSignature=e2(e,mI,mm.defaultValues(mI))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case mf:return new mc;case mI:return new mC;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case mf:return mc.compareWithDefault("tbs",A.tbs)&&mc.compareWithDefault("version",A.version)&&mc.compareWithDefault("requestorName",A.requestorName)&&mc.compareWithDefault("requestList",A.requestList)&&mc.compareWithDefault("requestExtensions",A.requestExtensions);case mI:return mC.compareWithDefault("signatureAlgorithm",A.signatureAlgorithm)&&mC.compareWithDefault("signature",A.signature)&&mC.compareWithDefault("certs",A.certs);default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"OCSPRequest",value:[mc.schema(A.tbsRequest||{names:{blockName:mf}}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[mC.schema(A.optionalSignature||{names:{blockName:mI}})]})]})}fromSchema(e){Ad(e,mw);let A=tb(e,e,mm.schema());d$.assertSchema(A,this.className),this.tbsRequest=new mc({schema:A.result.tbsRequest}),mI in A.result&&(this.optionalSignature=new mC({schema:A.result.optionalSignature}))}toSchema(e=!1){let A=[];return A.push(this.tbsRequest.toSchema(e)),this.optionalSignature&&A.push(new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[this.optionalSignature.toSchema()]})),new A6({value:A})}toJSON(){let e={tbsRequest:this.tbsRequest.toJSON()};return this.optionalSignature&&(e.optionalSignature=this.optionalSignature.toJSON()),e}async createForCertificate(e,A,t=gn(!0)){let r=new I8;await r.createForCertificate(e,A,t),this.tbsRequest.requestList.push(new mA({reqCert:r}))}async sign(e,A="SHA-1",t=gn(!0)){if(dW.assertEmpty(e,"privateKey","OCSPRequest.sign method"),!this.optionalSignature)throw Error('Need to create "optionalSignature" field before signing');let r=await t.getSignatureParameters(e,A),i=r.parameters;this.optionalSignature.signatureAlgorithm=r.signatureAlgorithm;let n=this.tbsRequest.toSchema(!0).toBER(!1),a=await t.signWithPrivateKey(n,e,i);this.optionalSignature.signature=new AY({valueHex:a})}verify(){}}mm.CLASS_NAME="OCSPRequest";let mE="responseType",my="response",mB=[mE,my];class mQ extends dX{constructor(e={}){super(),this.responseType=e2(e,mE,mQ.defaultValues(mE)),this.response=e2(e,my,mQ.defaultValues(my)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case mE:return"";case my:return new Aj;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case mE:return""===A;case my:return A.isEqual(mQ.defaultValues(e));default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new A1({name:A.responseType||""}),new Aj({name:A.response||""})]})}fromSchema(e){Ad(e,mB);let A=tb(e,e,mQ.schema({names:{responseType:mE,response:my}}));d$.assertSchema(A,this.className),this.responseType=A.result.responseType.valueBlock.toString(),this.response=A.result.response}toSchema(){return new A6({value:[new A1({value:this.responseType}),this.response]})}toJSON(){return{responseType:this.responseType,response:this.response.toJSON()}}}mQ.CLASS_NAME="ResponseBytes";let mD="responseStatus",mb="responseBytes";class mS extends dX{constructor(e={}){super(),this.responseStatus=e2(e,mD,mS.defaultValues(mD)),mb in e&&(this.responseBytes=e2(e,mb,mS.defaultValues(mb))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case mD:return new A$;case mb:return new mQ;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case mD:return A.isEqual(mS.defaultValues(e));case mb:return mQ.compareWithDefault("responseType",A.responseType)&&mQ.compareWithDefault("response",A.response);default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"OCSPResponse",value:[new A$({name:A.responseStatus||mD}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[mQ.schema(A.responseBytes||{names:{blockName:mb}})]})]})}fromSchema(e){Ad(e,[mD,mb]);let A=tb(e,e,mS.schema());d$.assertSchema(A,this.className),this.responseStatus=A.result.responseStatus,mb in A.result&&(this.responseBytes=new mQ({schema:A.result.responseBytes}))}toSchema(){let e=[];return e.push(this.responseStatus),this.responseBytes&&e.push(new Ax({idBlock:{tagClass:3,tagNumber:0},value:[this.responseBytes.toSchema()]})),new A6({value:e})}toJSON(){let e={responseStatus:this.responseStatus.toJSON()};return this.responseBytes&&(e.responseBytes=this.responseBytes.toJSON()),e}async getCertificateStatus(e,A,t=gn(!0)){let r,i={isForCertificate:!1,status:2};if(!this.responseBytes||this.responseBytes.responseType!==uZ)return i;try{let e=AU(this.responseBytes.response.valueBlock.valueHexView);d$.assert(e,"Basic OCSP response"),r=new wT({schema:e.result})}catch{return i}return r.getCertificateStatus(e,A,t)}async sign(e,A,t=gn(!0)){var r;if(this.responseBytes&&this.responseBytes.responseType===uZ)return wT.fromBER(this.responseBytes.response.valueBlock.valueHexView).sign(e,A,t);throw Error(`Unknown ResponseBytes type: ${(null==(r=this.responseBytes)?void 0:r.responseType)||"Unknown"}`)}async verify(e=null,A=gn(!0)){var t;if(mb in this==!1)throw Error("Empty ResponseBytes field");if(this.responseBytes&&this.responseBytes.responseType===uZ){let t=wT.fromBER(this.responseBytes.response.valueBlock.valueHexView);return null!==e&&(t.certs||(t.certs=[]),t.certs.push(e)),t.verify({},A)}throw Error(`Unknown ResponseBytes type: ${(null==(t=this.responseBytes)?void 0:t.responseType)||"Unknown"}`)}}mS.CLASS_NAME="OCSPResponse";let mk="type",mR="attributes",mv="encodedValue",mG=[mR];class mT extends dX{constructor(e={}){super(),this.type=e2(e,mk,mT.defaultValues(mk)),this.attributes=e2(e,mR,mT.defaultValues(mR)),this.encodedValue=e2(e,mv,mT.defaultValues(mv)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case mk:return -1;case mR:return[];case mv:return dZ;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case mk:return A===mT.defaultValues(mk);case mR:return 0===A.length;case mv:return 0===A.byteLength;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new Ax({name:A.blockName||"",optional:!0,idBlock:{tagClass:3,tagNumber:A.tagNumber||0},value:[new tQ({name:A.attributes||"",value:um.schema()})]})}fromSchema(e){Ad(e,mG);let A=tb(e,e,mT.schema({names:{tagNumber:this.type,attributes:mR}}));if(d$.assertSchema(A,this.className),this.type=A.result.idBlock.tagNumber,this.encodedValue=eV.toArrayBuffer(A.result.valueBeforeDecodeView),new Uint8Array(this.encodedValue)[0]=49,mR in A.result==!1)if(0!==this.type)return;else throw Error("Wrong structure of SignedUnsignedAttributes");this.attributes=Array.from(A.result.attributes,e=>new um({schema:e}))}toSchema(){if(mT.compareWithDefault(mk,this.type)||mT.compareWithDefault(mR,this.attributes))throw Error('Incorrectly initialized "SignedAndUnsignedAttributes" class');return new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:this.type},value:Array.from(this.attributes,e=>e.toSchema())})}toJSON(){if(mT.compareWithDefault(mk,this.type)||mT.compareWithDefault(mR,this.attributes))throw Error('Incorrectly initialized "SignedAndUnsignedAttributes" class');return{type:this.type,attributes:Array.from(this.attributes,e=>e.toJSON())}}}mT.CLASS_NAME="SignedAndUnsignedAttributes";let mM="version",mN="digestAlgorithm",mO="signedAttrs",mH="signatureAlgorithm",mU="signature",m_="unsignedAttrs",mx="SignerInfo",mL=`${mx}.${mM}`,mP=`${mx}.sid`,mq=`${mx}.${mN}`,mK=`${mx}.${mO}`,mJ=`${mx}.${mH}`,mF=`${mx}.${mU}`,mj=`${mx}.${m_}`,mz=[mL,mP,mq,mK,mJ,mF,mj];class mY extends dX{constructor(e={}){super(),this.version=e2(e,mM,mY.defaultValues(mM)),this.sid=e2(e,"sid",mY.defaultValues("sid")),this.digestAlgorithm=e2(e,mN,mY.defaultValues(mN)),mO in e&&(this.signedAttrs=e2(e,mO,mY.defaultValues(mO))),this.signatureAlgorithm=e2(e,mH,mY.defaultValues(mH)),this.signature=e2(e,mU,mY.defaultValues(mU)),m_ in e&&(this.unsignedAttrs=e2(e,m_,mY.defaultValues(m_))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case mM:return 0;case"sid":return new ty;case mN:return new uh;case mO:return new mT({type:0});case mH:return new uh;case mU:return new Aj;case m_:return new mT({type:1});default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case mM:return mY.defaultValues(mM)===A;case"sid":return A instanceof ty;case mN:if(A instanceof uh==!1)return!1;return A.isEqual(mY.defaultValues(mN));case mO:return mT.compareWithDefault("type",A.type)&&mT.compareWithDefault("attributes",A.attributes)&&mT.compareWithDefault("encodedValue",A.encodedValue);case mH:if(A instanceof uh==!1)return!1;return A.isEqual(mY.defaultValues(mH));case mU:case m_:return mT.compareWithDefault("type",A.type)&&mT.compareWithDefault("attributes",A.attributes)&&mT.compareWithDefault("encodedValue",A.encodedValue);default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:mx,value:[new AW({name:A.version||mL}),new tB({value:[fI.schema(A.sidSchema||{names:{blockName:mP}}),new tB({value:[new Ax({optional:!0,name:A.sid||mP,idBlock:{tagClass:3,tagNumber:0},value:[new Aj]}),new AM({optional:!0,name:A.sid||mP,idBlock:{tagClass:3,tagNumber:0}})]})]}),uh.schema(A.digestAlgorithm||{names:{blockName:mq}}),mT.schema(A.signedAttrs||{names:{blockName:mK,tagNumber:0}}),uh.schema(A.signatureAlgorithm||{names:{blockName:mJ}}),new Aj({name:A.signature||mF}),mT.schema(A.unsignedAttrs||{names:{blockName:mj,tagNumber:1}})]})}fromSchema(e){Ad(e,mz);let A=tb(e,e,mY.schema());d$.assertSchema(A,this.className),this.version=A.result[mL].valueBlock.valueDec;let t=A.result[mP];1===t.idBlock.tagClass?this.sid=new fI({schema:t}):this.sid=t,this.digestAlgorithm=new uh({schema:A.result[mq]}),mK in A.result&&(this.signedAttrs=new mT({type:0,schema:A.result[mK]})),this.signatureAlgorithm=new uh({schema:A.result[mJ]}),this.signature=A.result[mF],mj in A.result&&(this.unsignedAttrs=new mT({type:1,schema:A.result[mj]}))}toSchema(){if(mY.compareWithDefault("sid",this.sid))throw Error('Incorrectly initialized "SignerInfo" class');let e=[];return e.push(new AW({value:this.version})),this.sid instanceof fI?e.push(this.sid.toSchema()):e.push(this.sid),e.push(this.digestAlgorithm.toSchema()),this.signedAttrs&&!1===mY.compareWithDefault(mO,this.signedAttrs)&&e.push(this.signedAttrs.toSchema()),e.push(this.signatureAlgorithm.toSchema()),e.push(this.signature),this.unsignedAttrs&&!1===mY.compareWithDefault(m_,this.unsignedAttrs)&&e.push(this.unsignedAttrs.toSchema()),new A6({value:e})}toJSON(){if(mY.compareWithDefault("sid",this.sid))throw Error('Incorrectly initialized "SignerInfo" class');let e={version:this.version,digestAlgorithm:this.digestAlgorithm.toJSON(),signatureAlgorithm:this.signatureAlgorithm.toJSON(),signature:this.signature.toJSON()};return this.sid instanceof ty||(e.sid=this.sid.toJSON()),this.signedAttrs&&!1===mY.compareWithDefault(mO,this.signedAttrs)&&(e.signedAttrs=this.signedAttrs.toJSON()),this.unsignedAttrs&&!1===mY.compareWithDefault(m_,this.unsignedAttrs)&&(e.unsignedAttrs=this.unsignedAttrs.toJSON()),e}}mY.CLASS_NAME="SignerInfo";let mZ="version",mV="policy",mW="messageImprint",m$="serialNumber",mX="genTime",m0="ordering",m1="nonce",m8="accuracy",m4="extensions",m2="TSTInfo",m6=`${m2}.${mZ}`,m3=`${m2}.${mV}`,m5=`${m2}.${mW}`,m9=`${m2}.${m$}`,m7=`${m2}.${mX}`,Ee=`${m2}.${m8}`,EA=`${m2}.${m0}`,Et=`${m2}.${m1}`,Er=`${m2}.tsa`,Ei=`${m2}.${m4}`,En=[m6,m3,m5,m9,m7,Ee,EA,Et,Er,Ei];class Ea extends dX{constructor(e={}){super(),this.version=e2(e,mZ,Ea.defaultValues(mZ)),this.policy=e2(e,mV,Ea.defaultValues(mV)),this.messageImprint=e2(e,mW,Ea.defaultValues(mW)),this.serialNumber=e2(e,m$,Ea.defaultValues(m$)),this.genTime=e2(e,mX,Ea.defaultValues(mX)),m8 in e&&(this.accuracy=e2(e,m8,Ea.defaultValues(m8))),m0 in e&&(this.ordering=e2(e,m0,Ea.defaultValues(m0))),m1 in e&&(this.nonce=e2(e,m1,Ea.defaultValues(m1))),"tsa"in e&&(this.tsa=e2(e,"tsa",Ea.defaultValues("tsa"))),m4 in e&&(this.extensions=e2(e,m4,Ea.defaultValues(m4))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case mZ:return 0;case mV:return"";case mW:return new w5;case m$:return new AW;case mX:return new Date(0,0,0);case m8:return new uo;case m0:return!1;case m1:return new AW;case"tsa":return new d7;case m4:return[];default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case mZ:case mV:case mX:case m0:return A===Ea.defaultValues(m0);case mW:return w5.compareWithDefault(w2,A.hashAlgorithm)&&w5.compareWithDefault(w6,A.hashedMessage);case m$:case m1:return A.isEqual(Ea.defaultValues(m1));case m8:return uo.compareWithDefault(ui,A.seconds)&&uo.compareWithDefault(un,A.millis)&&uo.compareWithDefault(ua,A.micros);case"tsa":return d7.compareWithDefault(d5,A.type)&&d7.compareWithDefault(d9,A.value);case m4:return 0===A.length;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||m2,value:[new AW({name:A.version||m6}),new A1({name:A.policy||m3}),w5.schema(A.messageImprint||{names:{blockName:m5}}),new AW({name:A.serialNumber||m9}),new tC({name:A.genTime||m7}),uo.schema(A.accuracy||{names:{blockName:Ee}}),new AJ({name:A.ordering||EA,optional:!0}),new AW({name:A.nonce||Et,optional:!0}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[d7.schema(A.tsa||{names:{blockName:Er}})]}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:[new tQ({name:A.extensions||Ei,value:gO.schema(A.extension||{})})]})]})}fromSchema(e){Ad(e,En);let A=tb(e,e,Ea.schema());d$.assertSchema(A,this.className),this.version=A.result[m6].valueBlock.valueDec,this.policy=A.result[m3].valueBlock.toString(),this.messageImprint=new w5({schema:A.result[m5]}),this.serialNumber=A.result[m9],this.genTime=A.result[m7].toDate(),Ee in A.result&&(this.accuracy=new uo({schema:A.result[Ee]})),EA in A.result&&(this.ordering=A.result[EA].valueBlock.value),Et in A.result&&(this.nonce=A.result[Et]),Er in A.result&&(this.tsa=new d7({schema:A.result[Er]})),Ei in A.result&&(this.extensions=Array.from(A.result[Ei],e=>new gO({schema:e})))}toSchema(){let e=[];return e.push(new AW({value:this.version})),e.push(new A1({value:this.policy})),e.push(this.messageImprint.toSchema()),e.push(this.serialNumber),e.push(new tC({valueDate:this.genTime})),this.accuracy&&e.push(this.accuracy.toSchema()),void 0!==this.ordering&&e.push(new AJ({value:this.ordering})),this.nonce&&e.push(this.nonce),this.tsa&&e.push(new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[this.tsa.toSchema()]})),this.extensions&&e.push(new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:Array.from(this.extensions,e=>e.toSchema())})),new A6({value:e})}toJSON(){let e={version:this.version,policy:this.policy,messageImprint:this.messageImprint.toJSON(),serialNumber:this.serialNumber.toJSON(),genTime:this.genTime};return this.accuracy&&(e.accuracy=this.accuracy.toJSON()),void 0!==this.ordering&&(e.ordering=this.ordering),this.nonce&&(e.nonce=this.nonce.toJSON()),this.tsa&&(e.tsa=this.tsa.toJSON()),this.extensions&&(e.extensions=Array.from(this.extensions,e=>e.toJSON())),e}async verify(e,A=gn(!0)){if(!e.data)throw Error('"data" is a mandatory attribute for TST_INFO verification');let t=e.data;if(e.notBefore&&this.genTime<e.notBefore)throw Error("Generation time for TSTInfo object is less than notBefore value");if(e.notAfter&&this.genTime>e.notAfter)throw Error("Generation time for TSTInfo object is more than notAfter value");let r=A.getAlgorithmByOID(this.messageImprint.hashAlgorithm.algorithmId,!0,"MessageImprint.hashAlgorithm"),i=await A.digest(r.name,new Uint8Array(t));return eV.isEqual(i,this.messageImprint.hashedMessage.valueBlock.valueHexView)}}Ea.CLASS_NAME="TSTInfo";let Eo="version",Es="digestAlgorithms",El="encapContentInfo",Ed="certificates",Eu="crls",Ec="signerInfos",Eh="ocsps",Eg="SignedData",Ep=`${Eg}.${Eo}`,EC=`${Eg}.${Es}`,Ef=`${Eg}.${El}`,EI=`${Eg}.${Ed}`,Ew=`${Eg}.${Eu}`,Em=`${Eg}.${Ec}`,EE=[Ep,EC,Ef,EI,Ew,Em];class Ey extends Error{constructor({message:e,code:A=0,date:t=new Date,signatureVerified:r=null,signerCertificate:i=null,signerCertificateVerified:n=null,timestampSerial:a=null,certificatePath:o=[]}){super(e),this.name="SignedDataVerifyError",this.date=t,this.code=A,this.timestampSerial=a,this.signatureVerified=r,this.signerCertificate=i,this.signerCertificateVerified=n,this.certificatePath=o}}class EB extends dX{constructor(e={}){super(),this.version=e2(e,Eo,EB.defaultValues(Eo)),this.digestAlgorithms=e2(e,Es,EB.defaultValues(Es)),this.encapContentInfo=e2(e,El,EB.defaultValues(El)),Ed in e&&(this.certificates=e2(e,Ed,EB.defaultValues(Ed))),Eu in e&&(this.crls=e2(e,Eu,EB.defaultValues(Eu))),Eh in e&&(this.ocsps=e2(e,Eh,EB.defaultValues(Eh))),this.signerInfos=e2(e,Ec,EB.defaultValues(Ec)),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Eo:return 0;case Es:return[];case El:return new wX;case Ed:case Eu:case Eh:case Ec:return[];default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case Eo:return A===EB.defaultValues(Eo);case El:return wX.compareWithDefault("eContentType",A.eContentType)&&wX.compareWithDefault("eContent",A.eContent);case Es:case Ed:case Eu:case Eh:case Ec:return 0===A.length;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return void 0===A.optional&&(A.optional=!1),new A6({name:A.blockName||Eg,optional:A.optional,value:[new AW({name:A.version||Ep}),new A3({value:[new tQ({name:A.digestAlgorithms||EC,value:uh.schema()})]}),wX.schema(A.encapContentInfo||{names:{blockName:Ef}}),new Ax({name:A.certificates||EI,optional:!0,idBlock:{tagClass:3,tagNumber:0},value:ft.schema().valueBlock.value}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:1},value:fd.schema(A.crls||{names:{crls:Ew}}).valueBlock.value}),new A3({value:[new tQ({name:A.signerInfos||Em,value:mY.schema()})]})]})}fromSchema(e){Ad(e,EE);let A=tb(e,e,EB.schema());if(d$.assertSchema(A,this.className),this.version=A.result[Ep].valueBlock.valueDec,EC in A.result&&(this.digestAlgorithms=Array.from(A.result[EC],e=>new uh({schema:e}))),this.encapContentInfo=new wX({schema:A.result[Ef]}),EI in A.result){let e=new ft({schema:new A3({value:A.result[EI].valueBlock.value})});this.certificates=e.certificates.slice(0)}Ew in A.result&&(this.crls=Array.from(A.result[Ew],e=>1===e.idBlock.tagClass?new CT({schema:e}):(e.idBlock.tagClass=1,e.idBlock.tagNumber=16,new fa({schema:e})))),Em in A.result&&(this.signerInfos=Array.from(A.result[Em],e=>new mY({schema:e})))}toSchema(e=!1){let A=[];if(this.certificates&&this.certificates.length&&this.certificates.some(e=>e instanceof C7)||this.crls&&this.crls.length&&this.crls.some(e=>e instanceof fa)?this.version=5:this.certificates&&this.certificates.length&&this.certificates.some(e=>e instanceof pk)?this.version=4:this.certificates&&this.certificates.length&&this.certificates.some(e=>e instanceof g3)||this.signerInfos.some(e=>3===e.version)||this.encapContentInfo.eContentType!==EB.ID_DATA?this.version=3:this.version=1,A.push(new AW({value:this.version})),A.push(new A3({value:Array.from(this.digestAlgorithms,e=>e.toSchema())})),A.push(this.encapContentInfo.toSchema()),this.certificates){let e=new ft({certificates:this.certificates}).toSchema();A.push(new Ax({idBlock:{tagClass:3,tagNumber:0},value:e.valueBlock.value}))}return this.crls&&A.push(new Ax({idBlock:{tagClass:3,tagNumber:1},value:Array.from(this.crls,A=>{if(A instanceof fa){let e=A.toSchema();return e.idBlock.tagClass=3,e.idBlock.tagNumber=1,e}return A.toSchema(e)})})),A.push(new A3({value:Array.from(this.signerInfos,e=>e.toSchema())})),new A6({value:A})}toJSON(){let e={version:this.version,digestAlgorithms:Array.from(this.digestAlgorithms,e=>e.toJSON()),encapContentInfo:this.encapContentInfo.toJSON(),signerInfos:Array.from(this.signerInfos,e=>e.toJSON())};return this.certificates&&(e.certificates=Array.from(this.certificates,e=>e.toJSON())),this.crls&&(e.crls=Array.from(this.crls,e=>e.toJSON())),e}async verify({signer:e=-1,data:A=dZ,trustedCerts:t=[],checkDate:r=new Date,checkChain:i=!1,passedWhenNotRevValues:n=!1,extendedMode:a=!1,findOrigin:o=null,findIssuer:s=null}={},l=gn(!0)){let d=null,u=null;try{let c=dZ,h="",g=[],p=this.signerInfos[e];if(!p)throw new Ey({date:r,code:1,message:"Unable to get signer by supplied index"});if(!this.certificates)throw new Ey({date:r,code:2,message:"No certificates attached to this signed data"});if(p.sid instanceof fI){for(let e of this.certificates)if(e instanceof CA&&e.issuer.isEqual(p.sid.issuer)&&e.serialNumber.isEqual(p.sid.serialNumber)){d=e;break}}else{let e=p.sid,A=e.idBlock.isConstructed?e.valueBlock.value[0].valueBlock.valueHex:e.valueBlock.valueHex;for(let e of this.certificates){if(!(e instanceof CA))continue;let t=await l.digest({name:"sha-1"},e.subjectPublicKeyInfo.subjectPublicKey.valueBlock.valueHexView);if(AA(t,A)){d=e;break}}}if(!d)throw new Ey({date:r,code:3,message:"Unable to find signer certificate"});if("1.2.840.113549.1.9.16.1.4"===this.encapContentInfo.eContentType){let e;if(!this.encapContentInfo.eContent)throw new Ey({date:r,code:15,message:"Error during verification: TSTInfo eContent is empty",signatureVerified:null,signerCertificate:d,timestampSerial:u,signerCertificateVerified:!0});try{e=Ea.fromBER(this.encapContentInfo.eContent.valueBlock.valueHexView)}catch{throw new Ey({date:r,code:15,message:"Error during verification: TSTInfo wrong ASN.1 schema ",signatureVerified:null,signerCertificate:d,timestampSerial:u,signerCertificateVerified:!0})}if(r=e.genTime,u=e.serialNumber.valueBlock.valueHexView.slice().buffer,0===A.byteLength)throw new Ey({date:r,code:4,message:"Missed detached data input array"});if(!await e.verify({data:A},l))throw new Ey({date:r,code:15,message:"Error during verification: TSTInfo verification is failed",signatureVerified:!1,signerCertificate:d,timestampSerial:u,signerCertificateVerified:!0})}if(i){let e=this.certificates.filter(e=>e instanceof CA&&!!Ct(e,d)),A={checkDate:r,certs:e,trustedCerts:t};s&&(A.findIssuer=s),o&&(A.findOrigin=o);let i=new wE(A);if(i.certs.push(d),this.crls)for(let e of this.crls)"thisUpdate"in e?i.crls.push(e):e.otherRevInfoFormat===uZ&&i.ocsps.push(new wT({schema:e.otherRevInfo}));this.ocsps&&i.ocsps.push(...this.ocsps);let a=await i.verify({passedWhenNotRevValues:n},l).catch(e=>{throw new Ey({date:r,code:5,message:`Validation of signer's certificate failed with error: ${e instanceof Object?e.resultMessage:e}`,signerCertificate:d,signerCertificateVerified:!1})});if(a.certificatePath&&(g=a.certificatePath),!a.result)throw new Ey({date:r,code:5,message:`Validation of signer's certificate failed: ${a.resultMessage}`,signerCertificate:d,signerCertificateVerified:!1})}let C=l.getAlgorithmByOID(p.digestAlgorithm.algorithmId);if(!("name"in C))throw new Ey({date:r,code:7,message:`Unsupported signature algorithm: ${p.digestAlgorithm.algorithmId}`,signerCertificate:d,signerCertificateVerified:!0});h=C.name;let f=this.encapContentInfo.eContent;if(f)A=1===f.idBlock.tagClass&&4===f.idBlock.tagNumber?f.getValue():f.valueBlock.valueBeforeDecodeView.slice().buffer;else if(0===A.byteLength)throw new Ey({date:r,code:8,message:"Missed detached data input array",signerCertificate:d,signerCertificateVerified:!0});if(p.signedAttrs){let e=!1,A=!1;for(let t of p.signedAttrs.attributes)if("1.2.840.113549.1.9.3"===t.type&&(e=!0),"1.2.840.113549.1.9.4"===t.type&&(A=!0,c=t.values[0].valueBlock.valueHex),e&&A)break;if(!1===e)throw new Ey({date:r,code:9,message:'Attribute "content-type" is a mandatory attribute for "signed attributes"',signerCertificate:d,signerCertificateVerified:!0});if(!1===A)throw new Ey({date:r,code:10,message:'Attribute "message-digest" is a mandatory attribute for "signed attributes"',signatureVerified:null,signerCertificate:d,signerCertificateVerified:!0})}if(p.signedAttrs){let e=await l.digest(h,new Uint8Array(A));if(!AA(e,c))throw new Ey({date:r,code:15,message:"Error during verification: Message digest doesn't match",signatureVerified:null,signerCertificate:d,timestampSerial:u,signerCertificateVerified:!0});A=p.signedAttrs.encodedValue}let I="1.2.840.113549.1.1.1"===p.signatureAlgorithm.algorithmId?await l.verifyWithPublicKey(A,p.signature,d.subjectPublicKeyInfo,p.signatureAlgorithm,h):await l.verifyWithPublicKey(A,p.signature,d.subjectPublicKeyInfo,p.signatureAlgorithm);if(a)return{date:r,code:14,message:"",signatureVerified:I,signerCertificate:d,timestampSerial:u,signerCertificateVerified:!0,certificatePath:g};return I}catch(e){if(e instanceof Ey)throw e;throw new Ey({date:r,code:15,message:`Error during verification: ${e instanceof Error?e.message:e}`,signatureVerified:null,signerCertificate:d,timestampSerial:u,signerCertificateVerified:!0})}}async sign(e,A,t="SHA-1",r=dZ,i=gn(!0)){var n;if(!e)throw Error("Need to provide a private key for signing");let a=this.signerInfos[A];if(!a)throw RangeError("SignerInfo index is out of range");!(null==(n=a.signedAttrs)?void 0:n.attributes.length)&&"hash"in e.algorithm&&"hash"in e.algorithm&&e.algorithm.hash&&(t=e.algorithm.hash.name);let o=i.getOIDByAlgorithm({name:t},!0,"hashAlgorithm");0===this.digestAlgorithms.filter(e=>e.algorithmId===o).length&&this.digestAlgorithms.push(new uh({algorithmId:o,algorithmParams:new Aq})),a.digestAlgorithm=new uh({algorithmId:o,algorithmParams:new Aq});let s=await i.getSignatureParameters(e,t),l=s.parameters;if(a.signatureAlgorithm=s.signatureAlgorithm,a.signedAttrs)0!==a.signedAttrs.encodedValue.byteLength?r=a.signedAttrs.encodedValue:(r=a.signedAttrs.toSchema().toBER(),eV.toUint8Array(r)[0]=49);else{let e=this.encapContentInfo.eContent;if(e)r=1===e.idBlock.tagClass&&4===e.idBlock.tagNumber?e.getValue():e.valueBlock.valueBeforeDecodeView.slice().buffer;else if(0===r.byteLength)throw Error("Missed detached data input array")}a.signature=new Aj({valueHex:await i.signWithPrivateKey(r,e,l)})}}EB.CLASS_NAME="SignedData",EB.ID_DATA=uq;let EQ="version",ED="authSafe",Eb="macData",ES="parsedValue",Ek=[EQ,ED,Eb];class ER extends dX{constructor(e={}){super(),this.version=e2(e,EQ,ER.defaultValues(EQ)),this.authSafe=e2(e,ED,ER.defaultValues(ED)),Eb in e&&(this.macData=e2(e,Eb,ER.defaultValues(Eb))),ES in e&&(this.parsedValue=e2(e,ES,ER.defaultValues(ES))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case EQ:return 3;case ED:return new pT;case Eb:return new w4;case ES:return{};default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case EQ:return A===ER.defaultValues(e);case ED:return pT.compareWithDefault("contentType",A.contentType)&&pT.compareWithDefault("content",A.content);case Eb:return w4.compareWithDefault("mac",A.mac)&&w4.compareWithDefault("macSalt",A.macSalt)&&w4.compareWithDefault("iterations",A.iterations);case ES:return A instanceof Object&&0===Object.keys(A).length;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new AW({name:A.version||EQ}),pT.schema(A.authSafe||{names:{blockName:ED}}),w4.schema(A.macData||{names:{blockName:Eb,optional:!0}})]})}fromSchema(e){Ad(e,Ek);let A=tb(e,e,ER.schema({names:{version:EQ,authSafe:{names:{blockName:ED}},macData:{names:{blockName:Eb}}}}));d$.assertSchema(A,this.className),this.version=A.result.version.valueBlock.valueDec,this.authSafe=new pT({schema:A.result.authSafe}),Eb in A.result&&(this.macData=new w4({schema:A.result.macData}))}toSchema(){let e=[new AW({value:this.version}),this.authSafe.toSchema()];return this.macData&&e.push(this.macData.toSchema()),new A6({value:e})}toJSON(){let e={version:this.version,authSafe:this.authSafe.toJSON()};return this.macData&&(e.macData=this.macData.toJSON()),e}async makeInternalValues(e={},A=gn(!0)){if(dV.assert(e,"parameters","object"),!this.parsedValue)throw Error('Please call "parseValues" function first in order to make "parsedValue" data');switch(dW.assertEmpty(this.parsedValue.integrityMode,"integrityMode","parsedValue"),dW.assertEmpty(this.parsedValue.authenticatedSafe,"authenticatedSafe","parsedValue"),this.parsedValue.integrityMode){case 0:{if(!("iterations"in e))throw new dW("iterations");dW.assertEmpty(e.pbkdf2HashAlgorithm,"pbkdf2HashAlgorithm"),dW.assertEmpty(e.hmacHashAlgorithm,"hmacHashAlgorithm"),dW.assertEmpty(e.password,"password");let t=new ArrayBuffer(64),r=new Uint8Array(t);A.getRandomValues(r);let i=this.parsedValue.authenticatedSafe.toSchema().toBER(!1);this.authSafe=new pT({contentType:pT.DATA,content:new Aj({valueHex:i})});let n=await A.stampDataWithPassword({password:e.password,hashAlgorithm:e.hmacHashAlgorithm,salt:t,iterationCount:e.iterations,contentToStamp:i});this.macData=new w4({mac:new wZ({digestAlgorithm:new uh({algorithmId:A.getOIDByAlgorithm({name:e.hmacHashAlgorithm},!0,"hmacHashAlgorithm")}),digest:new Aj({valueHex:n})}),macSalt:new Aj({valueHex:t}),iterations:e.iterations})}break;case 1:{if(!("signingCertificate"in e))throw new dW("signingCertificate");dW.assertEmpty(e.privateKey,"privateKey"),dW.assertEmpty(e.hashAlgorithm,"hashAlgorithm");let t=this.parsedValue.authenticatedSafe.toSchema().toBER(!1),r=new EB({version:1,encapContentInfo:new wX({eContentType:"1.2.840.113549.1.7.1",eContent:new Aj({valueHex:t})}),certificates:[e.signingCertificate]}),i=await A.digest({name:e.hashAlgorithm},new Uint8Array(t)),n=[];n.push(new um({type:"1.2.840.113549.1.9.3",values:[new A1({value:"1.2.840.113549.1.7.1"})]})),n.push(new um({type:"1.2.840.113549.1.9.5",values:[new tp({valueDate:new Date})]})),n.push(new um({type:"1.2.840.113549.1.9.4",values:[new Aj({valueHex:i})]})),r.signerInfos.push(new mY({version:1,sid:new fI({issuer:e.signingCertificate.issuer,serialNumber:e.signingCertificate.serialNumber}),signedAttrs:new mT({type:0,attributes:n})})),await r.sign(e.privateKey,0,e.hashAlgorithm,void 0,A),this.authSafe=new pT({contentType:"1.2.840.113549.1.7.2",content:r.toSchema(!0)})}break;default:throw Error(`Parameter "integrityMode" has unknown value: ${this.parsedValue.integrityMode}`)}}async parseInternalValues(e,A=gn(!0)){switch(dV.assert(e,"parameters","object"),void 0===e.checkIntegrity&&(e.checkIntegrity=!0),this.parsedValue={},this.authSafe.contentType){case pT.DATA:{dW.assertEmpty(e.password,"password"),this.parsedValue.integrityMode=0,dV.assert(this.authSafe.content,"authSafe.content",Aj);let t=this.authSafe.content.getValue();if(this.parsedValue.authenticatedSafe=IV.fromBER(t),e.checkIntegrity){if(!this.macData)throw Error('Absent "macData" value, can not check PKCS#12 data integrity');let r=A.getAlgorithmByOID(this.macData.mac.digestAlgorithm.algorithmId,!0,"digestAlgorithm");if(!await A.verifyDataStampedWithPassword({password:e.password,hashAlgorithm:r.name,salt:eV.toArrayBuffer(this.macData.macSalt.valueBlock.valueHexView),iterationCount:this.macData.iterations||1,contentToVerify:t,signatureToVerify:eV.toArrayBuffer(this.macData.mac.digest.valueBlock.valueHexView)}))throw Error("Integrity for the PKCS#12 data is broken!")}}break;case pT.SIGNED_DATA:{this.parsedValue.integrityMode=1;let e=new EB({schema:this.authSafe.content}),t=e.encapContentInfo.eContent;dW.assert(t,"eContent","cmsSigned.encapContentInfo"),dV.assert(t,"eContent",Aj);let r=t.getValue();if(this.parsedValue.authenticatedSafe=IV.fromBER(r),!await e.verify({signer:0,checkChain:!1},A))throw Error("Integrity for the PKCS#12 data is broken!")}break;default:throw Error(`Incorrect value for "this.authSafe.contentType": ${this.authSafe.contentType}`)}}}ER.CLASS_NAME="PFX";let Ev="status",EG="statusStrings",ET="failInfo",EM=[Ev,EG,ET];(E=eY||(eY={}))[E.granted=0]="granted",E[E.grantedWithMods=1]="grantedWithMods",E[E.rejection=2]="rejection",E[E.waiting=3]="waiting",E[E.revocationWarning=4]="revocationWarning",E[E.revocationNotification=5]="revocationNotification";class EN extends dX{constructor(e={}){super(),this.status=e2(e,Ev,EN.defaultValues(Ev)),EG in e&&(this.statusStrings=e2(e,EG,EN.defaultValues(EG))),ET in e&&(this.failInfo=e2(e,ET,EN.defaultValues(ET))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case Ev:return 2;case EG:return[];case ET:return new AY;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case Ev:return A===EN.defaultValues(e);case EG:return 0===A.length;case ET:return A.isEqual(EN.defaultValues(e));default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||"",value:[new AW({name:A.status||""}),new A6({optional:!0,value:[new tQ({name:A.statusStrings||"",value:new tA})]}),new AY({name:A.failInfo||"",optional:!0})]})}fromSchema(e){Ad(e,EM);let A=tb(e,e,EN.schema({names:{status:Ev,statusStrings:EG,failInfo:ET}}));d$.assertSchema(A,this.className);let t=A.result.status;if(!0===t.valueBlock.isHexOnly||t.valueBlock.valueDec<0||t.valueBlock.valueDec>5)throw Error('PKIStatusInfo "status" has invalid value');this.status=t.valueBlock.valueDec,EG in A.result&&(this.statusStrings=A.result.statusStrings),ET in A.result&&(this.failInfo=A.result.failInfo)}toSchema(){let e=[];return e.push(new AW({value:this.status})),this.statusStrings&&e.push(new A6({optional:!0,value:this.statusStrings})),this.failInfo&&e.push(this.failInfo),new A6({value:e})}toJSON(){let e={status:this.status};return this.statusStrings&&(e.statusStrings=Array.from(this.statusStrings,e=>e.toJSON())),this.failInfo&&(e.failInfo=this.failInfo.toJSON()),e}}EN.CLASS_NAME="PKIStatusInfo";let EO="version",EH="messageImprint",EU="reqPolicy",E_="nonce",Ex="certReq",EL="extensions",EP="TimeStampReq",Eq=`${EP}.${EO}`,EK=`${EP}.${EH}`,EJ=`${EP}.${EU}`,EF=`${EP}.${E_}`,Ej=`${EP}.${Ex}`,Ez=`${EP}.${EL}`,EY=[Eq,EK,EJ,EF,Ej,Ez];class EZ extends dX{constructor(e={}){super(),this.version=e2(e,EO,EZ.defaultValues(EO)),this.messageImprint=e2(e,EH,EZ.defaultValues(EH)),EU in e&&(this.reqPolicy=e2(e,EU,EZ.defaultValues(EU))),E_ in e&&(this.nonce=e2(e,E_,EZ.defaultValues(E_))),Ex in e&&(this.certReq=e2(e,Ex,EZ.defaultValues(Ex))),EL in e&&(this.extensions=e2(e,EL,EZ.defaultValues(EL))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case EO:return 0;case EH:return new w5;case EU:return"";case E_:return new AW;case Ex:return!1;case EL:return[];default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case EO:case EU:case Ex:return A===EZ.defaultValues(e);case EH:return w5.compareWithDefault("hashAlgorithm",A.hashAlgorithm)&&w5.compareWithDefault("hashedMessage",A.hashedMessage);case E_:return A.isEqual(EZ.defaultValues(e));case EL:return 0===A.length;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||EP,value:[new AW({name:A.version||Eq}),w5.schema(A.messageImprint||{names:{blockName:EK}}),new A1({name:A.reqPolicy||EJ,optional:!0}),new AW({name:A.nonce||EF,optional:!0}),new AJ({name:A.certReq||Ej,optional:!0}),new Ax({optional:!0,idBlock:{tagClass:3,tagNumber:0},value:[new tQ({name:A.extensions||Ez,value:gO.schema()})]})]})}fromSchema(e){Ad(e,EY);let A=tb(e,e,EZ.schema());d$.assertSchema(A,this.className),this.version=A.result[Eq].valueBlock.valueDec,this.messageImprint=new w5({schema:A.result[EK]}),EJ in A.result&&(this.reqPolicy=A.result[EJ].valueBlock.toString()),EF in A.result&&(this.nonce=A.result[EF]),Ej in A.result&&(this.certReq=A.result[Ej].valueBlock.value),Ez in A.result&&(this.extensions=Array.from(A.result[Ez],e=>new gO({schema:e})))}toSchema(){let e=[];return e.push(new AW({value:this.version})),e.push(this.messageImprint.toSchema()),this.reqPolicy&&e.push(new A1({value:this.reqPolicy})),this.nonce&&e.push(this.nonce),Ex in this&&!1===EZ.compareWithDefault(Ex,this.certReq)&&e.push(new AJ({value:this.certReq})),this.extensions&&e.push(new Ax({idBlock:{tagClass:3,tagNumber:0},value:Array.from(this.extensions,e=>e.toSchema())})),new A6({value:e})}toJSON(){let e={version:this.version,messageImprint:this.messageImprint.toJSON()};return void 0!==this.reqPolicy&&(e.reqPolicy=this.reqPolicy),void 0!==this.nonce&&(e.nonce=this.nonce.toJSON()),void 0!==this.certReq&&!1===EZ.compareWithDefault(Ex,this.certReq)&&(e.certReq=this.certReq),this.extensions&&(e.extensions=Array.from(this.extensions,e=>e.toJSON())),e}}EZ.CLASS_NAME="TimeStampReq";let EV="status",EW="timeStampToken",E$="TimeStampResp",EX=`${E$}.${EV}`,E0=`${E$}.${EW}`,E1=[EX,E0];class E8 extends dX{constructor(e={}){super(),this.status=e2(e,EV,E8.defaultValues(EV)),EW in e&&(this.timeStampToken=e2(e,EW,E8.defaultValues(EW))),e.schema&&this.fromSchema(e.schema)}static defaultValues(e){switch(e){case EV:return new EN;case EW:return new pT;default:return super.defaultValues(e)}}static compareWithDefault(e,A){switch(e){case EV:return EN.compareWithDefault(EV,A.status)&&"statusStrings"in A==!1&&"failInfo"in A==!1;case EW:return""===A.contentType&&A.content instanceof ty;default:return super.defaultValues(e)}}static schema(e={}){let A=e2(e,"names",{});return new A6({name:A.blockName||E$,value:[EN.schema(A.status||{names:{blockName:EX}}),pT.schema(A.timeStampToken||{names:{blockName:E0,optional:!0}})]})}fromSchema(e){Ad(e,E1);let A=tb(e,e,E8.schema());d$.assertSchema(A,this.className),this.status=new EN({schema:A.result[EX]}),E0 in A.result&&(this.timeStampToken=new pT({schema:A.result[E0]}))}toSchema(){let e=[];return e.push(this.status.toSchema()),this.timeStampToken&&e.push(this.timeStampToken.toSchema()),new A6({value:e})}toJSON(){let e={status:this.status.toJSON()};return this.timeStampToken&&(e.timeStampToken=this.timeStampToken.toJSON()),e}async sign(e,A,t=gn(!0)){return this.assertContentType(),new EB({schema:this.timeStampToken.content}).sign(e,0,A,void 0,t)}async verify(e={signer:0,trustedCerts:[],data:dZ},A=gn(!0)){return this.assertContentType(),new EB({schema:this.timeStampToken.content}).verify(e,A)}assertContentType(){if(!this.timeStampToken)throw Error("timeStampToken is absent in TSP response");if(this.timeStampToken.contentType!==uK)throw Error(`Wrong format of timeStampToken: ${this.timeStampToken.contentType}`)}}if(E8.CLASS_NAME="TimeStampResp","u">typeof globalThis&&"crypto"in globalThis){let e="webcrypto";"webkitSubtle"in globalThis.crypto&&(e="safari"),gi(e,new gA({name:e,crypto:globalThis.crypto}))}else if("u">typeof crypto&&"webcrypto"in crypto){let e="NodeJS ^15";gi(e,new gA({name:e,crypto:crypto.webcrypto}))}let E4=new TextEncoder,E2=new TextDecoder("utf-8",{fatal:!0}),E6=eZ.webcrypto,E3=new gA({name:"node",crypto:E6}),E5={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256",publicExponent:new Uint8Array([1,0,1]),modulusLength:2048},E9=`-----BEGIN CERTIFICATE-----
998
998
  MIIDaTCCAlGgAwIBAgIBATANBgkqhkiG9w0BAQUFADB5MQswCQYDVQQGEwJVUzET
999
999
  MBEGA1UEChMKQXBwbGUgSW5jLjEmMCQGA1UECxMdQXBwbGUgQ2VydGlmaWNhdGlv