zevairouter 1.0.161 → 1.0.162

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 (310) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/cli/app/.next-cli-build/BUILD_ID +1 -1
  3. package/cli/app/.next-cli-build/app-path-routes-manifest.json +8 -8
  4. package/cli/app/.next-cli-build/build-manifest.json +2 -2
  5. package/cli/app/.next-cli-build/server/app/(dashboard)/dashboard/automation/page_client-reference-manifest.js +1 -1
  6. package/cli/app/.next-cli-build/server/app/(dashboard)/dashboard/basic-chat/page_client-reference-manifest.js +1 -1
  7. package/cli/app/.next-cli-build/server/app/(dashboard)/dashboard/cli-tools/[toolId]/page_client-reference-manifest.js +1 -1
  8. package/cli/app/.next-cli-build/server/app/(dashboard)/dashboard/cli-tools/page_client-reference-manifest.js +1 -1
  9. package/cli/app/.next-cli-build/server/app/(dashboard)/dashboard/combos/page_client-reference-manifest.js +1 -1
  10. package/cli/app/.next-cli-build/server/app/(dashboard)/dashboard/console-log/page_client-reference-manifest.js +1 -1
  11. package/cli/app/.next-cli-build/server/app/(dashboard)/dashboard/context/page_client-reference-manifest.js +1 -1
  12. package/cli/app/.next-cli-build/server/app/(dashboard)/dashboard/endpoint/page_client-reference-manifest.js +1 -1
  13. package/cli/app/.next-cli-build/server/app/(dashboard)/dashboard/media-providers/[kind]/[id]/page_client-reference-manifest.js +1 -1
  14. package/cli/app/.next-cli-build/server/app/(dashboard)/dashboard/media-providers/[kind]/page_client-reference-manifest.js +1 -1
  15. package/cli/app/.next-cli-build/server/app/(dashboard)/dashboard/media-providers/combo/[id]/page_client-reference-manifest.js +1 -1
  16. package/cli/app/.next-cli-build/server/app/(dashboard)/dashboard/media-providers/web/page_client-reference-manifest.js +1 -1
  17. package/cli/app/.next-cli-build/server/app/(dashboard)/dashboard/mitm/page_client-reference-manifest.js +1 -1
  18. package/cli/app/.next-cli-build/server/app/(dashboard)/dashboard/page_client-reference-manifest.js +1 -1
  19. package/cli/app/.next-cli-build/server/app/(dashboard)/dashboard/playground/page_client-reference-manifest.js +1 -1
  20. package/cli/app/.next-cli-build/server/app/(dashboard)/dashboard/profile/page_client-reference-manifest.js +1 -1
  21. package/cli/app/.next-cli-build/server/app/(dashboard)/dashboard/providers/[id]/page_client-reference-manifest.js +1 -1
  22. package/cli/app/.next-cli-build/server/app/(dashboard)/dashboard/providers/new/page_client-reference-manifest.js +1 -1
  23. package/cli/app/.next-cli-build/server/app/(dashboard)/dashboard/providers/page_client-reference-manifest.js +1 -1
  24. package/cli/app/.next-cli-build/server/app/(dashboard)/dashboard/proxy-pools/page_client-reference-manifest.js +1 -1
  25. package/cli/app/.next-cli-build/server/app/(dashboard)/dashboard/pxpipe/page_client-reference-manifest.js +1 -1
  26. package/cli/app/.next-cli-build/server/app/(dashboard)/dashboard/quota/page_client-reference-manifest.js +1 -1
  27. package/cli/app/.next-cli-build/server/app/(dashboard)/dashboard/terminal/page_client-reference-manifest.js +1 -1
  28. package/cli/app/.next-cli-build/server/app/(dashboard)/dashboard/token-saver/page_client-reference-manifest.js +1 -1
  29. package/cli/app/.next-cli-build/server/app/(dashboard)/dashboard/translator/page_client-reference-manifest.js +1 -1
  30. package/cli/app/.next-cli-build/server/app/(dashboard)/dashboard/usage/page_client-reference-manifest.js +1 -1
  31. package/cli/app/.next-cli-build/server/app/_global-error/page_client-reference-manifest.js +1 -1
  32. package/cli/app/.next-cli-build/server/app/_global-error.html +1 -1
  33. package/cli/app/.next-cli-build/server/app/_global-error.rsc +1 -1
  34. package/cli/app/.next-cli-build/server/app/_global-error.segments/_full.segment.rsc +1 -1
  35. package/cli/app/.next-cli-build/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  36. package/cli/app/.next-cli-build/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  37. package/cli/app/.next-cli-build/server/app/_global-error.segments/_head.segment.rsc +1 -1
  38. package/cli/app/.next-cli-build/server/app/_global-error.segments/_index.segment.rsc +1 -1
  39. package/cli/app/.next-cli-build/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  40. package/cli/app/.next-cli-build/server/app/_not-found/page_client-reference-manifest.js +1 -1
  41. package/cli/app/.next-cli-build/server/app/_not-found.html +1 -1
  42. package/cli/app/.next-cli-build/server/app/_not-found.rsc +3 -3
  43. package/cli/app/.next-cli-build/server/app/_not-found.segments/_full.segment.rsc +3 -3
  44. package/cli/app/.next-cli-build/server/app/_not-found.segments/_head.segment.rsc +1 -1
  45. package/cli/app/.next-cli-build/server/app/_not-found.segments/_index.segment.rsc +3 -3
  46. package/cli/app/.next-cli-build/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  47. package/cli/app/.next-cli-build/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  48. package/cli/app/.next-cli-build/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  49. package/cli/app/.next-cli-build/server/app/api/models/route.js +1 -1
  50. package/cli/app/.next-cli-build/server/app/api/providers/route.js +1 -1
  51. package/cli/app/.next-cli-build/server/app/api/providers/validate/route.js +1 -1
  52. package/cli/app/.next-cli-build/server/app/api/translator/console-logs/route.js +1 -1
  53. package/cli/app/.next-cli-build/server/app/api/translator/console-logs/stream/route.js +1 -1
  54. package/cli/app/.next-cli-build/server/app/api/version/route.js +1 -1
  55. package/cli/app/.next-cli-build/server/app/api/version/shutdown/route.js +1 -1
  56. package/cli/app/.next-cli-build/server/app/api/version/update/route.js +1 -1
  57. package/cli/app/.next-cli-build/server/app/callback/page_client-reference-manifest.js +1 -1
  58. package/cli/app/.next-cli-build/server/app/callback.html +1 -1
  59. package/cli/app/.next-cli-build/server/app/callback.rsc +3 -3
  60. package/cli/app/.next-cli-build/server/app/callback.segments/_full.segment.rsc +3 -3
  61. package/cli/app/.next-cli-build/server/app/callback.segments/_head.segment.rsc +1 -1
  62. package/cli/app/.next-cli-build/server/app/callback.segments/_index.segment.rsc +3 -3
  63. package/cli/app/.next-cli-build/server/app/callback.segments/_tree.segment.rsc +1 -1
  64. package/cli/app/.next-cli-build/server/app/callback.segments/callback/__PAGE__.segment.rsc +1 -1
  65. package/cli/app/.next-cli-build/server/app/callback.segments/callback.segment.rsc +1 -1
  66. package/cli/app/.next-cli-build/server/app/dashboard/automation.html +1 -1
  67. package/cli/app/.next-cli-build/server/app/dashboard/automation.rsc +5 -5
  68. package/cli/app/.next-cli-build/server/app/dashboard/automation.segments/!KGRhc2hib2FyZCk/dashboard/automation/__PAGE__.segment.rsc +2 -2
  69. package/cli/app/.next-cli-build/server/app/dashboard/automation.segments/!KGRhc2hib2FyZCk/dashboard/automation.segment.rsc +1 -1
  70. package/cli/app/.next-cli-build/server/app/dashboard/automation.segments/!KGRhc2hib2FyZCk/dashboard.segment.rsc +1 -1
  71. package/cli/app/.next-cli-build/server/app/dashboard/automation.segments/!KGRhc2hib2FyZCk.segment.rsc +2 -2
  72. package/cli/app/.next-cli-build/server/app/dashboard/automation.segments/_full.segment.rsc +5 -5
  73. package/cli/app/.next-cli-build/server/app/dashboard/automation.segments/_head.segment.rsc +1 -1
  74. package/cli/app/.next-cli-build/server/app/dashboard/automation.segments/_index.segment.rsc +3 -3
  75. package/cli/app/.next-cli-build/server/app/dashboard/automation.segments/_tree.segment.rsc +1 -1
  76. package/cli/app/.next-cli-build/server/app/dashboard/basic-chat.html +1 -1
  77. package/cli/app/.next-cli-build/server/app/dashboard/basic-chat.rsc +5 -5
  78. package/cli/app/.next-cli-build/server/app/dashboard/basic-chat.segments/!KGRhc2hib2FyZCk/dashboard/basic-chat/__PAGE__.segment.rsc +2 -2
  79. package/cli/app/.next-cli-build/server/app/dashboard/basic-chat.segments/!KGRhc2hib2FyZCk/dashboard/basic-chat.segment.rsc +1 -1
  80. package/cli/app/.next-cli-build/server/app/dashboard/basic-chat.segments/!KGRhc2hib2FyZCk/dashboard.segment.rsc +1 -1
  81. package/cli/app/.next-cli-build/server/app/dashboard/basic-chat.segments/!KGRhc2hib2FyZCk.segment.rsc +2 -2
  82. package/cli/app/.next-cli-build/server/app/dashboard/basic-chat.segments/_full.segment.rsc +5 -5
  83. package/cli/app/.next-cli-build/server/app/dashboard/basic-chat.segments/_head.segment.rsc +1 -1
  84. package/cli/app/.next-cli-build/server/app/dashboard/basic-chat.segments/_index.segment.rsc +3 -3
  85. package/cli/app/.next-cli-build/server/app/dashboard/basic-chat.segments/_tree.segment.rsc +1 -1
  86. package/cli/app/.next-cli-build/server/app/dashboard/cli-tools.html +1 -1
  87. package/cli/app/.next-cli-build/server/app/dashboard/cli-tools.rsc +5 -5
  88. package/cli/app/.next-cli-build/server/app/dashboard/cli-tools.segments/!KGRhc2hib2FyZCk/dashboard/cli-tools/__PAGE__.segment.rsc +2 -2
  89. package/cli/app/.next-cli-build/server/app/dashboard/cli-tools.segments/!KGRhc2hib2FyZCk/dashboard/cli-tools.segment.rsc +1 -1
  90. package/cli/app/.next-cli-build/server/app/dashboard/cli-tools.segments/!KGRhc2hib2FyZCk/dashboard.segment.rsc +1 -1
  91. package/cli/app/.next-cli-build/server/app/dashboard/cli-tools.segments/!KGRhc2hib2FyZCk.segment.rsc +2 -2
  92. package/cli/app/.next-cli-build/server/app/dashboard/cli-tools.segments/_full.segment.rsc +5 -5
  93. package/cli/app/.next-cli-build/server/app/dashboard/cli-tools.segments/_head.segment.rsc +1 -1
  94. package/cli/app/.next-cli-build/server/app/dashboard/cli-tools.segments/_index.segment.rsc +3 -3
  95. package/cli/app/.next-cli-build/server/app/dashboard/cli-tools.segments/_tree.segment.rsc +1 -1
  96. package/cli/app/.next-cli-build/server/app/dashboard/combos.html +1 -1
  97. package/cli/app/.next-cli-build/server/app/dashboard/combos.rsc +5 -5
  98. package/cli/app/.next-cli-build/server/app/dashboard/combos.segments/!KGRhc2hib2FyZCk/dashboard/combos/__PAGE__.segment.rsc +2 -2
  99. package/cli/app/.next-cli-build/server/app/dashboard/combos.segments/!KGRhc2hib2FyZCk/dashboard/combos.segment.rsc +1 -1
  100. package/cli/app/.next-cli-build/server/app/dashboard/combos.segments/!KGRhc2hib2FyZCk/dashboard.segment.rsc +1 -1
  101. package/cli/app/.next-cli-build/server/app/dashboard/combos.segments/!KGRhc2hib2FyZCk.segment.rsc +2 -2
  102. package/cli/app/.next-cli-build/server/app/dashboard/combos.segments/_full.segment.rsc +5 -5
  103. package/cli/app/.next-cli-build/server/app/dashboard/combos.segments/_head.segment.rsc +1 -1
  104. package/cli/app/.next-cli-build/server/app/dashboard/combos.segments/_index.segment.rsc +3 -3
  105. package/cli/app/.next-cli-build/server/app/dashboard/combos.segments/_tree.segment.rsc +1 -1
  106. package/cli/app/.next-cli-build/server/app/dashboard/context.html +1 -1
  107. package/cli/app/.next-cli-build/server/app/dashboard/context.rsc +5 -5
  108. package/cli/app/.next-cli-build/server/app/dashboard/context.segments/!KGRhc2hib2FyZCk/dashboard/context/__PAGE__.segment.rsc +2 -2
  109. package/cli/app/.next-cli-build/server/app/dashboard/context.segments/!KGRhc2hib2FyZCk/dashboard/context.segment.rsc +1 -1
  110. package/cli/app/.next-cli-build/server/app/dashboard/context.segments/!KGRhc2hib2FyZCk/dashboard.segment.rsc +1 -1
  111. package/cli/app/.next-cli-build/server/app/dashboard/context.segments/!KGRhc2hib2FyZCk.segment.rsc +2 -2
  112. package/cli/app/.next-cli-build/server/app/dashboard/context.segments/_full.segment.rsc +5 -5
  113. package/cli/app/.next-cli-build/server/app/dashboard/context.segments/_head.segment.rsc +1 -1
  114. package/cli/app/.next-cli-build/server/app/dashboard/context.segments/_index.segment.rsc +3 -3
  115. package/cli/app/.next-cli-build/server/app/dashboard/context.segments/_tree.segment.rsc +1 -1
  116. package/cli/app/.next-cli-build/server/app/dashboard/endpoint.html +1 -1
  117. package/cli/app/.next-cli-build/server/app/dashboard/endpoint.rsc +5 -5
  118. package/cli/app/.next-cli-build/server/app/dashboard/endpoint.segments/!KGRhc2hib2FyZCk/dashboard/endpoint/__PAGE__.segment.rsc +2 -2
  119. package/cli/app/.next-cli-build/server/app/dashboard/endpoint.segments/!KGRhc2hib2FyZCk/dashboard/endpoint.segment.rsc +1 -1
  120. package/cli/app/.next-cli-build/server/app/dashboard/endpoint.segments/!KGRhc2hib2FyZCk/dashboard.segment.rsc +1 -1
  121. package/cli/app/.next-cli-build/server/app/dashboard/endpoint.segments/!KGRhc2hib2FyZCk.segment.rsc +2 -2
  122. package/cli/app/.next-cli-build/server/app/dashboard/endpoint.segments/_full.segment.rsc +5 -5
  123. package/cli/app/.next-cli-build/server/app/dashboard/endpoint.segments/_head.segment.rsc +1 -1
  124. package/cli/app/.next-cli-build/server/app/dashboard/endpoint.segments/_index.segment.rsc +3 -3
  125. package/cli/app/.next-cli-build/server/app/dashboard/endpoint.segments/_tree.segment.rsc +1 -1
  126. package/cli/app/.next-cli-build/server/app/dashboard/media-providers/web.html +1 -1
  127. package/cli/app/.next-cli-build/server/app/dashboard/media-providers/web.rsc +5 -5
  128. package/cli/app/.next-cli-build/server/app/dashboard/media-providers/web.segments/!KGRhc2hib2FyZCk/dashboard/media-providers/web/__PAGE__.segment.rsc +2 -2
  129. package/cli/app/.next-cli-build/server/app/dashboard/media-providers/web.segments/!KGRhc2hib2FyZCk/dashboard/media-providers/web.segment.rsc +1 -1
  130. package/cli/app/.next-cli-build/server/app/dashboard/media-providers/web.segments/!KGRhc2hib2FyZCk/dashboard/media-providers.segment.rsc +1 -1
  131. package/cli/app/.next-cli-build/server/app/dashboard/media-providers/web.segments/!KGRhc2hib2FyZCk/dashboard.segment.rsc +1 -1
  132. package/cli/app/.next-cli-build/server/app/dashboard/media-providers/web.segments/!KGRhc2hib2FyZCk.segment.rsc +2 -2
  133. package/cli/app/.next-cli-build/server/app/dashboard/media-providers/web.segments/_full.segment.rsc +5 -5
  134. package/cli/app/.next-cli-build/server/app/dashboard/media-providers/web.segments/_head.segment.rsc +1 -1
  135. package/cli/app/.next-cli-build/server/app/dashboard/media-providers/web.segments/_index.segment.rsc +3 -3
  136. package/cli/app/.next-cli-build/server/app/dashboard/media-providers/web.segments/_tree.segment.rsc +1 -1
  137. package/cli/app/.next-cli-build/server/app/dashboard/mitm.html +1 -1
  138. package/cli/app/.next-cli-build/server/app/dashboard/mitm.rsc +5 -5
  139. package/cli/app/.next-cli-build/server/app/dashboard/mitm.segments/!KGRhc2hib2FyZCk/dashboard/mitm/__PAGE__.segment.rsc +2 -2
  140. package/cli/app/.next-cli-build/server/app/dashboard/mitm.segments/!KGRhc2hib2FyZCk/dashboard/mitm.segment.rsc +1 -1
  141. package/cli/app/.next-cli-build/server/app/dashboard/mitm.segments/!KGRhc2hib2FyZCk/dashboard.segment.rsc +1 -1
  142. package/cli/app/.next-cli-build/server/app/dashboard/mitm.segments/!KGRhc2hib2FyZCk.segment.rsc +2 -2
  143. package/cli/app/.next-cli-build/server/app/dashboard/mitm.segments/_full.segment.rsc +5 -5
  144. package/cli/app/.next-cli-build/server/app/dashboard/mitm.segments/_head.segment.rsc +1 -1
  145. package/cli/app/.next-cli-build/server/app/dashboard/mitm.segments/_index.segment.rsc +3 -3
  146. package/cli/app/.next-cli-build/server/app/dashboard/mitm.segments/_tree.segment.rsc +1 -1
  147. package/cli/app/.next-cli-build/server/app/dashboard/playground.html +1 -1
  148. package/cli/app/.next-cli-build/server/app/dashboard/playground.rsc +5 -5
  149. package/cli/app/.next-cli-build/server/app/dashboard/playground.segments/!KGRhc2hib2FyZCk/dashboard/playground/__PAGE__.segment.rsc +2 -2
  150. package/cli/app/.next-cli-build/server/app/dashboard/playground.segments/!KGRhc2hib2FyZCk/dashboard/playground.segment.rsc +1 -1
  151. package/cli/app/.next-cli-build/server/app/dashboard/playground.segments/!KGRhc2hib2FyZCk/dashboard.segment.rsc +1 -1
  152. package/cli/app/.next-cli-build/server/app/dashboard/playground.segments/!KGRhc2hib2FyZCk.segment.rsc +2 -2
  153. package/cli/app/.next-cli-build/server/app/dashboard/playground.segments/_full.segment.rsc +5 -5
  154. package/cli/app/.next-cli-build/server/app/dashboard/playground.segments/_head.segment.rsc +1 -1
  155. package/cli/app/.next-cli-build/server/app/dashboard/playground.segments/_index.segment.rsc +3 -3
  156. package/cli/app/.next-cli-build/server/app/dashboard/playground.segments/_tree.segment.rsc +1 -1
  157. package/cli/app/.next-cli-build/server/app/dashboard/profile.html +1 -1
  158. package/cli/app/.next-cli-build/server/app/dashboard/profile.rsc +5 -5
  159. package/cli/app/.next-cli-build/server/app/dashboard/profile.segments/!KGRhc2hib2FyZCk/dashboard/profile/__PAGE__.segment.rsc +2 -2
  160. package/cli/app/.next-cli-build/server/app/dashboard/profile.segments/!KGRhc2hib2FyZCk/dashboard/profile.segment.rsc +1 -1
  161. package/cli/app/.next-cli-build/server/app/dashboard/profile.segments/!KGRhc2hib2FyZCk/dashboard.segment.rsc +1 -1
  162. package/cli/app/.next-cli-build/server/app/dashboard/profile.segments/!KGRhc2hib2FyZCk.segment.rsc +2 -2
  163. package/cli/app/.next-cli-build/server/app/dashboard/profile.segments/_full.segment.rsc +5 -5
  164. package/cli/app/.next-cli-build/server/app/dashboard/profile.segments/_head.segment.rsc +1 -1
  165. package/cli/app/.next-cli-build/server/app/dashboard/profile.segments/_index.segment.rsc +3 -3
  166. package/cli/app/.next-cli-build/server/app/dashboard/profile.segments/_tree.segment.rsc +1 -1
  167. package/cli/app/.next-cli-build/server/app/dashboard/providers/new.html +1 -1
  168. package/cli/app/.next-cli-build/server/app/dashboard/providers/new.rsc +5 -5
  169. package/cli/app/.next-cli-build/server/app/dashboard/providers/new.segments/!KGRhc2hib2FyZCk/dashboard/providers/new/__PAGE__.segment.rsc +2 -2
  170. package/cli/app/.next-cli-build/server/app/dashboard/providers/new.segments/!KGRhc2hib2FyZCk/dashboard/providers/new.segment.rsc +1 -1
  171. package/cli/app/.next-cli-build/server/app/dashboard/providers/new.segments/!KGRhc2hib2FyZCk/dashboard/providers.segment.rsc +1 -1
  172. package/cli/app/.next-cli-build/server/app/dashboard/providers/new.segments/!KGRhc2hib2FyZCk/dashboard.segment.rsc +1 -1
  173. package/cli/app/.next-cli-build/server/app/dashboard/providers/new.segments/!KGRhc2hib2FyZCk.segment.rsc +2 -2
  174. package/cli/app/.next-cli-build/server/app/dashboard/providers/new.segments/_full.segment.rsc +5 -5
  175. package/cli/app/.next-cli-build/server/app/dashboard/providers/new.segments/_head.segment.rsc +1 -1
  176. package/cli/app/.next-cli-build/server/app/dashboard/providers/new.segments/_index.segment.rsc +3 -3
  177. package/cli/app/.next-cli-build/server/app/dashboard/providers/new.segments/_tree.segment.rsc +1 -1
  178. package/cli/app/.next-cli-build/server/app/dashboard/providers.html +1 -1
  179. package/cli/app/.next-cli-build/server/app/dashboard/providers.rsc +5 -5
  180. package/cli/app/.next-cli-build/server/app/dashboard/providers.segments/!KGRhc2hib2FyZCk/dashboard/providers/__PAGE__.segment.rsc +2 -2
  181. package/cli/app/.next-cli-build/server/app/dashboard/providers.segments/!KGRhc2hib2FyZCk/dashboard/providers.segment.rsc +1 -1
  182. package/cli/app/.next-cli-build/server/app/dashboard/providers.segments/!KGRhc2hib2FyZCk/dashboard.segment.rsc +1 -1
  183. package/cli/app/.next-cli-build/server/app/dashboard/providers.segments/!KGRhc2hib2FyZCk.segment.rsc +2 -2
  184. package/cli/app/.next-cli-build/server/app/dashboard/providers.segments/_full.segment.rsc +5 -5
  185. package/cli/app/.next-cli-build/server/app/dashboard/providers.segments/_head.segment.rsc +1 -1
  186. package/cli/app/.next-cli-build/server/app/dashboard/providers.segments/_index.segment.rsc +3 -3
  187. package/cli/app/.next-cli-build/server/app/dashboard/providers.segments/_tree.segment.rsc +1 -1
  188. package/cli/app/.next-cli-build/server/app/dashboard/proxy-pools.html +1 -1
  189. package/cli/app/.next-cli-build/server/app/dashboard/proxy-pools.rsc +5 -5
  190. package/cli/app/.next-cli-build/server/app/dashboard/proxy-pools.segments/!KGRhc2hib2FyZCk/dashboard/proxy-pools/__PAGE__.segment.rsc +2 -2
  191. package/cli/app/.next-cli-build/server/app/dashboard/proxy-pools.segments/!KGRhc2hib2FyZCk/dashboard/proxy-pools.segment.rsc +1 -1
  192. package/cli/app/.next-cli-build/server/app/dashboard/proxy-pools.segments/!KGRhc2hib2FyZCk/dashboard.segment.rsc +1 -1
  193. package/cli/app/.next-cli-build/server/app/dashboard/proxy-pools.segments/!KGRhc2hib2FyZCk.segment.rsc +2 -2
  194. package/cli/app/.next-cli-build/server/app/dashboard/proxy-pools.segments/_full.segment.rsc +5 -5
  195. package/cli/app/.next-cli-build/server/app/dashboard/proxy-pools.segments/_head.segment.rsc +1 -1
  196. package/cli/app/.next-cli-build/server/app/dashboard/proxy-pools.segments/_index.segment.rsc +3 -3
  197. package/cli/app/.next-cli-build/server/app/dashboard/proxy-pools.segments/_tree.segment.rsc +1 -1
  198. package/cli/app/.next-cli-build/server/app/dashboard/pxpipe.html +1 -1
  199. package/cli/app/.next-cli-build/server/app/dashboard/pxpipe.rsc +5 -5
  200. package/cli/app/.next-cli-build/server/app/dashboard/pxpipe.segments/!KGRhc2hib2FyZCk/dashboard/pxpipe/__PAGE__.segment.rsc +2 -2
  201. package/cli/app/.next-cli-build/server/app/dashboard/pxpipe.segments/!KGRhc2hib2FyZCk/dashboard/pxpipe.segment.rsc +1 -1
  202. package/cli/app/.next-cli-build/server/app/dashboard/pxpipe.segments/!KGRhc2hib2FyZCk/dashboard.segment.rsc +1 -1
  203. package/cli/app/.next-cli-build/server/app/dashboard/pxpipe.segments/!KGRhc2hib2FyZCk.segment.rsc +2 -2
  204. package/cli/app/.next-cli-build/server/app/dashboard/pxpipe.segments/_full.segment.rsc +5 -5
  205. package/cli/app/.next-cli-build/server/app/dashboard/pxpipe.segments/_head.segment.rsc +1 -1
  206. package/cli/app/.next-cli-build/server/app/dashboard/pxpipe.segments/_index.segment.rsc +3 -3
  207. package/cli/app/.next-cli-build/server/app/dashboard/pxpipe.segments/_tree.segment.rsc +1 -1
  208. package/cli/app/.next-cli-build/server/app/dashboard/quota.html +2 -2
  209. package/cli/app/.next-cli-build/server/app/dashboard/quota.rsc +6 -6
  210. package/cli/app/.next-cli-build/server/app/dashboard/quota.segments/!KGRhc2hib2FyZCk/dashboard/quota/__PAGE__.segment.rsc +3 -3
  211. package/cli/app/.next-cli-build/server/app/dashboard/quota.segments/!KGRhc2hib2FyZCk/dashboard/quota.segment.rsc +1 -1
  212. package/cli/app/.next-cli-build/server/app/dashboard/quota.segments/!KGRhc2hib2FyZCk/dashboard.segment.rsc +1 -1
  213. package/cli/app/.next-cli-build/server/app/dashboard/quota.segments/!KGRhc2hib2FyZCk.segment.rsc +2 -2
  214. package/cli/app/.next-cli-build/server/app/dashboard/quota.segments/_full.segment.rsc +6 -6
  215. package/cli/app/.next-cli-build/server/app/dashboard/quota.segments/_head.segment.rsc +1 -1
  216. package/cli/app/.next-cli-build/server/app/dashboard/quota.segments/_index.segment.rsc +3 -3
  217. package/cli/app/.next-cli-build/server/app/dashboard/quota.segments/_tree.segment.rsc +1 -1
  218. package/cli/app/.next-cli-build/server/app/dashboard/settings/pricing/page_client-reference-manifest.js +1 -1
  219. package/cli/app/.next-cli-build/server/app/dashboard/settings/pricing.html +1 -1
  220. package/cli/app/.next-cli-build/server/app/dashboard/settings/pricing.rsc +3 -3
  221. package/cli/app/.next-cli-build/server/app/dashboard/settings/pricing.segments/_full.segment.rsc +3 -3
  222. package/cli/app/.next-cli-build/server/app/dashboard/settings/pricing.segments/_head.segment.rsc +1 -1
  223. package/cli/app/.next-cli-build/server/app/dashboard/settings/pricing.segments/_index.segment.rsc +3 -3
  224. package/cli/app/.next-cli-build/server/app/dashboard/settings/pricing.segments/_tree.segment.rsc +1 -1
  225. package/cli/app/.next-cli-build/server/app/dashboard/settings/pricing.segments/dashboard/settings/pricing/__PAGE__.segment.rsc +1 -1
  226. package/cli/app/.next-cli-build/server/app/dashboard/settings/pricing.segments/dashboard/settings/pricing.segment.rsc +1 -1
  227. package/cli/app/.next-cli-build/server/app/dashboard/settings/pricing.segments/dashboard/settings.segment.rsc +1 -1
  228. package/cli/app/.next-cli-build/server/app/dashboard/settings/pricing.segments/dashboard.segment.rsc +1 -1
  229. package/cli/app/.next-cli-build/server/app/dashboard/token-saver.html +1 -1
  230. package/cli/app/.next-cli-build/server/app/dashboard/token-saver.rsc +5 -5
  231. package/cli/app/.next-cli-build/server/app/dashboard/token-saver.segments/!KGRhc2hib2FyZCk/dashboard/token-saver/__PAGE__.segment.rsc +2 -2
  232. package/cli/app/.next-cli-build/server/app/dashboard/token-saver.segments/!KGRhc2hib2FyZCk/dashboard/token-saver.segment.rsc +1 -1
  233. package/cli/app/.next-cli-build/server/app/dashboard/token-saver.segments/!KGRhc2hib2FyZCk/dashboard.segment.rsc +1 -1
  234. package/cli/app/.next-cli-build/server/app/dashboard/token-saver.segments/!KGRhc2hib2FyZCk.segment.rsc +2 -2
  235. package/cli/app/.next-cli-build/server/app/dashboard/token-saver.segments/_full.segment.rsc +5 -5
  236. package/cli/app/.next-cli-build/server/app/dashboard/token-saver.segments/_head.segment.rsc +1 -1
  237. package/cli/app/.next-cli-build/server/app/dashboard/token-saver.segments/_index.segment.rsc +3 -3
  238. package/cli/app/.next-cli-build/server/app/dashboard/token-saver.segments/_tree.segment.rsc +1 -1
  239. package/cli/app/.next-cli-build/server/app/dashboard/translator.html +1 -1
  240. package/cli/app/.next-cli-build/server/app/dashboard/translator.rsc +5 -5
  241. package/cli/app/.next-cli-build/server/app/dashboard/translator.segments/!KGRhc2hib2FyZCk/dashboard/translator/__PAGE__.segment.rsc +2 -2
  242. package/cli/app/.next-cli-build/server/app/dashboard/translator.segments/!KGRhc2hib2FyZCk/dashboard/translator.segment.rsc +1 -1
  243. package/cli/app/.next-cli-build/server/app/dashboard/translator.segments/!KGRhc2hib2FyZCk/dashboard.segment.rsc +1 -1
  244. package/cli/app/.next-cli-build/server/app/dashboard/translator.segments/!KGRhc2hib2FyZCk.segment.rsc +2 -2
  245. package/cli/app/.next-cli-build/server/app/dashboard/translator.segments/_full.segment.rsc +5 -5
  246. package/cli/app/.next-cli-build/server/app/dashboard/translator.segments/_head.segment.rsc +1 -1
  247. package/cli/app/.next-cli-build/server/app/dashboard/translator.segments/_index.segment.rsc +3 -3
  248. package/cli/app/.next-cli-build/server/app/dashboard/translator.segments/_tree.segment.rsc +1 -1
  249. package/cli/app/.next-cli-build/server/app/dashboard/usage.html +1 -1
  250. package/cli/app/.next-cli-build/server/app/dashboard/usage.rsc +5 -5
  251. package/cli/app/.next-cli-build/server/app/dashboard/usage.segments/!KGRhc2hib2FyZCk/dashboard/usage/__PAGE__.segment.rsc +2 -2
  252. package/cli/app/.next-cli-build/server/app/dashboard/usage.segments/!KGRhc2hib2FyZCk/dashboard/usage.segment.rsc +1 -1
  253. package/cli/app/.next-cli-build/server/app/dashboard/usage.segments/!KGRhc2hib2FyZCk/dashboard.segment.rsc +1 -1
  254. package/cli/app/.next-cli-build/server/app/dashboard/usage.segments/!KGRhc2hib2FyZCk.segment.rsc +2 -2
  255. package/cli/app/.next-cli-build/server/app/dashboard/usage.segments/_full.segment.rsc +5 -5
  256. package/cli/app/.next-cli-build/server/app/dashboard/usage.segments/_head.segment.rsc +1 -1
  257. package/cli/app/.next-cli-build/server/app/dashboard/usage.segments/_index.segment.rsc +3 -3
  258. package/cli/app/.next-cli-build/server/app/dashboard/usage.segments/_tree.segment.rsc +1 -1
  259. package/cli/app/.next-cli-build/server/app/dashboard.html +1 -1
  260. package/cli/app/.next-cli-build/server/app/dashboard.rsc +5 -5
  261. package/cli/app/.next-cli-build/server/app/dashboard.segments/!KGRhc2hib2FyZCk/dashboard/__PAGE__.segment.rsc +2 -2
  262. package/cli/app/.next-cli-build/server/app/dashboard.segments/!KGRhc2hib2FyZCk/dashboard.segment.rsc +1 -1
  263. package/cli/app/.next-cli-build/server/app/dashboard.segments/!KGRhc2hib2FyZCk.segment.rsc +2 -2
  264. package/cli/app/.next-cli-build/server/app/dashboard.segments/_full.segment.rsc +5 -5
  265. package/cli/app/.next-cli-build/server/app/dashboard.segments/_head.segment.rsc +1 -1
  266. package/cli/app/.next-cli-build/server/app/dashboard.segments/_index.segment.rsc +3 -3
  267. package/cli/app/.next-cli-build/server/app/dashboard.segments/_tree.segment.rsc +1 -1
  268. package/cli/app/.next-cli-build/server/app/index.html +1 -1
  269. package/cli/app/.next-cli-build/server/app/index.rsc +3 -3
  270. package/cli/app/.next-cli-build/server/app/index.segments/__PAGE__.segment.rsc +1 -1
  271. package/cli/app/.next-cli-build/server/app/index.segments/_full.segment.rsc +3 -3
  272. package/cli/app/.next-cli-build/server/app/index.segments/_head.segment.rsc +1 -1
  273. package/cli/app/.next-cli-build/server/app/index.segments/_index.segment.rsc +3 -3
  274. package/cli/app/.next-cli-build/server/app/index.segments/_tree.segment.rsc +1 -1
  275. package/cli/app/.next-cli-build/server/app/landing/page_client-reference-manifest.js +1 -1
  276. package/cli/app/.next-cli-build/server/app/landing.html +1 -1
  277. package/cli/app/.next-cli-build/server/app/landing.rsc +4 -4
  278. package/cli/app/.next-cli-build/server/app/landing.segments/_full.segment.rsc +4 -4
  279. package/cli/app/.next-cli-build/server/app/landing.segments/_head.segment.rsc +1 -1
  280. package/cli/app/.next-cli-build/server/app/landing.segments/_index.segment.rsc +3 -3
  281. package/cli/app/.next-cli-build/server/app/landing.segments/_tree.segment.rsc +1 -1
  282. package/cli/app/.next-cli-build/server/app/landing.segments/landing/__PAGE__.segment.rsc +2 -2
  283. package/cli/app/.next-cli-build/server/app/landing.segments/landing.segment.rsc +1 -1
  284. package/cli/app/.next-cli-build/server/app/login/page_client-reference-manifest.js +1 -1
  285. package/cli/app/.next-cli-build/server/app/login.html +1 -1
  286. package/cli/app/.next-cli-build/server/app/login.rsc +4 -4
  287. package/cli/app/.next-cli-build/server/app/login.segments/_full.segment.rsc +4 -4
  288. package/cli/app/.next-cli-build/server/app/login.segments/_head.segment.rsc +1 -1
  289. package/cli/app/.next-cli-build/server/app/login.segments/_index.segment.rsc +3 -3
  290. package/cli/app/.next-cli-build/server/app/login.segments/_tree.segment.rsc +1 -1
  291. package/cli/app/.next-cli-build/server/app/login.segments/login/__PAGE__.segment.rsc +2 -2
  292. package/cli/app/.next-cli-build/server/app/login.segments/login.segment.rsc +1 -1
  293. package/cli/app/.next-cli-build/server/app/page_client-reference-manifest.js +1 -1
  294. package/cli/app/.next-cli-build/server/app-paths-manifest.json +8 -8
  295. package/cli/app/.next-cli-build/server/chunks/3155.js +1 -1
  296. package/cli/app/.next-cli-build/server/chunks/4746.js +1 -1
  297. package/cli/app/.next-cli-build/server/chunks/5307.js +1 -1
  298. package/cli/app/.next-cli-build/server/chunks/8306.js +1 -1
  299. package/cli/app/.next-cli-build/server/chunks/8371.js +1 -1
  300. package/cli/app/.next-cli-build/server/chunks/9621.js +1 -1
  301. package/cli/app/.next-cli-build/server/middleware-build-manifest.js +1 -1
  302. package/cli/app/.next-cli-build/server/pages/404.html +1 -1
  303. package/cli/app/.next-cli-build/server/pages/500.html +1 -1
  304. package/cli/app/.next-cli-build/static/chunks/{620-04e6e41abaf14d26.js → 620-1d63d33751749341.js} +1 -1
  305. package/cli/app/CHANGELOG.md +5 -0
  306. package/cli/app/package.json +1 -1
  307. package/cli/package.json +1 -1
  308. package/package.json +1 -1
  309. /package/cli/app/.next-cli-build/static/{zs0kUFVQPqSXvSJ1dbHWv → gR4IhToD5iPmyO1KKxUOo}/_buildManifest.js +0 -0
  310. /package/cli/app/.next-cli-build/static/{zs0kUFVQPqSXvSJ1dbHWv → gR4IhToD5iPmyO1KKxUOo}/_ssgManifest.js +0 -0
@@ -1 +1 @@
1
- "use strict";exports.id=8371,exports.ids=[8371],exports.modules={48371:(a,b,c)=>{c.d(b,{xM:()=>ah,t9:()=>ao,TK:()=>an,cO:()=>i.cO,VU:()=>aL});var d=c(55511),e=c(73024),f=c.n(e),g=c(76760),h=c.n(g),i=c(13868),j=c(71998),k=c(89718),l=c(20116),m=c(90715),n=c(92990),o=c(39609);let p=globalThis.fetch,q=new Set(["ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT"]),r=new Set(["a timeout","is cancelled","is complete","number banned, when number already used"]);class s extends Error{constructor(a,{status:b,body:c}={}){super(a),this.name="FiveSimError",this.status=b,this.body=c}}class t extends s{constructor(a){super(`5sim order ${a} timed out waiting for SMS`),this.name="FiveSimTimeoutError",this.orderId=a}}class u extends s{constructor(a,b){super(`5sim request to ${a} timed out after ${b}ms`),this.name="FiveSimRequestTimeoutError",this.code="FIVESIM_REQUEST_TIMEOUT",this.path=a,this.timeoutMs=b}}class v extends s{constructor(a){super(a),this.name="FiveSimUnknownOutcomeError",this.code="FIVESIM_BUY_OUTCOME_UNKNOWN",this.outcomeUnknown=!0}}class w extends s{constructor(a,b){super(`5sim order ${a} cancelled: ${b}`),this.name="FiveSimCancelledError",this.orderId=a}}class x extends s{constructor(a){super(`5sim order ${a} number was already used (banned)`),this.name="FiveSimBannedError",this.orderId=a}}class y{constructor({apiKey:a,proxyOptions:b=null,fetchImpl:c=null}={}){if(!a||"string"!=typeof a||!a.trim())throw new s("5sim API key is required");this.apiKey=a.trim(),this.proxyOptions=b,this.fetchImpl="function"==typeof c?c:null}_headers(a={}){return{Authorization:`Bearer ${this.apiKey}`,Accept:"application/json",...a}}async _get(a,{headers:b,timeoutMs:c=15e3,signal:d,...e}={}){let f,g=`https://5sim.net/v1${a}`,h=this.fetchImpl||(this.proxyOptions?.enabled?o.proxyAwareFetch:p),i=Number.isFinite(c)&&c>0?new AbortController:null,j=i?.signal||null,k=i?setTimeout(()=>i.abort(),c):null;k?.unref?.();let l=function(a){let b=a.filter(Boolean);if(0===b.length)return null;if(1===b.length)return b[0];if("function"==typeof AbortSignal.any)return AbortSignal.any(b);let c=new AbortController;for(let a of b){if(a.aborted){c.abort(a.reason);break}a.addEventListener("abort",()=>c.abort(a.reason),{once:!0})}return c.signal}([d,j]),m=b=>{if(d?.aborted){let c=new s(`5sim request to ${a} was aborted`);return c.code="FIVESIM_REQUEST_ABORTED",c.cause=b,c}if(j?.aborted){let d=new u(a,c);return d.cause=b,d}return b};try{let c;try{f=await h(g,{method:"GET",headers:this._headers(b),...e,...l?{signal:l}:{}},this.proxyOptions)}catch(a){throw m(a)}try{c=await f.text()}catch(a){throw m(a)}if(!f.ok)throw new s(`5sim request to ${a} failed (HTTP ${f.status}): ${c.slice(0,200)}`,{status:f.status,body:c});try{return JSON.parse(c)}catch{if(c&&!c.startsWith("{"))throw new s(`5sim ${a} returned non-JSON: ${c.slice(0,200)}`,{status:f.status,body:c});return null}}finally{k&&clearTimeout(k)}}async buyNumber({country:a="hongkong",operator:b="any",product:c="codebuddy",allowProductFallback:d=!1,responseTimeoutMs:e=2e4,lateAbortTimeoutMs:f=45e3,signal:g=null}={}){if(g?.aborted){let a=new s("5sim purchase cancelled before the request started");throw a.code="FIVESIM_REQUEST_ABORTED",a}let h="codebuddy"===c&&d?["codebuddy","other"]:[c],i=null;for(let c of h){let j=`/user/buy/activation/${encodeURIComponent(a)}/${encodeURIComponent(b)}/${encodeURIComponent(c)}`;try{let a,b=Math.max(Number(f)||45e3,(Number(e)||2e4)+1e3),c=this._get(j,{timeoutMs:b});try{a=await A(c,e,g)}catch(a){throw a?.code==="FIVESIM_BUY_OUTCOME_UNKNOWN"&&c.then(a=>a?.id?this.cancelOrder(a.id):null).catch(()=>null),a}if(!a||!a.id||!a.phone)throw new s(`5sim buyNumber returned unexpected shape: ${JSON.stringify(a).slice(0,200)}`,{body:a});return a}catch(e){i=e;let a=e?.status,b=String(e?.body||e?.message||"").toLowerCase();if(!(d&&"codebuddy"===c&&h.includes("other")&&(400===a||404===a||b.includes("no free")||b.includes("not enough")||b.includes("no product"))))throw e}}throw i||new s("5sim buyNumber failed for all product candidates")}async checkOrder(a,b={}){return this._get(`/user/check/${a}`,b)}async pollCode(a,{timeoutMs:b=9e5,intervalMs:c=6e3,signal:d}={}){let e=Number(c),f=Number.isFinite(e)?Math.max(5e3,e):6e3,g=Number(b),h=Number.isFinite(g)&&g>0?g:9e5,i=Date.now()+h,j=0,k=async()=>{try{await function(a,b=null){return b?.aborted?Promise.reject(b.reason||Error("Aborted")):new Promise((c,d)=>{let e=()=>b?.removeEventListener("abort",g),f=setTimeout(()=>{e(),c()},a),g=()=>{clearTimeout(f),e(),d(b.reason||Error("Aborted"))};b?.addEventListener("abort",g,{once:!0})})}(f,d)}catch(b){if(d?.aborted)throw new w(a,"aborted by caller");throw b}};for(;Date.now()<i;){let b;if(d?.aborted)throw new w(a,"aborted by caller");try{b=await this.checkOrder(a,{signal:d})}catch(b){if(d?.aborted||b?.code==="FIVESIM_REQUEST_ABORTED")throw new w(a,"aborted by caller");if(b instanceof u||function(a){if(a instanceof s)return 408===a.status||429===a.status||a.status>=500;if(a instanceof TypeError)return!0;let b=a?.code||a?.cause?.code;return q.has(b)}(b)){if(++j>5)throw b;await k();continue}throw b}if(j=0,Array.isArray(b.sms)&&b.sms.length>0){let a=z(b.sms[b.sms.length-1]);if(a)return a}if(b.status&&r.has(b.status)){if("a timeout"===b.status)throw new t(a);if("number banned, when number already used"===b.status)throw new x(a);if("is cancelled"===b.status)throw new w(a,b.status);if("is complete"===b.status){let c=function(a){if(!Array.isArray(a))return null;for(let b=a.length-1;b>=0;b--){let c=z(a[b]);if(c)return c}return null}(b.sms);if(c)return c;throw new s(`5sim order ${a} completed but no SMS code found`,{body:b})}}await k()}throw new t(a)}async finishOrder(a){try{return await this._get(`/user/finish/${a}`),!0}catch(b){return console.warn(`[5sim] finishOrder(${a}) failed (best-effort): ${b.message}`),!1}}async cancelOrder(a){try{return await this._get(`/user/cancel/${a}`),!0}catch(b){return console.warn(`[5sim] cancelOrder(${a}) failed (best-effort): ${b.message}`),!1}}async banOrder(a){try{return await this._get(`/user/ban/${a}`),!0}catch(b){return console.warn(`[5sim] banOrder(${a}) failed (best-effort): ${b.message}`),!1}}async getBalance(){try{let a=await this._get("/user/profile");return{balance:a?.balance??null,rating:a?.rating??null}}catch(a){return console.warn(`[5sim] getBalance failed: ${a.message}`),{balance:null,rating:null}}}}function z(a){return a?a.code&&/\d{4,8}/.test(String(a.code))?String(a.code).match(/\d{4,8}/)[0]:a.text?function(a){if(!a)return null;let b=String(a).match(/\b(\d{4,8})\b/);return b?b[1]:null}(a.text):null:null}async function A(a,b,c=null){let d=Number(b)||2e4,e=null,f=null,g=new Promise((a,b)=>{let g=a=>b(new v(`5sim buy request ${a}; purchase outcome is unknown and any late successful order will be cancelled automatically`));e=setTimeout(()=>{g(`did not answer within ${d}ms`)},d),e.unref?.(),f=()=>g("was interrupted by the caller"),c?.aborted?f():c?.addEventListener("abort",f,{once:!0})});try{return await Promise.race([a,g])}finally{e&&clearTimeout(e),f&&c?.removeEventListener("abort",f)}}let B=["https://www.codebuddy.cn/login/"],C=["text=手机号","div:has-text('手机号')","span:has-text('手机号')","[class*='phone']:has-text('手机号')","div.kc-phone-tab:has-text('手机号')"],D=["text=手机号","text=其他登录方式","text=微信","#phone-iframe",".login-phone-box"],E=["button:has-text('同意')","text=同意并继续","text=同意"],F="#phone-iframe",G="#phoneNumber",H=".kc-country-option",I=".kc-country-code-text",J="#code",K=".code-btn",L=['iframe[src*="captcha"]','iframe[src*="tcaptcha"]',"#tcaptcha","#tcaptcha_transform",".nc_iconfont",".nc_wrapper",'[class*="captcha"]','[id*="captcha"]',"text=滑块","text=拖动"],M=["#input-error",".pf-c-form__helper-text.pf-m-error",".kc-feedback-text"],N=new Set(["login_risk_state"]),O=["账号访问受限","安全策略限制","访问受限","account restricted","access restricted"];function P(a="Tencent risk policy rejected the post-OTP session"){return{status:"failed_restricted",error:`Account restricted after OTP (${a}). Use a different residential CN/HK proxy with concurrency 1; do not retry this number on the same egress IP.`}}async function Q(a){let b=a.locator("input.btn-lg.code-btn").first(),c=null;try{await b.waitFor({state:"visible",timeout:5e3}),c=b}catch{let b=a.locator(K).first();try{await b.waitFor({state:"visible",timeout:5e3}),c=b}catch{c=null}}if(!c)return{ok:!1,reason:"missing"};let d=await c.click().then(()=>!0).catch(()=>!1);return{ok:d,reason:d?null:"click_failed"}}async function R(a,{timeoutMs:b=3e3}={}){let c=a.locator(".t-checkbox").last();if(!await c.isVisible({timeout:b}).catch(()=>!1))return{ok:!0,present:!1,changed:!1};let d=c.locator("input").first(),e=async()=>{if(!0===await d.isChecked().catch(()=>null))return!0;let a=await c.getAttribute("class").catch(()=>"");return!!/(?:^|\s)t-is-checked(?:\s|$)/.test(String(a||""))};if(await e())return{ok:!0,present:!0,changed:!1};if(!await c.click().then(()=>!0).catch(()=>!1))return{ok:!1,present:!0,changed:!1};let f=Date.now()+b;for(;Date.now()<f;){if(await e())return{ok:!0,present:!0,changed:!0};await a.waitForTimeout(100).catch(()=>new Promise(a=>setTimeout(a,100)))}return{ok:!1,present:!0,changed:!0}}async function S(a,{timeoutMs:b=8e3}={}){let c=Date.now()+b;for(;Date.now()<c;){let b=a.locator(K).first(),c=await b.evaluate(a=>({disabled:!!a.disabled,ariaDisabled:"true"===a.getAttribute("aria-disabled"),label:String(a.value||a.textContent||"").trim()})).catch(()=>null);if(c){let a=/(?:^\d+$|\d+\s*(?:s|sec|\u79d2)|\u91cd\u65b0|\u5df2\u53d1\u9001|resend|sent)/i.test(c.label);if(c.disabled||c.ariaDisabled||a)return{ok:!0,state:c}}await a.waitForTimeout(200).catch(()=>new Promise(a=>setTimeout(a,200)))}return{ok:!1,state:null}}async function T(a,{timeoutMs:b,signal:c=null}={}){let d=null,e=null,f=new Promise((a,c)=>{d=setTimeout(()=>c(Error("Timed out waiting for SMS code")),b),d.unref?.()}),g=c?new Promise((a,b)=>{e=()=>b(c.reason||Object.assign(Error("Job cancelled"),{code:"JOB_CANCELLED"})),c.aborted?e():c.addEventListener("abort",e,{once:!0})}):null;try{return await Promise.race([a,f,...g?[g]:[]])}finally{d&&clearTimeout(d),e&&c?.removeEventListener("abort",e)}}async function U({page:a,phone:b,resolvePhone:c,pollSmsPromise:d,waitForSms:e,onStep:f,phoneFormatter:g=a=>a,timeouts:h={},signal:i=null,isCancelled:j=null}){let k=h.nav??3e4,l=h.action??15e3,m=h.codeWait??9e5,n=h.postSubmit??1e4,o=(a,b)=>f?.(a,b),p=()=>{if(i?.aborted){if(i.reason?.code==="CN_ACCOUNT_HARD_TIMEOUT")throw i.reason;let a=Error("Job cancelled");throw a.code="JOB_CANCELLED",a}if("function"==typeof j&&j()){let a=Error("Job cancelled");throw a.code="JOB_CANCELLED",a}};try{var q;let f,h;o("cn_opening_login_page","Opening CodeBuddy CN login page"),p();try{a.setDefaultNavigationTimeout(k),a.setDefaultTimeout(l)}catch{}try{await a.context().route("**/*",a=>{var b,c;let d,e=a.request();return(b=e.url(),c=e.resourceType(),d=String(b||""),/googletagmanager|googleadservices|google-analytics|doubleclick|facebook|hotjar|clarity\.ms|hm\.baidu|google\.com\/rmkt/i.test(d)||"media"===c||"image"===c&&!/captcha|tcaptcha|challenge|verify|qrcode/i.test(d))?a.abort():a.continue()})}catch{}let j=null,r=[];for(let b=1;b<=2;b++){p();try{let c=B[(b-1)%B.length];o("cn_nav_attempt",`Navigation attempt ${b}/2 → ${c}`),b>1&&(await a.context().clearCookies().catch(()=>{}),await a.waitForTimeout(800)),await a.goto(c,{waitUntil:"commit",timeout:k}),p(),await a.waitForFunction(()=>"loading"!==document.readyState,{timeout:1e4}).catch(()=>{}),p();let d=await X(a,E,{timeout:6e3});d&&(await d.click().catch(()=>{}),o("cn_consent_dismissed","Privacy consent dialog dismissed (同意)"),await a.waitForTimeout(1e3));let e=await Y(a,D,25e3);if(p(),!e){let b=await a.locator("body").innerText().catch(()=>""),d=await a.evaluate(()=>document.documentElement?.outerHTML?.length||0).catch(()=>0),e=a.url();o("cn_spa_not_ready",`SPA not ready after 25s (url=${e}, body=${String(b).slice(0,80)}, html=${d})`),!b&&d<200?(o("cn_proxy_empty_page","Empty page body — proxy may be blocking codebuddy.cn"),r.push({code:"proxy_empty",detail:`empty page via ${c} (html=${d})`})):r.push({code:"spa_timeout",detail:`SPA not ready url=${e} html=${d}`});continue}o("cn_spa_ready","Login SPA ready"),o("cn_selecting_phone_tab","Selecting phone-number tab");let f=await X(a,C,{timeout:12e3});if(f?(await f.click().catch(()=>{}),o("cn_phone_tab_selected","Phone tab selected"),await a.waitForTimeout(800)):o("cn_phone_tab_not_found","Phone tab not found — checking if iframe already present"),o("cn_waiting_for_iframe","Waiting for phone iframe to load"),await a.locator(F).waitFor({state:"attached",timeout:18e3}).catch(()=>{}),j=await V(a)){if(await j.waitForSelector(G,{state:"visible",timeout:15e3}).then(()=>!0).catch(()=>!1)){o("cn_iframe_ready","Phone iframe + #phoneNumber ready");break}o("cn_iframe_empty","Iframe found but #phoneNumber not visible yet"),r.push({code:"iframe_empty",detail:"phone iframe attached but #phoneNumber not visible"}),j=null}else o("cn_iframe_missing",`No #phone-iframe (attempt ${b}/2)`),r.push({code:"iframe_missing",detail:"SPA loaded but #phone-iframe never appeared"})}catch(e){if(e?.code==="JOB_CANCELLED")throw e;let a=String(e?.message||e||"");o("cn_nav_retry",`Navigation attempt ${b}/2 failed: ${a.slice(0,120)}`);let c=/timeout|exceeded|ETIMEDOUT|net::ERR/i.test(a),d=/ERR_PROXY|ERR_TUNNEL|ERR_CONNECTION|NS_ERROR_PROXY|proxy/i.test(a);r.push({code:d?"proxy_network":c?"nav_timeout":"nav_error",detail:a.slice(0,160)})}}if(!j)return{status:"failed",error:function(a=[],b=2){let c=a.map(a=>a.code),d=a[a.length-1],e="Fix: use a live residential CN proxy (proxyPoolMode=single), concurrency 1, then retry. 5sim is not charged until the form loads.";return c.includes("proxy_empty")||c.includes("proxy_network")?`CodeBuddy CN login page empty/blocked via proxy after ${b} attempts (${d?.detail||"proxy blackhole"}). ${e}`:c.includes("nav_timeout")?`CodeBuddy CN navigation timed out after ${b} attempts (${d?.detail||"goto timeout"}). Proxy is too slow or dead. ${e}`:c.includes("spa_timeout")?`CodeBuddy CN SPA did not boot after ${b} attempts (${d?.detail||"no login UI"}). Proxy/CDN may be filtering JS. ${e}`:c.includes("iframe_missing")||c.includes("iframe_empty")?`CodeBuddy CN page opened but phone form iframe never appeared after ${b} attempts (${d?.detail||"no #phone-iframe"}). Site layout change or half-loaded SPA — retry with another CN exit IP. ${e}`:c.includes("nav_error")&&d?.detail?`CodeBuddy CN phone form failed after ${b} attempts: ${d.detail}. ${e}`:`Could not load CodeBuddy CN phone form after ${b} attempts (${d?.code||"unknown"}: ${d?.detail||"proxy/SPA"}). ${e}`}(r,2)};await j.waitForSelector("#kc-form-login",{timeout:l}).catch(()=>{}),await j.waitForSelector(G,{state:"visible",timeout:l}).catch(()=>{});let s=b;if("function"==typeof c&&(o("cn_ordering_after_form","Login form ready — ordering 5sim number now (not before nav)"),s=await c()),!s)return{status:"failed",error:"No phone number available (resolvePhone/phone missing)"};let t=g(s),{countryCode:u,localNumber:v}=(q=t,(!(h=String(q).replace(/[\s\-()]/g,"")).startsWith("+")&&/^\d+$/.test(h)&&(h="+"+h),h.startsWith("+852"))?{countryCode:"+852",localNumber:h.slice(4)}:h.startsWith("+86")?{countryCode:"+86",localNumber:h.slice(3)}:h.startsWith("+1")?{countryCode:"+1",localNumber:h.slice(2)}:{countryCode:"",localNumber:h.replace(/^\+/,"")});if(o("cn_selecting_country",`Selecting country code ${u} for phone ${t}`),!await W(j,u,l,o))return{status:"failed",error:`Could not select country code ${u||"(unknown)"} for ${t}`};o("cn_entering_phone",`Entering phone number: ${v}`);let w=j.locator(G).first();try{await w.waitFor({state:"visible",timeout:l})}catch{return{status:"failed",error:"Could not find the phone number input (#phoneNumber) inside the iframe"}}if(!await Z(w,v))return{status:"failed",error:"Phone number input did not retain the expected value"};o("cn_phone_entered",`Phone number entered: ${v}`);let x=await R(a);if(!x.ok)return{status:"failed",error:"Could not keep the service agreement checkbox checked"};x.present&&o("cn_agreement_checked",x.changed?"Agreement checkbox checked":"Agreement checkbox already checked"),o("cn_clicking_send_code","Clicking send SMS code button");let y=await Q(j);if("missing"===y.reason)return{status:"failed",error:"Could not find the send-SMS-code button (.code-btn) inside the iframe"};if(!y.ok)return{status:"failed",error:"Could not click the send-SMS-code button (.code-btn) inside the iframe"};o("cn_send_code_clicked","Send code button clicked");let z=await S(j),A=await ad(j);if(A)return{status:"failed",error:`Form error after sending code: ${A}`};if(!z.ok)return{status:"failed",error:"Tencent did not acknowledge the SMS-code request (no disabled/countdown state)"};o("cn_send_code_acknowledged","Tencent accepted the SMS-code request"),o("cn_waiting_for_sms","Waiting for SMS verification code from 5sim (timer starts now)");try{let a;if("function"==typeof e)a=Promise.resolve().then(()=>e());else if(d)a=d;else throw Error("No waitForSms/pollSmsPromise provided");f=await T(a,{timeoutMs:m,signal:i})}catch(a){if(a&&"FiveSimTimeoutError"===a.name)throw a;return(i?.aborted||a?.code==="JOB_CANCELLED")&&p(),{status:"failed",error:`Failed to receive SMS code: ${a.message}`}}if(!f)return{status:"failed",error:"Received empty SMS code from 5sim"};o("cn_sms_received",`SMS code received: ${f}`),o("cn_entering_code","Entering SMS verification code");let H=j.locator(J).first();try{await H.waitFor({state:"visible",timeout:l})}catch{return{status:"failed",error:"Could not find the verification code input (#code) inside the iframe"}}if(!await Z(H,f))return{status:"failed",error:"Verification code input did not retain the expected value"};o("cn_code_entered","Verification code entered");let I=1200+Math.floor(1800*Math.random());o("cn_pre_submit_pause",`Waiting ${I}ms before submit (humanize)`),await a.waitForTimeout(I);let K=Math.max(n,12e3);o("cn_submitting","Submitting the registration form once");let L=await V(a);if(!L)return{status:"failed",error:"Lost phone iframe before submit"};let M=await aa(L,l);if(!M.ok)return{status:"failed",error:"Could not submit the Keycloak login form"};if(o("cn_submitted",`Registration form submitted once via ${M.method}`),await a.waitForLoadState("domcontentloaded",{timeout:5e3}).catch(()=>{}),await a.waitForTimeout(1800),L=await V(a)||L,await ac(a,L))return o("cn_account_restricted","Account restricted after the OTP submit"),P("restriction message detected");if(o("cn_checking_captcha","Checking for captcha"),await ae(a,L,3e3))return o("cn_captcha_detected","Captcha appeared during registration - manual assist needed"),{status:"needs_manual",error:"A captcha appeared during registration. Complete it in the existing browser session.",captcha:!0};let O=await ad(L);if(O)return{status:"failed",error:`Form error after submit: ${O}`};o("cn_waiting_session",`Waiting up to ${Math.round(K/1e3)}s for Keycloak session cookies`);let U=await _(a,{timeoutMs:K,reportStep:o,alsoCheckFrame:()=>V(a)});if(U.ok)return o("cn_session_cookies",`Keycloak session cookies present (${U.cookie}) - registration success`),{status:"success"};if("restricted"===U.reason||function(a=[]){return a.some(a=>N.has(a?.name))}(U.cookies))return o("cn_account_restricted","Restriction detected while waiting for the login session"),P("restriction evidence detected during session handoff");if(L=await V(a)||L,await ae(a,L,2e3))return o("cn_captcha_detected","Captcha appeared while waiting for the login session"),{status:"needs_manual",error:"A captcha appeared while establishing the login session. Complete it in the existing browser.",captcha:!0};let $=await ab(a);return o("cn_success_unconfirmed",`No Keycloak session after submit — ${$.summary}`),{status:"needs_manual",error:`Login submit finished but no Keycloak session yet (${$.summary}). Complete login in the headed browser or retry with a fresh China proxy.`}}catch(a){if((i?.aborted||"function"==typeof j&&j())&&p(),a&&"FiveSimTimeoutError"===a.name||a?.code==="JOB_CANCELLED"||a?.code==="CN_ACCOUNT_HARD_TIMEOUT")throw a;return o("cn_automation_error",`Phone registration automation error: ${a.message}`),{status:"failed",error:a.message||"Unexpected error during phone registration"}}}async function V(a){try{await a.locator(F).waitFor({state:"attached",timeout:5e3});let b=await a.locator(F).elementHandle({timeout:2e3});if(b){let a=await b.contentFrame();if(a)return a}}catch{}for(let b of a.frames()){let a=b.url();if(a.includes("codebuddy.cn/auth/realms/copilot")||a.includes("protocol/openid-connect"))return b}return null}async function W(a,b,c,d){if(!b)return!1;let e=Math.min(Number(c)||15e3,1e4),f=async()=>{let c=a.locator(I).first(),f=String(await c.textContent({timeout:3e3}).catch(()=>"")).trim();if(f===b)return d?.("cn_country_already_selected",`Country code already ${b}`),!0;d?.("cn_opening_country_dropdown",`Opening country dropdown (current: ${f}, target: ${b})`);let g=a.locator(".kc-country-selector").first();for(let c of(await g.waitFor({state:"visible",timeout:Math.min(e,5e3)}),await g.click({timeout:3e3}).catch(()=>{}),await a.locator(H).first().waitFor({state:"visible",timeout:3e3}).catch(()=>{}),({"+852":["中国香港","香港","Hong Kong","+852"],"+86":["中国大陆","中国","China","+86"],"+853":["中国澳门","澳门","Macau","+853"],"+886":["中国台湾","台湾","Taiwan","+886"]})[b]||[b]))for(let e of[a.locator(`${H}:has-text("${c}")`).first(),a.getByText(c,{exact:!1}).first()]){if(!await e.isVisible({timeout:1500}).catch(()=>!1))continue;let f=await e.textContent({timeout:1500}).catch(()=>c);if(await e.click({timeout:2e3}).then(()=>!0).catch(()=>!1)&&await a.locator(I).filter({hasText:b}).first().waitFor({state:"visible",timeout:2e3}).then(()=>!0).catch(()=>!1))return d?.("cn_country_selected",`Country selected: ${String(f||c).trim()}`),!0}return d?.("cn_country_not_found",`Country code ${b} not found in dropdown`),await a.locator("body").click({timeout:1e3}).catch(()=>{}),!1},g=null;try{return await Promise.race([f(),new Promise((a,b)=>{g=setTimeout(()=>b(Error(`selectCountry timed out after ${e}ms`)),e),g.unref?.()})])}catch(a){return d?.("cn_country_select_error",`Country selection error: ${a.message}`),!1}finally{g&&clearTimeout(g)}}async function X(a,b,{timeout:c=1e4}={}){for(let d of b)try{let b=a.locator(d).first();return await b.waitFor({state:"visible",timeout:Math.min(c,5e3)}),b}catch{}return null}async function Y(a,b,c=15e3){let d=Date.now()+c;for(;Date.now()<d;){for(let c of b)try{let b=a.locator(c).first();if(await b.isVisible().catch(()=>!1))return!0}catch{}await new Promise(a=>setTimeout(a,250))}return!1}async function Z(a,b){let c=String(b??""),d=async()=>await a.inputValue().catch(()=>null)===c;try{if(await a.click(),await a.fill(""),await a.fill(c),await d())return!0}catch{}try{return await a.click(),await a.press("ControlOrMeta+a"),await a.type(c,{delay:50}),d()}catch{return!1}}let $=["KEYCLOAK_IDENTITY","KEYCLOAK_SESSION","KEYCLOAK_IDENTITY_LEGACY","KEYCLOAK_SESSION_LEGACY"];async function _(a,{timeoutMs:b=2e4,reportStep:c,alsoCheckFrame:d}={}){let e=Date.now()+b,f=0;for(;Date.now()<e;){let b=await a.context().cookies().catch(()=>[]),g=function(a=[]){for(let b of $)if(a.some(a=>a.name===b))return b;let b=a.find(a=>a.name.startsWith("KEYCLOAK_")&&!/locale|theme|restart/i.test(a.name));return b?.name||null}(b);if(g)return{ok:!0,cookie:g,cookies:b};try{let c=a.url();if(c&&!c.includes("/login")&&!c.includes("/auth/realms")){let a=b.find(a=>/^(access_token|cb_token|codebuddy)/i.test(a.name)||"token"===a.name&&a.domain?.includes("codebuddy"));if(a)return{ok:!0,cookie:a.name,cookies:b}}}catch{}let h=d?await d().catch(()=>null):null;if(await ac(a,h))return{ok:!1,cookies:b,reason:"restricted"};if(h){let a=await ad(h);if(a)return{ok:!1,cookies:b,reason:`form_error:${a}`}}if(c&&Date.now()-f>4e3){f=Date.now();let a=Math.max(0,Math.round((e-Date.now())/1e3));c("cn_waiting_session",`Still waiting for Keycloak session… ${a}s left`)}await a.waitForTimeout(500)}return{ok:!1,cookies:await a.context().cookies().catch(()=>[])}}async function aa(a,b=15e3){let c=a.locator("#kc-login").first();try{return await c.waitFor({state:"visible",timeout:b}),await c.click({timeout:5e3}),{ok:!0,method:"click"}}catch{}try{return await a.evaluate(()=>{let a=document.querySelector("#kc-form-login")||document.querySelector("form");if(!a)return!1;if("function"==typeof a.requestSubmit){let b=a.querySelector("#kc-login")||a.querySelector('[type="submit"]');b?a.requestSubmit(b):a.requestSubmit()}else a.submit();return!0})?{ok:!0,method:"requestSubmit"}:{ok:!1,method:null}}catch{let b=await a.locator(J).first().press("Enter").then(()=>!0).catch(()=>!1);return{ok:b,method:b?"enter":null}}}async function ab(a){let b="";try{b=a.url()}catch{b="(unknown)"}let c=(await a.context().cookies().catch(()=>[])).map(a=>a.name).slice(0,20).join(",")||"(none)",d="";try{d=await a.evaluate(()=>(document.body?.innerText||"").replace(/\s+/g," ").trim().slice(0,120))}catch{d=""}let e=await V(a),f="no-iframe";if(e)try{f=(await e.url()).slice(0,80)}catch{f="iframe-detached"}return{summary:`url=${b.slice(0,60)} cookies=[${c}] frame=${f}${d?` text="${d}"`:""}`,url:b,cookieNames:c,bodySnippet:d}}async function ac(a,b){for(let c of[b,a])if(c)try{let a=await c.evaluate(()=>document.body?.innerText||"");if(function(a){let b=String(a||"").toLowerCase();return O.some(a=>b.includes(a.toLowerCase()))}(a))return!0}catch{}return!1}async function ad(a){for(let b of M)try{let c=a.locator(b).first();if(await c.isVisible({timeout:1500}).catch(()=>!1)){let a=await c.textContent().catch(()=>""),b=String(a).trim();if(b&&b.length>1)return b}}catch{}try{let b=await a.evaluate(()=>(document.body?.innerText||"").replace(/\s+/g," ").trim());for(let a of["验证码错误","验证码已过期","验证码无效","请输入正确的验证码","手机号格式","发送过于频繁","Invalid","incorrect"])if(b.includes(a)){let c=b.indexOf(a);return b.slice(Math.max(0,c-10),c+a.length+40).trim()}}catch{}return null}async function ae(a,b,c=5e3){for(let b of L)try{let d=a.locator(b).first();if(await d.isVisible({timeout:Math.min(c,2e3)}).catch(()=>!1))return!0}catch{}if(b)for(let a of L)try{let d=b.locator(a).first();if(await d.isVisible({timeout:Math.min(c,2e3)}).catch(()=>!1))return!0}catch{}return!1}var af=c(40891),ag=c(75949);let ah=200,ai=Number.parseInt(process.env.ZEVAI_CN_ACCOUNT_TIMEOUT_MS||"",10)||3e5,aj="CN_API_KEY_OUTCOME_UNKNOWN",ak="CN_API_KEY_AUTOMATIC_RETRY_STOPPED",al="CN_ACCOUNT_RESTRICTED",am=new Set(["KEYCLOAK_IDENTITY","KEYCLOAK_SESSION","KEYCLOAK_IDENTITY_LEGACY","KEYCLOAK_SESSION_LEGACY"]),an=new Set(["hongkong","china"]),ao="hongkong",ap=new Set(["queued","running","needs_manual"]),aq=new Set(["queued","running","needs_manual"]);function ar(a){return String(a||"").trim()}function as(a,b,c){return a.manualSession={context:b,page:c,opened:!1,openedAt:null},a.manualSession}function at(){try{let{totalMemGb:a}=(0,l.si)();return Number.isFinite(a)&&a>0&&a<3}catch{return!1}}function au(a){return!!a?.proxyUrls?.length&&["manual","all","single"].includes(a?.proxyPoolMode)}async function av(a,{timeoutMs:b=6e3}={}){let c=null;try{c=a?.request||null}catch{c=null}if(!c||"function"!=typeof c.get)return{ok:!1,ip:null,ips:[],samples:0,error:"context request unavailable"};let d=[],e=null;for(let a of ag.PROXY_EGRESS_ECHO_URLS){d.push(a);let g=null;try{var f;if(g=await c.get(a,{timeout:b,failOnStatusCode:!1,headers:{Accept:"text/plain, application/json;q=0.9, */*;q=0.1","Cache-Control":"no-cache"}}),200>g.status()||g.status()>=300){e=`HTTP ${g.status()}`;continue}let h=(f=await g.text().catch(()=>""),(0,ag.parseProxyEgressIp)(f));if(!h){e="exit-IP response was not recognized";continue}return{ok:!0,ip:h,ips:[h],samples:1,attempts:d.length,attemptedUrls:d,unstable:!1,error:null}}catch(a){e=a?.name==="TimeoutError"?`timed out after ${b}ms`:"request failed"}finally{"function"==typeof g?.dispose&&await Promise.resolve(g.dispose()).catch(()=>null)}}return{ok:!1,ip:null,ips:[],samples:0,attempts:d.length,attemptedUrls:d,unstable:!1,error:e||"all exit-IP services failed"}}function aw(a,b=null){if(a?.unstable)throw Object.assign(Error("Manual proxy rotated between exit IPs during preflight; no phone number was purchased"),{code:"CN_PROXY_EGRESS_UNSTABLE"});if(!a?.ok||!a?.ip)throw Object.assign(Error(`Manual proxy exit IP could not be verified (${a?.error||"no response"}); no phone number was purchased`),{code:"CN_PROXY_EGRESS_UNVERIFIED"});if(b&&a.ip!==b)throw Object.assign(Error("Manual proxy browser exit IP changed before the 5sim purchase; no phone number was purchased"),{code:"CN_PROXY_EGRESS_CHANGED"});return a.ip}async function ax(a,{timeoutMs:b,message:c,code:d,onTimeout:e,onLateResolve:f}){let g=Promise.resolve(a),h=null,i=!1,j=new Promise((a,f)=>{"function"==typeof(h=setTimeout(()=>{i=!0;try{"function"==typeof e&&e()}catch{}f(Object.assign(Error(c),{code:d}))},b)).unref&&h.unref()});try{return await Promise.race([g,j])}finally{h&&clearTimeout(h),i&&"function"==typeof f&&g.then(f).catch(()=>null)}}function ay(a,b="API key request"){let c=Number(a?.status);if(429===c)throw Object.assign(Error(`${b} was rate limited (HTTP 429); automatic POST retries stopped`),{code:ak});if(Number.isFinite(c)&&c>=500)throw Object.assign(Error(`${b} returned HTTP ${c}; creation outcome may be unknown and automatic POST retries stopped`),{code:aj});return a}function az(a){let b=`${a?.text||""} ${a?.data?._raw||""} ${a?.url||""}`;return/<!doctype html|<html|login-pf|\/auth\/realms\//i.test(b)}function aA(a=[]){let b=a instanceof Set?a:new Set(Array.from(a,a=>"string"==typeof a?a:a?.name));return[...am].some(a=>b.has(a))}function aB(a,b=[]){let c=b instanceof Set?b:new Set(b),d=`${a?.text||""} ${a?.data?._raw||""}`;return!!/账号访问受限|安全策略限制|访问受限|account restricted|access restricted/i.test(d)||!!c.has("login_risk_state")&&(az(a)||a?.status===0||a?.status===401||a?.status===403)}async function aC({context:a,page:b,timeoutMs:c=1e4}){let d={Accept:"application/json, text/plain, */*","x-requested-with":"XMLHttpRequest","X-Domain":"www.codebuddy.cn","X-Product":"SaaS"},e=null;try{e=a?.request||null}catch{e=null}if(e&&"function"==typeof e.get)try{let a=await e.get("https://www.codebuddy.cn/console/accounts",{headers:d,timeout:c,failOnStatusCode:!1}),b=await a.text().catch(()=>"");return function(a,b,c={}){let d=String(b||""),e=null;try{e=d?JSON.parse(d):null}catch{e={_raw:d.slice(0,240),_notJson:!0}}return{status:Number(a)||0,data:e,text:d.slice(0,240),...c}}(a.status(),b,{source:"context-request",url:a.url(),contentType:a.headers()?.["content-type"]||""})}catch{}return ax(b.evaluate(async({requestTimeoutMs:a,requestHeaders:b})=>{let c=new AbortController,d=setTimeout(()=>c.abort(),a);try{let a=window.location.hostname||"www.codebuddy.cn",d="www.codebuddy.cn"===a?`${window.location.origin}`:"https://www.codebuddy.cn",e=await fetch(`${d}/console/accounts`,{credentials:"include",signal:c.signal,headers:b}),f=await e.text().catch(()=>""),g=null;try{g=f?JSON.parse(f):null}catch{g={_raw:String(f||"").slice(0,240),_notJson:!0}}return{status:e.status,data:g,text:String(f||"").slice(0,240),source:"page-fetch",url:e.url,contentType:e.headers.get("content-type")||""}}catch(a){return{status:0,timedOut:a?.name==="AbortError",error:a?.message||String(a),source:"page-fetch"}}finally{clearTimeout(d)}},{requestTimeoutMs:c,requestHeaders:d}),{timeoutMs:c,message:`Console account probe timed out after ${c/1e3}s`,code:"CN_CONSOLE_PROBE_TIMEOUT"}).catch(a=>({status:0,timedOut:a?.code==="CN_CONSOLE_PROBE_TIMEOUT",error:a?.message||String(a),source:"page-fetch"}))}async function aD(a){if(!a||"function"!=typeof a.close)return!0;try{return await ax(Promise.resolve().then(()=>a.close()),{timeoutMs:5e3,message:"Browser resource close timed out after 5s",code:"CN_RESOURCE_CLOSE_TIMEOUT"}),!0}catch{return!1}}async function aE(a,b){if(await aD(a)||!b?.browser)return;let c=b.browser;b.browser=null,await (0,ag.forceCloseBrowser)(c).catch(()=>null)}async function aF(a){try{return await ax(Promise.resolve().then(a),{timeoutMs:12e3,message:"5sim order settlement timed out after 12s",code:"CN_FIVESIM_SETTLE_TIMEOUT"})}catch{return!1}}async function aG({apiKey:a,phone:b,region:d,fiveSimOrderId:e,account:f}){let{createProviderConnection:g}=await Promise.resolve().then(c.bind(c,71998)),h={provider:"codebuddy-cn",authType:"apikey",apiKey:a,accessToken:a,name:b||`5sim-${e}`,email:b||`5sim-${e}`,providerSpecificData:{domain:"www.codebuddy.cn",phoneNumber:b,fiveSimOrderId:e,region:d,automation:"5sim-phone-bulk"},testStatus:"active"};return{connection:await g(h)}}class aH extends i.Q6{constructor({browserLauncher:a,requestDeviceCodeFn:b=af.cT,pollToken:d=af.ZV,fetchLoginAccountFn:e=af.w8,saveConnection:g=aG,fiveSimClientFactory:i=aI,phoneAutomation:j=U,phoneFormatter:k=ar,pollIntervalMs:l=n.ne.pollInterval,storageName:m="codebuddy-cn-bulk-import"}={}){super({browserLauncher:a||(async a=>{let{forceCloseBrowser:b,launchBulkImportBrowser:d}=await Promise.resolve().then(c.bind(c,75949)),e=Array.isArray(a?.proxyUrls)&&a.proxyUrls.length?a.proxyUrls[0]:null,f=process.env.ZEVAI_CN_HEADLESS,g=!1;return("0"===f||"false"===f)&&(g=!1),("1"===f||"true"===f)&&(g=!0),ax(d({engine:a?.engine||"cloakbrowser",proxyUrl:e,headless:g,windowSize:{width:1280,height:900},requireProxyGeoip:a?.proxyPoolMode==="manual"&&!!e}),{timeoutMs:9e4,message:"CloakBrowser launch timed out after 90s",code:"CN_BROWSER_LAUNCH_TIMEOUT",onLateResolve:a=>b(a)})}),storageName:m}),this.latestJobId&&this.readPersistedJob(this.latestJobId)||(this.latestJobId=function(a){try{let b=f().readdirSync(a).filter(a=>a.endsWith(".json")&&"meta.json"!==a).map(b=>{let c=h().join(a,b);try{let a=JSON.parse(f().readFileSync(c,"utf8"));if(!a?.jobId)return null;let b=Date.parse(a.createdAt||""),d=Number.isFinite(b)?b:f().statSync(c).mtimeMs;return{jobId:a.jobId,sortTime:d}}catch{return null}}).filter(Boolean).sort((a,b)=>b.sortTime-a.sortTime);return b[0]?.jobId||null}catch{return null}}(this.storageDir),this.latestJobId&&this.persistLatestJobId(this.latestJobId)),this.requestDeviceCode=b,this.pollToken=d,this.fetchLoginAccount=e,this.saveConnection=g,this.fiveSimClientFactory=i,this.phoneAutomation=j,this.phoneFormatter=k,this.pollIntervalMs=l}async startJob({count:a,concurrency:b,proxyPoolMode:c,proxyPoolId:e,manualProxyUrl:f,region:g}){let h=Number.parseInt(a,10);if(!Number.isFinite(h)||h<1)throw Object.assign(Error("At least one account is required (count >= 1)"),{error:"At least one account is required (count >= 1)"});if(h>ah)throw Object.assign(Error(`Count exceeds maximum of ${ah}`),{error:`Count exceeds maximum of ${ah}`});this.latestJobId&&!this.jobs.has(this.latestJobId)&&this.getJob(this.latestJobId);let k=[...this.jobs.values()].find(a=>a&&("running"===a.status||"queued"===a.status||"needs_manual"===a.status)&&!a.cancelRequested);if(k)throw Object.assign(Error(`Another CodeBuddy CN job is still active (${k.jobId}). Cancel it or wait before starting again.`),{error:`Another CodeBuddy CN job is still active (${k.jobId}). Cancel it or wait before starting again.`});let m=an.has(g)?g:ao,n=[],o="string"==typeof f?f.trim():"";if(o){if(!/^(https?|socks4|socks5):\/\/.+/i.test(o))throw Object.assign(Error("manualProxyUrl must be a valid proxy URL (http://, https://, socks4://, or socks5://)"),{error:"manualProxyUrl must be a valid proxy URL (http://, https://, socks4://, or socks5://)"});n=[o]}else if("all"===c)n=(await (0,j.ui)({isActive:!0})).map(a=>a.proxyUrl).filter(Boolean);else if("single"===c&&e){let a=await (0,j.hr)(e);a?.isActive&&a?.proxyUrl&&(n=[a.proxyUrl])}o||function(a,b){if(!["all","single"].includes(a)||b.length>0)return;let c="single"===a?"Selected proxy is missing or inactive; no automation was started":"No active proxies are available in the selected pool; no automation was started";throw Object.assign(Error(c),{error:c,code:"CN_PROXY_SELECTION_EMPTY"})}(c,n);let p=(0,d.randomUUID)(),q=(0,i.kF)(),r={jobId:p,status:"running",concurrency:function(a,{manualProxy:b=!1,processBoundProxy:c=!1}={}){return b||c?1:function(a){let b=at()?1:8;if((0,l.uT)(a))return Math.min(b,Math.max(1,(0,l.q)()));let c=Number.parseInt(a,10);return Number.isFinite(c)?Math.min(b,Math.max(1,c)):Math.min(b,1)}(a)}(b,{manualProxy:!!o,processBoundProxy:n.length>0}),proxyPoolMode:o?"manual":c||"none",proxyUrls:n,region:m,createdAt:q,startedAt:q,finishedAt:null,error:null,cancelRequested:!1,browser:null,nextIndex:0,manualFollowups:new Set,persistPromise:Promise.resolve(),lastPreview:null,lastPreviewCapturedAt:0,accounts:Array.from({length:h},(a,b)=>({line:b+1,region:m,phone:null,fiveSimOrderId:null,fiveSimActivationId:null,fingerprintSeed:(0,d.randomUUID)(),proxyUrl:null,egressIp:null,proxyTimezone:null,proxyLocale:null,abortController:new AbortController,status:"queued",error:null,connectionId:null,workerId:null,manualSession:null,runtimeSession:null,currentStep:"queued",updatedAt:q,logs:[(0,i.hn)("queued","Queued and waiting for an available worker")]}))};return this.jobs.set(p,r),this.latestJobId=p,this.persistLatestJobId(p),await this.persistJobSnapshot(r,{forcePreview:!1}),this.runJob(p),aK(r)}buildPersistedSnapshot(a){return aK(a,{preview:a.lastPreview||null})}terminalizeInterruptedSnapshot(a){if(!a||!ap.has(a.status))return a;let b="CodeBuddy CN job was interrupted by a service restart. Browser and OTP sessions cannot be resumed safely; start a new job.",c=(a.accounts||[]).map(a=>{if(!aq.has(a.status))return a;let c=(0,i.hn)("failed",b,"error");return{...a,status:"failed",error:b,currentStep:"failed",updatedAt:c.at,manualSessionAvailable:!1,logs:[...a.logs||[],c].slice(-40)}}),d={...a,status:"failed",error:a.error||b,finishedAt:a.finishedAt||(0,i.kF)(),accounts:c,summary:aJ(c),preview:null};return this.writePersistedJob(a.jobId,d),d}getJob(a){let b=this.jobs.get(a);if(b)return aK(b);let c=this.readPersistedJob(a);return c?this.terminalizeInterruptedSnapshot(c):null}async getJobWithPreview(a){let b=this.jobs.get(a);return b?(await this.persistJobSnapshot(b,{forcePreview:!1}),aK(b,{preview:b.lastPreview||null})):this.getJob(a)}async processAccount(a,b,c){if(a.cancelRequested||!a.browser)return void this.finalizeAccount(b,"cancelled",{error:"Job cancelled"});let d=null,e=null,f=!1,g=null,h=null;try{let c;this.setAccountStep(b,"reading_settings","Reading 5sim API key from settings"),await this.persistJobSnapshot(a,{forcePreview:!0});let j=(await (0,k.mt)()).fiveSimApiKey;if(!j||!j.trim()){this.finalizeAccount(b,"failed",{error:"5sim API key not configured. Set it in the automation modal or dashboard settings.",step:"failed",message:"5sim API key not configured"}),await this.persistJobSnapshot(a,{forcePreview:!0});return}d=this.fiveSimClientFactory({apiKey:j,proxyOptions:null}),this.setAccountStep(b,"creating_browser","Creating browser context (before 5sim order)"),await this.persistJobSnapshot(a,{forcePreview:!0});let l=(0,i.go)(a.browser,b.proxyUrl,{profile:"codebuddy-cn",region:a.region||"hongkong",fingerprintSeed:b.fingerprintSeed,lowMemory:at(),nativeCloakProfile:au(a)&&!!b.proxyUrl}),m=await ax(l,{timeoutMs:3e4,message:"Browser context creation timed out after 30s",code:"CN_CONTEXT_TIMEOUT",onLateResolve:a=>Promise.resolve(a?.context?.close?.()).catch(()=>null)});g=m.context;let n=m.page;if(b.runtimeSession={context:g,page:n},"manual"===a.proxyPoolMode&&b.proxyUrl){this.setAccountStep(b,"checking_proxy_egress","Verifying pasted proxy exit IP before opening the registration form"),await this.persistJobSnapshot(a,{forcePreview:!1});let c=(0,ag.getCloakProxyProfile)(a.browser),d=await av(g);b.egressIp=h=aw(d),b.proxyTimezone=c?.timezone||null,b.proxyLocale=c?.locale||null,this.setAccountStep(b,"proxy_egress_ready",`Manual proxy verified: ${h} (${d.samples} checks, ${b.proxyTimezone||"timezone unknown"}, ${b.proxyLocale||"locale unknown"})`),await this.persistJobSnapshot(a,{forcePreview:!1})}if(a.cancelRequested)throw Error("Job cancelled before ordering phone number");this.setAccountStep(b,"registering","Running phone registration on CodeBuddy CN"),await this.persistJobSnapshot(a,{forcePreview:!0});try{n.setDefaultTimeout(2e4),n.setDefaultNavigationTimeout(45e3)}catch{}let o=null,p=new Promise((a,c)=>{o=setTimeout(()=>{let a=Object.assign(Error(`CodeBuddy CN account hard timeout after ${Math.round(ai/1e3)}s (browser will be force-closed)`),{code:"CN_ACCOUNT_HARD_TIMEOUT"});b.abortController&&!b.abortController.signal.aborted&&b.abortController.abort(a),c(a)},ai),"function"==typeof o.unref&&o.unref()});try{c=await Promise.race([this.phoneAutomation({page:n,signal:b.abortController?.signal,isCancelled:()=>!0===a.cancelRequested,resolvePhone:async()=>{if(a.cancelRequested)throw Error("Job cancelled before ordering phone number");if("manual"===a.proxyPoolMode&&b.proxyUrl){this.setAccountStep(b,"rechecking_proxy_egress","Registration form is ready — confirming the pasted proxy stayed sticky"),await this.persistJobSnapshot(a,{forcePreview:!1});let c=await av(g);aw(c,h),this.setAccountStep(b,"proxy_egress_confirmed",`Manual proxy remained on ${h}; safe to purchase one phone number`),await this.persistJobSnapshot(a,{forcePreview:!1})}this.setAccountStep(b,"ordering_number",`Form ready — ordering ${a.region} phone from 5sim (single buy)`),await this.persistJobSnapshot(a,{forcePreview:!0});let c=await d.buyNumber({country:a.region,product:"codebuddy",allowProductFallback:!1,signal:b.abortController?.signal});return e=c.id,b.phone=c.phone,b.fiveSimOrderId=c.id,b.fiveSimActivationId=c.id,this.setAccountStep(b,"number_ordered",`Phone number ordered: ${c.phone} (1 buy, no re-order)`),await this.persistJobSnapshot(a,{forcePreview:!0}),c.phone},waitForSms:async()=>{if(!e)throw Error("Cannot poll SMS — no 5sim order id");this.setAccountStep(b,"sms_poll_started","SMS poll started (full 90s window after send-code)"),await this.persistJobSnapshot(a,{forcePreview:!1});let c=await d.pollCode(e,{timeoutMs:9e4,signal:b.abortController?.signal});return f=!0,c},onStep:(c,d)=>{this.setAccountStep(b,c,d),this.persistJobSnapshot(a,{forcePreview:!1})},phoneFormatter:this.phoneFormatter}),p])}finally{o&&clearTimeout(o)}if(String(c.status||"").startsWith("failed")){let h=c.error||"Phone registration failed before submit",i=c.status||"failed";this.finalizeAccount(b,i,{error:h,step:i,message:h}),d&&e&&(f?await aF(()=>d.finishOrder(e)):await aF(()=>d.cancelOrder(e))),b.runtimeSession=null,await aE(g,a),await this.persistJobSnapshot(a,{forcePreview:!0});return}if("needs_manual"===c.status){as(b,g,n),this.finalizeAccount(b,"needs_manual",{error:c.error||"Manual completion is required",step:"awaiting_manual",message:c.error||"Complete the existing CodeBuddy login session manually"}),d&&e&&f&&await aF(()=>d.finishOrder(e)),await this.persistJobSnapshot(a,{forcePreview:!0}),await this.runCnManualFollowup(a,b,b.workerId,g,n,d,e);return}if("success"!==c.status)throw Error(`Unexpected phone automation status: ${c.status||"unknown"}`);await this.captureApiKey(a,b,g,n,d,e);return}catch(j){let c=j instanceof t,h=a.cancelRequested||j?.code==="JOB_CANCELLED",i=h?"Job cancelled":c?"SMS OTP not received within 90s — number banned":j.message||"Unexpected CodeBuddy CN bulk import failure";if(this.finalizeAccount(b,h?"cancelled":"failed",{error:i,step:h?"cancelled":c?"sms_timeout":"failed",message:i}),d&&e&&(f?await aF(()=>d.finishOrder(e)):c?await aF(()=>d.banOrder(e)):await aF(()=>d.cancelOrder(e))),b.runtimeSession=null,await aE(g,a),(j?.code==="CN_ACCOUNT_HARD_TIMEOUT"||j?.code==="CN_CONTEXT_TIMEOUT"||a.cancelRequested)&&a.browser){let b=a.browser;a.browser=null,await (0,ag.forceCloseBrowser)(b).catch(()=>null)}await this.persistJobSnapshot(a,{forcePreview:!0})}}async captureApiKey(a,b,c,d,e,f){let g="personal-edition-user-id",h=null,i=async(a,{timeout:b=12e3,interval:c=150}={})=>{let d=Date.now()+b;for(;Date.now()<d;){try{if(await a())return!0}catch{}await new Promise(a=>setTimeout(a,c))}return!1};try{this.setAccountStep(b,"waiting_session","Establishing CodeBuddy console session (probe APIs, not just cookies)"),await this.persistJobSnapshot(a,{forcePreview:!0});let j=async()=>{let a=await c.cookies().catch(()=>[]);return{cookies:a,names:new Set(a.map(a=>a.name)),list:a.map(a=>a.name)}},k=a=>a.has("AUTH_SESSION_ID")||a.has("session")||a.has("qcloud_uid")||a.has("qcmainCSRFToken")||a.has("x_host_key_access"),l=()=>aC({context:c,page:d}),m=a=>{let b=a?.data;if(!b||"object"!=typeof b)return[];for(let a of[b?.data?.accounts,b?.accounts,b?.data?.list,b?.list,b?.data?.result,b?.result,b?.data?.items,b?.items,Array.isArray(b?.data)?b.data:null,Array.isArray(b)?b:null])if(Array.isArray(a)&&a.length>0)return a;return[]},n=async(a=2500)=>{let b=!1,c=null;try{await Promise.race([d.waitForLoadState("domcontentloaded",{timeout:a}).catch(()=>null),i(async()=>{if(b)return!0;let a=await j();return aA(a.names)},{timeout:a,interval:200}),new Promise(b=>{c=setTimeout(b,a)})])}finally{b=!0,c&&clearTimeout(c)}},o=async a=>{let b=Date.now();try{await d.goto(a,{waitUntil:"commit",timeout:18e3});let c=18e3-(Date.now()-b);return c>0&&await n(Math.min(2500,c)),!0}catch{return!1}},p=["https://www.codebuddy.cn/","https://www.codebuddy.cn/console","https://www.codebuddy.cn/console/","https://www.codebuddy.cn/profile","https://www.codebuddy.cn/profile/keys"],q=[],r=null,s=!1,t="",u=null,v=0;for(let c=0;c<6;c+=1){if(a.cancelRequested)throw Error("Job cancelled while establishing session");let e=await j(),f=aA(e.names),g=k(e.names),h=p[Math.min(c,p.length-1)];c<3||c%2==0||!g?(this.setAccountStep(b,"waiting_session",`OIDC handoff ${c+1}/6 → ${h.replace("https://www.codebuddy.cn","")} (${f?"KEYCLOAK":g?"soft-session":"weak"})`),await this.persistJobSnapshot(a,{forcePreview:!1}),await o(h)):await new Promise(a=>setTimeout(a,300)),/^https:\/\/www\.codebuddy\.cn(?:[/:]|$)/i.test(d.url?.()||"")||await o("https://www.codebuddy.cn/console"),r=await l(),q=m(r),(r?.status>0||r?.text||r?.data)&&(u=r),t=JSON.stringify(r?.data??r?.text??r?.error??null).slice(0,180);let i=az(r),n=await j();if(!aA(n.names)&&aB(r,n.names)?v+=1:v=0,v>=2)throw Object.assign(Error(`Tencent restricted the post-OTP session (${v} console probes returned login/risk evidence; source=${r?.source||"unknown"})`),{code:al});if(r?.status===200&&!i&&Array.isArray(q)&&q.length>0){s=!0,this.setAccountStep(b,"session_ready",`Console session accepted (HTTP 200, ${q.length} account(s)${f?", KEYCLOAK ok":", soft session"})`),await this.persistJobSnapshot(a,{forcePreview:!0});break}if(g&&r?.status===200&&!i&&r?.data?._notJson!==!0&&Array.isArray(q)&&0===q.length&&c>=3){this.setAccountStep(b,"session_soft","Console HTTP 200 but 0 accounts — trying personal API key with soft session (cookies ok)"),await this.persistJobSnapshot(a,{forcePreview:!0}),s=!0;break}this.setAccountStep(b,"resolving_enterprise",`Console not ready (HTTP ${r?.status||0}, accounts=${q.length}${i?", login HTML":""}, source=${r?.source||"unknown"}) — ${c+1}/6 body=${t.slice(0,80)}`),await this.persistJobSnapshot(a,{forcePreview:!1})}if(!s){let a=await j(),b=u||r,c=aB(b,a.names)||a.names.has("login_risk_state")&&v>0;throw Object.assign(Error(c?`Tencent restricted the post-OTP session (HTTP ${b?.status||0}; login_risk_state present; source=${b?.source||"unknown"})`:`Console accounts unavailable after login (HTTP ${b?.status||0}; cookies: ${a.list.slice(0,18).join(",")||"(none)"}; body=${t.slice(0,120)}; probeError=${r?.error||"none"}) — session not accepted for API key`),{code:c?al:"CN_CONSOLE_SESSION_UNAVAILABLE"})}let w=g;if(Array.isArray(q)&&q.length>0){let a=q.find(a=>a?.lastLogin)||q[0];a?.type&&"personal"!==a.type&&a.enterpriseId?w=a.enterpriseId:a?.enterpriseId&&a?.type!=="personal"&&(w=a.enterpriseId)}this.setAccountStep(b,"creating_api_key",`Creating API key (enterprise=${w}, accounts=${q.length})`),await this.persistJobSnapshot(a,{forcePreview:!0});let x=`zevai-router-${b.workerId||"account"}-${Date.now()}`,y=async a=>d.evaluate(async({enterpriseId:a,keyName:b,timeoutMs:c})=>{let d=new AbortController,e=setTimeout(()=>d.abort(),c);try{let c=window.location.hostname||"www.codebuddy.cn",e="www.codebuddy.cn"===c?window.location.origin:"https://www.codebuddy.cn",f=await fetch(`${e}/console/api/client/v1/api-keys`,{method:"POST",credentials:"include",signal:d.signal,headers:{"Content-Type":"application/json",Accept:"application/json, text/plain, */*","x-requested-with":"XMLHttpRequest","X-Domain":"www.codebuddy.cn","X-Product":"SaaS"},body:JSON.stringify({name:b,expire_in_days:365,user_enterprise_id:a})}),g=await f.text().catch(()=>""),h=null;try{h=g?JSON.parse(g):null}catch{h={_raw:String(g||"").slice(0,200)}}return{ok:f.ok,status:f.status,data:h}}catch(a){return{ok:!1,status:0,outcomeUnknown:!0,timedOut:a?.name==="AbortError",error:a?.message||String(a)}}finally{clearTimeout(e)}},{enterpriseId:a,keyName:x,timeoutMs:6e4}),z=async(c,d)=>{let e,f=Date.now(),g=null,h=setInterval(()=>{if(g)return;let c=Math.max(5,Math.round((Date.now()-f)/1e3));this.setAccountStep(b,"creating_api_key",`${d} — waiting for CodeBuddy (${c}s)`),g=this.persistJobSnapshot(a,{forcePreview:!1}).catch(()=>null).finally(()=>{g=null})},5e3);"function"==typeof h.unref&&h.unref();try{e=await ax(y(c),{timeoutMs:6e4,message:"API key request timed out after 60s; creation outcome is unknown",code:aj})}catch(a){if(a?.code===aj)throw a;throw Object.assign(Error(`API key request lost its response; creation outcome is unknown: ${a?.message||String(a)}`),{code:aj})}finally{clearInterval(h),g&&await g.catch(()=>null)}if(e?.outcomeUnknown){let a=e.timedOut?"timed out after 60s":`lost its response (${e.error||"network error"})`;throw Object.assign(Error(`API key request ${a}; creation outcome is unknown`),{code:aj})}return ay(e,d)};if(!await o("https://www.codebuddy.cn/profile/keys"))throw Object.assign(Error("Keys page navigation timed out after 18s"),{code:"CN_CONSOLE_NAV_TIMEOUT"});let A=await z(w,"Creating API key");A?.status===400&&w!==g&&(this.setAccountStep(b,"retrying_api_key","Retrying with personal-edition enterprise id"),await this.persistJobSnapshot(a,{forcePreview:!1}),A=await z(g,"Retrying personal API key"));let B=a=>a?.ok===!1&&(401===a.status||403===a.status);for(let c=1;c<=2&&B(A);c+=1){for(let d of(this.setAccountStep(b,"retrying_api_key",`API key 401/403 — OIDC re-handoff round ${c}/2 (waiting strong session)`),await this.persistJobSnapshot(a,{forcePreview:!0}),["https://www.codebuddy.cn/","https://www.codebuddy.cn/console","https://www.codebuddy.cn/profile/keys"]))await o(d);await i(async()=>{let a=await j();return aA(a.names)},{timeout:8e3*c,interval:300}).catch(()=>null),A=await z(g,`Retrying API key after OIDC handoff ${c}/2`)}let C=A?.data?.code;if(!A||!A.ok||!A.data||0!==C&&200!==C&&void 0!==C){let a="string"==typeof A?.data?._raw?A.data._raw.replace(/\s+/g," ").slice(0,120):null,b=a&&/openresty|nginx|Authorization Required/i.test(a)?" [edge proxy blocked — session half-baked]":"";throw Error(`API key creation failed (HTTP ${A?.status??"no-response"}, code=${C??"n/a"})${b}: ${JSON.stringify(A?.data??null).slice(0,200)}`)}let D=A.data?.data||A.data,E=D?.apiKey||D?.key||D?.token||D?.secret||D?.api_key||("string"==typeof D?D:null)||A.data.apiKey||A.data.key||A.data.token||A.data.secret;if(!E||"string"!=typeof E)throw Object.assign(Error(`API key response did not contain a key field; creation outcome is unknown: ${JSON.stringify(A.data).slice(0,300)}`),{code:aj});h=E,this.setAccountStep(b,"api_key_created","API key created successfully"),await this.persistJobSnapshot(a,{forcePreview:!0}),this.setAccountStep(b,"saving_connection","Saving CodeBuddy CN connection"),await this.persistJobSnapshot(a,{forcePreview:!0});let{connection:F}=await this.saveConnection({apiKey:E,phone:b.phone,region:b.region,fiveSimOrderId:f,account:b});await aF(()=>e.finishOrder(f)),this.finalizeAccount(b,"success",{connectionId:F.id,step:"connection_saved",message:`CodeBuddy CN connection saved (phone: ${b.phone})`}),b.runtimeSession=null,await aE(c,a),await this.persistJobSnapshot(a,{forcePreview:!0})}catch(m){let g=m?.code===al,i=m?.code===aj,j=m?.code===ak,k=i||j;if(g){this.finalizeAccount(b,"failed_restricted",{error:`${m.message}. Use a different residential CN/HK proxy with concurrency 1.`,step:"failed_restricted",message:"Tencent restricted the post-OTP session; API-key capture was not attempted"}),await aF(()=>e.finishOrder(f)),b.runtimeSession=null,await aE(c,a),await this.persistJobSnapshot(a,{forcePreview:!0});return}let l=i?`${m.message}. Check the CodeBuddy keys page before creating another key.`:m.message;if(k||as(b,c,d),this.finalizeAccount(b,"needs_manual",{error:`Registration succeeded but API key capture failed: ${l}`,step:i?"api_key_outcome_unknown":j?"api_key_retry_stopped":"awaiting_manual",message:i?"Registration done; API key request outcome is unknown. Check existing keys before retrying.":j?"Registration done; API key request was rate limited. Automatic POST retries stopped.":h?`API key captured; retrying local connection save without creating another key: ${m.message}`:`Registration done, API key capture failed: ${m.message}`}),await aF(()=>e.finishOrder(f)),await this.persistJobSnapshot(a,{forcePreview:!0}),k){b.runtimeSession=null,await aE(c,a);return}await this.runCnManualFollowup(a,b,b.workerId,c,d,e,f,h)}}async runCnManualFollowup(a,b,c,d,e,f,g,h=null){let i=(async()=>{let c=async()=>{let c=b.manualSession,e=c?.context||d,f=c?.headedBrowser||null;await aE(e,a),f&&await (0,ag.forceCloseBrowser)(f).catch(()=>null)};try{this.setAccountStep(b,"manual_waiting","Waiting for operator to complete in headed browser"),await this.persistJobSnapshot(a,{forcePreview:!0});let c=at()?18e4:48e4,f=Date.now()+c,i="string"==typeof h&&h?h:null,j=!!i;for(;!j&&Date.now()<f&&!a.cancelRequested;){let a=await d.cookies().catch(()=>[]);if(aA(a)){j=!0;break}let b=await aC({context:d,page:e}).catch(()=>null);if(function(a){let b=a?.data?.code;return a?.status===200&&!az(a)&&a?.data!==null&&"object"==typeof a?.data&&a.data?._notJson!==!0&&(void 0===b||0===b||200===b)}(b)){j=!0;break}await new Promise(a=>setTimeout(a,1e4))}if(a.cancelRequested){this.finalizeAccount(b,"cancelled",{error:"Job cancelled",step:"cancelled",message:"Job cancelled while waiting for manual completion"}),await this.persistJobSnapshot(a,{forcePreview:!0});return}if(!j)throw Error("Manual assist timed out — CodeBuddy login was not authenticated");if(!i){this.setAccountStep(b,"manual_authenticated","Manual login authenticated; creating one API key"),await this.persistJobSnapshot(a,{forcePreview:!0}),await e.goto("https://www.codebuddy.cn/profile/keys",{waitUntil:"commit",timeout:18e3});let c=`zevai-router-manual-${b.workerId||"account"}-${Date.now()}`,d=await ax(e.evaluate(async({keyName:a,timeoutMs:b})=>{let c=new AbortController,d=setTimeout(()=>c.abort(),b);try{let b=await fetch("https://www.codebuddy.cn/console/api/client/v1/api-keys",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/plain, */*","x-requested-with":"XMLHttpRequest","X-Domain":"www.codebuddy.cn","X-Product":"SaaS"},credentials:"include",signal:c.signal,body:JSON.stringify({name:a,expire_in_days:365,user_enterprise_id:"personal-edition-user-id"})}),d=await b.json().catch(()=>null);return{ok:b.ok,status:b.status,data:d}}catch(a){return{ok:!1,status:0,outcomeUnknown:!0,error:a?.message||String(a)}}finally{clearTimeout(d)}},{keyName:c,timeoutMs:6e4}),{timeoutMs:6e4,message:"Manual API key request timed out; creation outcome is unknown",code:aj});if(d?.outcomeUnknown)throw Object.assign(Error(`Manual API key request lost its response; creation outcome is unknown: ${d.error||"network error"}`),{code:aj});if(ay(d,"Manual API key request"),!d?.ok)throw Error(`Manual API key request failed (HTTP ${d?.status||0}); it was not retried`);let f=d.data?.data||d.data;if(!(i=f?.apiKey||f?.key||f?.token||f?.secret||f?.api_key||("string"==typeof f?f:null))||"string"!=typeof i)throw Object.assign(Error("Manual API key response was successful but did not contain the key; creation outcome is unknown"),{code:aj})}this.setAccountStep(b,"saving_connection","Saving CodeBuddy CN connection (manual)"),await this.persistJobSnapshot(a,{forcePreview:!0});let{connection:k}=await this.saveConnection({apiKey:i,phone:b.phone,region:b.region,fiveSimOrderId:g,account:b});this.finalizeAccount(b,"success",{connectionId:k.id,step:"connection_saved",message:`CodeBuddy CN connection saved via manual assist (phone: ${b.phone||"N/A"})`}),await this.persistJobSnapshot(a,{forcePreview:!0})}catch(c){if(a.cancelRequested)this.finalizeAccount(b,"cancelled",{error:"Job cancelled",step:"cancelled",message:"Job cancelled while waiting for manual completion"});else c?.code===aj||c?.code===ak?this.finalizeAccount(b,"needs_manual",{error:`${c.message}. Check existing CodeBuddy keys before retrying manually.`,step:c?.code===aj?"api_key_outcome_unknown":"api_key_retry_stopped",message:"Manual API key POST retries stopped"}):this.finalizeAccount(b,"failed",{error:c.message||"Manual assist flow failed",step:"failed",message:c.message||"Manual assist flow failed"});await this.persistJobSnapshot(a,{forcePreview:!0})}finally{await c(),b.manualSession=null,b.runtimeSession=null,a.manualFollowups.delete(i),await this.persistJobSnapshot(a,{forcePreview:!0})}})();a.manualFollowups.add(i)}async runWorker(a,b){if(!au(a))return super.runWorker(a,b);for(;!a.cancelRequested;){let c=this.dequeueAccount(a,b);if(!c)return;if(!a.browser)try{a.browser=await this.browserLauncher({...a,proxyUrls:c.proxyUrl?[c.proxyUrl]:a.proxyUrls})}catch(b){this.finalizeAccount(c,"failed",{error:b?.message||"Manual proxy browser launch failed",step:"failed",message:b?.message||"Manual proxy browser launch failed"}),await this.persistJobSnapshot(a,{forcePreview:!0});continue}try{await this.processAccount(a,c,b)}catch(b){"running"===c.status&&(this.finalizeAccount(c,"failed",{error:b?.message||"Unexpected manual proxy worker failure",step:"failed",message:b?.message||"Unexpected manual proxy worker failure"}),await this.persistJobSnapshot(a,{forcePreview:!0}))}finally{if(a.manualFollowups.size>0&&await Promise.allSettled([...a.manualFollowups]),a.browser){let b=a.browser;a.browser=null,await (0,ag.forceCloseBrowser)(b).catch(()=>null)}}}}shouldPrelaunchBrowser(a){return!au(a)}cancelJob(a){let b=this.jobs.get(a);if(!b)return null;for(let a of(b.cancelRequested=!0,b.accounts)){a.abortController&&!a.abortController.signal.aborted&&a.abortController.abort();let b=a.manualSession,c=a.runtimeSession,d=new Set([b?.context,c?.context].filter(Boolean)),e=new Set([b?.headedBrowser,b?.ownedBrowser].filter(Boolean));Promise.allSettled([...[...d].map(a=>aD(a)),...[...e].map(a=>(0,ag.forceCloseBrowser)(a))]),a.runtimeSession=null,a.manualSession=null,aq.has(a.status)&&this.finalizeAccount(a,"cancelled",{error:"Job cancelled",step:"cancelled",message:"Job cancelled by user"})}if(b.browser){let a=b.browser;b.browser=null,(0,ag.forceCloseBrowser)(a).catch(()=>null)}return ap.has(b.status)&&(b.status="cancelled",b.finishedAt=b.finishedAt||(0,i.kF)()),this.persistJobSnapshot(b,{forcePreview:!0}),aK(b)}}function aI({apiKey:a,proxyOptions:b}){return new y({apiKey:a,proxyOptions:b})}function aJ(a=[]){let b={total:a.length,queued:0,running:0,completed:0,success:0,failed:0,needs_manual:0,cancelled:0};for(let c of a){let a=c.status||"queued";"success"===a?(b.success+=1,b.completed+=1):a.startsWith("failed")?(b.failed+=1,b.completed+=1):"needs_manual"===a?b.needs_manual+=1:"cancelled"===a?(b.cancelled+=1,b.completed+=1):"running"===a?b.running+=1:b.queued+=1}return b}function aK(a,b={}){return a?{jobId:a.jobId,status:a.status,summary:aJ(a.accounts),concurrency:a.concurrency,proxyPoolMode:a.proxyPoolMode,region:a.region,createdAt:a.createdAt,startedAt:a.startedAt,finishedAt:a.finishedAt,error:(0,m.yr)(a.error),cancelRequested:a.cancelRequested,accounts:(a.accounts||[]).map(a=>({line:a.line,region:a.region,phone:a.phone,fiveSimOrderId:a.fiveSimOrderId,proxyUrl:a.proxyUrl?function(a){if(!a)return null;let b=String(a),c=()=>b.length>20?`${b.slice(0,10)}***${b.slice(-10)}`:"***";try{let a=new URL(b);if(!/^(https?|socks4|socks5):$/.test(a.protocol))return c();return(0,m.Eq)(b)}catch{return c()}}(a.proxyUrl):null,egressIp:a.egressIp||null,proxyTimezone:a.proxyTimezone||null,proxyLocale:a.proxyLocale||null,status:a.status,error:(0,m.yr)(a.error),connectionId:a.connectionId,workerId:a.workerId,manualSessionAvailable:!!a.manualSession,currentStep:a.currentStep,updatedAt:a.updatedAt,logs:(a.logs||[]).map(a=>({...a,message:(0,m.yr)(a.message)}))})),preview:void 0!==b.preview?b.preview:a.lastPreview||null,...b}:null}function aL(){return(!globalThis.__codeBuddyCnBulkImportSingleton&&(globalThis.__codeBuddyCnBulkImportSingleton={manager:new aH}),globalThis.__codeBuddyCnBulkImportSingleton).manager}}};
1
+ "use strict";exports.id=8371,exports.ids=[8371],exports.modules={48371:(a,b,c)=>{c.d(b,{xM:()=>aj,t9:()=>aq,TK:()=>ap,cO:()=>i.cO,VU:()=>aN});var d=c(55511),e=c(73024),f=c.n(e),g=c(76760),h=c.n(g),i=c(13868),j=c(71998),k=c(89718),l=c(20116),m=c(90715),n=c(92990),o=c(39609);let p=globalThis.fetch,q=new Set(["ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT"]),r=new Set(["a timeout","is cancelled","is complete","number banned, when number already used"]);class s extends Error{constructor(a,{status:b,body:c}={}){super(a),this.name="FiveSimError",this.status=b,this.body=c}}class t extends s{constructor(a){super(`5sim order ${a} timed out waiting for SMS`),this.name="FiveSimTimeoutError",this.orderId=a}}class u extends s{constructor(a,b){super(`5sim request to ${a} timed out after ${b}ms`),this.name="FiveSimRequestTimeoutError",this.code="FIVESIM_REQUEST_TIMEOUT",this.path=a,this.timeoutMs=b}}class v extends s{constructor(a){super(a),this.name="FiveSimUnknownOutcomeError",this.code="FIVESIM_BUY_OUTCOME_UNKNOWN",this.outcomeUnknown=!0}}class w extends s{constructor(a,b){super(`5sim order ${a} cancelled: ${b}`),this.name="FiveSimCancelledError",this.orderId=a}}class x extends s{constructor(a){super(`5sim order ${a} number was already used (banned)`),this.name="FiveSimBannedError",this.orderId=a}}class y{constructor({apiKey:a,proxyOptions:b=null,fetchImpl:c=null}={}){if(!a||"string"!=typeof a||!a.trim())throw new s("5sim API key is required");this.apiKey=a.trim(),this.proxyOptions=b,this.fetchImpl="function"==typeof c?c:null}_headers(a={}){return{Authorization:`Bearer ${this.apiKey}`,Accept:"application/json",...a}}async _get(a,{headers:b,timeoutMs:c=15e3,signal:d,...e}={}){let f,g=`https://5sim.net/v1${a}`,h=this.fetchImpl||(this.proxyOptions?.enabled?o.proxyAwareFetch:p),i=Number.isFinite(c)&&c>0?new AbortController:null,j=i?.signal||null,k=i?setTimeout(()=>i.abort(),c):null;k?.unref?.();let l=function(a){let b=a.filter(Boolean);if(0===b.length)return null;if(1===b.length)return b[0];if("function"==typeof AbortSignal.any)return AbortSignal.any(b);let c=new AbortController;for(let a of b){if(a.aborted){c.abort(a.reason);break}a.addEventListener("abort",()=>c.abort(a.reason),{once:!0})}return c.signal}([d,j]),m=b=>{if(d?.aborted){let c=new s(`5sim request to ${a} was aborted`);return c.code="FIVESIM_REQUEST_ABORTED",c.cause=b,c}if(j?.aborted){let d=new u(a,c);return d.cause=b,d}return b};try{let c;try{f=await h(g,{method:"GET",headers:this._headers(b),...e,...l?{signal:l}:{}},this.proxyOptions)}catch(a){throw m(a)}try{c=await f.text()}catch(a){throw m(a)}if(!f.ok)throw new s(`5sim request to ${a} failed (HTTP ${f.status}): ${c.slice(0,200)}`,{status:f.status,body:c});try{return JSON.parse(c)}catch{if(c&&!c.startsWith("{"))throw new s(`5sim ${a} returned non-JSON: ${c.slice(0,200)}`,{status:f.status,body:c});return null}}finally{k&&clearTimeout(k)}}async buyNumber({country:a="hongkong",operator:b="any",product:c="codebuddy",allowProductFallback:d=!1,responseTimeoutMs:e=2e4,lateAbortTimeoutMs:f=45e3,signal:g=null}={}){if(g?.aborted){let a=new s("5sim purchase cancelled before the request started");throw a.code="FIVESIM_REQUEST_ABORTED",a}let h="codebuddy"===c&&d?["codebuddy","other"]:[c],i=null;for(let c of h){let j=`/user/buy/activation/${encodeURIComponent(a)}/${encodeURIComponent(b)}/${encodeURIComponent(c)}`;try{let a,b=Math.max(Number(f)||45e3,(Number(e)||2e4)+1e3),c=this._get(j,{timeoutMs:b});try{a=await A(c,e,g)}catch(a){throw a?.code==="FIVESIM_BUY_OUTCOME_UNKNOWN"&&c.then(a=>a?.id?this.cancelOrder(a.id):null).catch(()=>null),a}if(!a||!a.id||!a.phone)throw new s(`5sim buyNumber returned unexpected shape: ${JSON.stringify(a).slice(0,200)}`,{body:a});return a}catch(e){i=e;let a=e?.status,b=String(e?.body||e?.message||"").toLowerCase();if(!(d&&"codebuddy"===c&&h.includes("other")&&(400===a||404===a||b.includes("no free")||b.includes("not enough")||b.includes("no product"))))throw e}}throw i||new s("5sim buyNumber failed for all product candidates")}async checkOrder(a,b={}){return this._get(`/user/check/${a}`,b)}async pollCode(a,{timeoutMs:b=9e5,intervalMs:c=6e3,signal:d}={}){let e=Number(c),f=Number.isFinite(e)?Math.max(5e3,e):6e3,g=Number(b),h=Number.isFinite(g)&&g>0?g:9e5,i=Date.now()+h,j=0,k=async()=>{try{await function(a,b=null){return b?.aborted?Promise.reject(b.reason||Error("Aborted")):new Promise((c,d)=>{let e=()=>b?.removeEventListener("abort",g),f=setTimeout(()=>{e(),c()},a),g=()=>{clearTimeout(f),e(),d(b.reason||Error("Aborted"))};b?.addEventListener("abort",g,{once:!0})})}(f,d)}catch(b){if(d?.aborted)throw new w(a,"aborted by caller");throw b}};for(;Date.now()<i;){let b;if(d?.aborted)throw new w(a,"aborted by caller");try{b=await this.checkOrder(a,{signal:d})}catch(b){if(d?.aborted||b?.code==="FIVESIM_REQUEST_ABORTED")throw new w(a,"aborted by caller");if(b instanceof u||function(a){if(a instanceof s)return 408===a.status||429===a.status||a.status>=500;if(a instanceof TypeError)return!0;let b=a?.code||a?.cause?.code;return q.has(b)}(b)){if(++j>5)throw b;await k();continue}throw b}if(j=0,Array.isArray(b.sms)&&b.sms.length>0){let a=z(b.sms[b.sms.length-1]);if(a)return a}if(b.status&&r.has(b.status)){if("a timeout"===b.status)throw new t(a);if("number banned, when number already used"===b.status)throw new x(a);if("is cancelled"===b.status)throw new w(a,b.status);if("is complete"===b.status){let c=function(a){if(!Array.isArray(a))return null;for(let b=a.length-1;b>=0;b--){let c=z(a[b]);if(c)return c}return null}(b.sms);if(c)return c;throw new s(`5sim order ${a} completed but no SMS code found`,{body:b})}}await k()}throw new t(a)}async finishOrder(a){try{return await this._get(`/user/finish/${a}`),!0}catch(b){return console.warn(`[5sim] finishOrder(${a}) failed (best-effort): ${b.message}`),!1}}async cancelOrder(a){try{return await this._get(`/user/cancel/${a}`),!0}catch(b){return console.warn(`[5sim] cancelOrder(${a}) failed (best-effort): ${b.message}`),!1}}async banOrder(a){try{return await this._get(`/user/ban/${a}`),!0}catch(b){return console.warn(`[5sim] banOrder(${a}) failed (best-effort): ${b.message}`),!1}}async getBalance(){try{let a=await this._get("/user/profile");return{balance:a?.balance??null,rating:a?.rating??null}}catch(a){return console.warn(`[5sim] getBalance failed: ${a.message}`),{balance:null,rating:null}}}}function z(a){return a?a.code&&/\d{4,8}/.test(String(a.code))?String(a.code).match(/\d{4,8}/)[0]:a.text?function(a){if(!a)return null;let b=String(a).match(/\b(\d{4,8})\b/);return b?b[1]:null}(a.text):null:null}async function A(a,b,c=null){let d=Number(b)||2e4,e=null,f=null,g=new Promise((a,b)=>{let g=a=>b(new v(`5sim buy request ${a}; purchase outcome is unknown and any late successful order will be cancelled automatically`));e=setTimeout(()=>{g(`did not answer within ${d}ms`)},d),e.unref?.(),f=()=>g("was interrupted by the caller"),c?.aborted?f():c?.addEventListener("abort",f,{once:!0})});try{return await Promise.race([a,g])}finally{e&&clearTimeout(e),f&&c?.removeEventListener("abort",f)}}let B=["https://www.codebuddy.cn/login/"],C=["text=手机号","div:has-text('手机号')","span:has-text('手机号')","[class*='phone']:has-text('手机号')","div.kc-phone-tab:has-text('手机号')"],D=["text=手机号","text=其他登录方式","text=微信","#phone-iframe",".login-phone-box"],E=["button:has-text('同意')","text=同意并继续","text=同意"],F="#phone-iframe",G="#phoneNumber",H=".kc-country-option",I=".kc-country-code-text",J="#code",K=".code-btn",L=['iframe[src*="captcha"]','iframe[src*="tcaptcha"]',"#tcaptcha","#tcaptcha_transform",".nc_iconfont",".nc_wrapper",'[class*="captcha"]','[id*="captcha"]',"text=滑块","text=拖动"],M=["#input-error",".pf-c-form__helper-text.pf-m-error",".kc-feedback-text"],N=new Set(["login_risk_state"]),O=["账号访问受限","安全策略限制","访问受限","account restricted","access restricted"];function P(a="Tencent risk policy rejected the post-OTP session"){return{status:"failed_restricted",error:`Account restricted after OTP (${a}). Use a different residential CN/HK proxy with concurrency 1; do not retry this number on the same egress IP.`}}async function Q(a){let b=a.locator("input.btn-lg.code-btn").first(),c=null;try{await b.waitFor({state:"visible",timeout:5e3}),c=b}catch{let b=a.locator(K).first();try{await b.waitFor({state:"visible",timeout:5e3}),c=b}catch{c=null}}if(!c)return{ok:!1,reason:"missing"};let d=await c.click().then(()=>!0).catch(()=>!1);return{ok:d,reason:d?null:"click_failed"}}async function R(a,{timeoutMs:b=3e3}={}){let c=Date.now()+b;for(;Date.now()<c;){for(let b of E){let c=a.locator(b).first();if(await c.isVisible().catch(()=>!1))return c}await a.waitForTimeout(100).catch(()=>new Promise(a=>setTimeout(a,100)))}return null}async function S(a,b,{reportStep:c,consentTimeoutMs:d=3e3}={}){let e=await b.click().then(()=>!0).catch(()=>!1);await a.waitForTimeout(250).catch(()=>null);let f=await R(a,{timeoutMs:d});return f?!!await f.click().then(()=>!0).catch(()=>!1)&&(c?.("cn_consent_dismissed","Service agreement accepted after opening phone login"),await a.waitForTimeout(300).catch(()=>null),!!(await T(a,{timeoutMs:d})).ok&&(!!await a.locator(F).isVisible().catch(()=>!1)||b.click().then(()=>!0).catch(()=>!1))):e}async function T(a,{timeoutMs:b=3e3}={}){let c=a.locator(".t-checkbox").last();if(!await c.isVisible({timeout:b}).catch(()=>!1))return{ok:!0,present:!1,changed:!1};let d=c.locator("input").first(),e=async()=>{if(!0===await d.isChecked().catch(()=>null))return!0;let a=await c.getAttribute("class").catch(()=>"");return!!/(?:^|\s)t-is-checked(?:\s|$)/.test(String(a||""))};if(await e())return{ok:!0,present:!0,changed:!1};if(!await c.click().then(()=>!0).catch(()=>!1))return{ok:!1,present:!0,changed:!1};let f=Date.now()+b;for(;Date.now()<f;){if(await e())return{ok:!0,present:!0,changed:!0};await a.waitForTimeout(100).catch(()=>new Promise(a=>setTimeout(a,100)))}return{ok:!1,present:!0,changed:!0}}async function U(a,{timeoutMs:b=8e3}={}){let c=Date.now()+b;for(;Date.now()<c;){let b=a.locator(K).first(),c=await b.evaluate(a=>({disabled:!!a.disabled,ariaDisabled:"true"===a.getAttribute("aria-disabled"),label:String(a.value||a.textContent||"").trim()})).catch(()=>null);if(c){let a=/(?:^\d+$|\d+\s*(?:s|sec|\u79d2)|\u91cd\u65b0|\u5df2\u53d1\u9001|resend|sent)/i.test(c.label);if(c.disabled||c.ariaDisabled||a)return{ok:!0,state:c}}await a.waitForTimeout(200).catch(()=>new Promise(a=>setTimeout(a,200)))}return{ok:!1,state:null}}async function V(a,{timeoutMs:b,signal:c=null}={}){let d=null,e=null,f=new Promise((a,c)=>{d=setTimeout(()=>c(Error("Timed out waiting for SMS code")),b),d.unref?.()}),g=c?new Promise((a,b)=>{e=()=>b(c.reason||Object.assign(Error("Job cancelled"),{code:"JOB_CANCELLED"})),c.aborted?e():c.addEventListener("abort",e,{once:!0})}):null;try{return await Promise.race([a,f,...g?[g]:[]])}finally{d&&clearTimeout(d),e&&c?.removeEventListener("abort",e)}}async function W({page:a,phone:b,resolvePhone:c,pollSmsPromise:d,waitForSms:e,onStep:f,phoneFormatter:g=a=>a,timeouts:h={},signal:i=null,isCancelled:j=null}){let k=h.nav??3e4,l=h.action??15e3,m=h.codeWait??9e5,n=h.postSubmit??1e4,o=(a,b)=>f?.(a,b),p=()=>{if(i?.aborted){if(i.reason?.code==="CN_ACCOUNT_HARD_TIMEOUT")throw i.reason;let a=Error("Job cancelled");throw a.code="JOB_CANCELLED",a}if("function"==typeof j&&j()){let a=Error("Job cancelled");throw a.code="JOB_CANCELLED",a}};try{var q;let f,h;o("cn_opening_login_page","Opening CodeBuddy CN login page"),p();try{a.setDefaultNavigationTimeout(k),a.setDefaultTimeout(l)}catch{}try{await a.context().route("**/*",a=>{var b,c;let d,e=a.request();return(b=e.url(),c=e.resourceType(),d=String(b||""),/googletagmanager|googleadservices|google-analytics|doubleclick|facebook|hotjar|clarity\.ms|hm\.baidu|google\.com\/rmkt/i.test(d)||"media"===c||"image"===c&&!/captcha|tcaptcha|challenge|verify|qrcode/i.test(d))?a.abort():a.continue()})}catch{}let j=null,r=[];for(let b=1;b<=2;b++){p();try{let c=B[(b-1)%B.length];o("cn_nav_attempt",`Navigation attempt ${b}/2 → ${c}`),b>1&&(await a.context().clearCookies().catch(()=>{}),await a.waitForTimeout(800)),await a.goto(c,{waitUntil:"commit",timeout:k}),p(),await a.waitForFunction(()=>"loading"!==document.readyState,{timeout:1e4}).catch(()=>{}),p();let d=await $(a,D,25e3);if(p(),!d){let b=await a.locator("body").innerText().catch(()=>""),d=await a.evaluate(()=>document.documentElement?.outerHTML?.length||0).catch(()=>0),e=a.url();o("cn_spa_not_ready",`SPA not ready after 25s (url=${e}, body=${String(b).slice(0,80)}, html=${d})`),!b&&d<200?(o("cn_proxy_empty_page","Empty page body — proxy may be blocking codebuddy.cn"),r.push({code:"proxy_empty",detail:`empty page via ${c} (html=${d})`})):r.push({code:"spa_timeout",detail:`SPA not ready url=${e} html=${d}`});continue}o("cn_spa_ready","Login SPA ready"),o("cn_selecting_phone_tab","Selecting phone-number tab");let e=await Z(a,C,{timeout:12e3});if(e){if(!await S(a,e,{reportStep:o})){o("cn_phone_tab_failed","Could not open phone login after service agreement"),r.push({code:"phone_tab_failed",detail:"phone tab or post-click consent could not be completed"});continue}o("cn_phone_tab_selected","Phone tab selected"),await a.waitForTimeout(800)}else o("cn_phone_tab_not_found","Phone tab not found — checking if iframe already present");if(o("cn_waiting_for_iframe","Waiting for phone iframe to load"),await a.locator(F).waitFor({state:"attached",timeout:18e3}).catch(()=>{}),j=await X(a)){if(await j.waitForSelector(G,{state:"visible",timeout:15e3}).then(()=>!0).catch(()=>!1)){o("cn_iframe_ready","Phone iframe + #phoneNumber ready");break}o("cn_iframe_empty","Iframe found but #phoneNumber not visible yet"),r.push({code:"iframe_empty",detail:"phone iframe attached but #phoneNumber not visible"}),j=null}else o("cn_iframe_missing",`No #phone-iframe (attempt ${b}/2)`),r.push({code:"iframe_missing",detail:"SPA loaded but #phone-iframe never appeared"})}catch(e){if(e?.code==="JOB_CANCELLED")throw e;let a=String(e?.message||e||"");o("cn_nav_retry",`Navigation attempt ${b}/2 failed: ${a.slice(0,120)}`);let c=/timeout|exceeded|ETIMEDOUT|net::ERR/i.test(a),d=/ERR_PROXY|ERR_TUNNEL|ERR_CONNECTION|NS_ERROR_PROXY|proxy/i.test(a);r.push({code:d?"proxy_network":c?"nav_timeout":"nav_error",detail:a.slice(0,160)})}}if(!j)return{status:"failed",error:function(a=[],b=2){let c=a.map(a=>a.code),d=a[a.length-1],e="Fix: use a live residential CN proxy (proxyPoolMode=single), concurrency 1, then retry. 5sim is not charged until the form loads.";return c.includes("proxy_empty")||c.includes("proxy_network")?`CodeBuddy CN login page empty/blocked via proxy after ${b} attempts (${d?.detail||"proxy blackhole"}). ${e}`:c.includes("nav_timeout")?`CodeBuddy CN navigation timed out after ${b} attempts (${d?.detail||"goto timeout"}). Proxy is too slow or dead. ${e}`:c.includes("spa_timeout")?`CodeBuddy CN SPA did not boot after ${b} attempts (${d?.detail||"no login UI"}). Proxy/CDN may be filtering JS. ${e}`:c.includes("iframe_missing")||c.includes("iframe_empty")?`CodeBuddy CN page opened but phone form iframe never appeared after ${b} attempts (${d?.detail||"no #phone-iframe"}). Site layout change or half-loaded SPA — retry with another CN exit IP. ${e}`:c.includes("nav_error")&&d?.detail?`CodeBuddy CN phone form failed after ${b} attempts: ${d.detail}. ${e}`:`Could not load CodeBuddy CN phone form after ${b} attempts (${d?.code||"unknown"}: ${d?.detail||"proxy/SPA"}). ${e}`}(r,2)};await j.waitForSelector("#kc-form-login",{timeout:l}).catch(()=>{}),await j.waitForSelector(G,{state:"visible",timeout:l}).catch(()=>{});let s=b;if("function"==typeof c&&(o("cn_ordering_after_form","Login form ready — ordering 5sim number now (not before nav)"),s=await c()),!s)return{status:"failed",error:"No phone number available (resolvePhone/phone missing)"};let t=g(s),{countryCode:u,localNumber:v}=(q=t,(!(h=String(q).replace(/[\s\-()]/g,"")).startsWith("+")&&/^\d+$/.test(h)&&(h="+"+h),h.startsWith("+852"))?{countryCode:"+852",localNumber:h.slice(4)}:h.startsWith("+86")?{countryCode:"+86",localNumber:h.slice(3)}:h.startsWith("+1")?{countryCode:"+1",localNumber:h.slice(2)}:{countryCode:"",localNumber:h.replace(/^\+/,"")});if(o("cn_selecting_country",`Selecting country code ${u} for phone ${t}`),!await Y(j,u,l,o))return{status:"failed",error:`Could not select country code ${u||"(unknown)"} for ${t}`};o("cn_entering_phone",`Entering phone number: ${v}`);let w=j.locator(G).first();try{await w.waitFor({state:"visible",timeout:l})}catch{return{status:"failed",error:"Could not find the phone number input (#phoneNumber) inside the iframe"}}if(!await _(w,v))return{status:"failed",error:"Phone number input did not retain the expected value"};o("cn_phone_entered",`Phone number entered: ${v}`);let x=await T(a);if(!x.ok)return{status:"failed",error:"Could not keep the service agreement checkbox checked"};x.present&&o("cn_agreement_checked",x.changed?"Agreement checkbox checked":"Agreement checkbox already checked"),o("cn_clicking_send_code","Clicking send SMS code button");let y=await Q(j);if("missing"===y.reason)return{status:"failed",error:"Could not find the send-SMS-code button (.code-btn) inside the iframe"};if(!y.ok)return{status:"failed",error:"Could not click the send-SMS-code button (.code-btn) inside the iframe"};o("cn_send_code_clicked","Send code button clicked");let z=await U(j),A=await af(j);if(A)return{status:"failed",error:`Form error after sending code: ${A}`};if(!z.ok)return{status:"failed",error:"Tencent did not acknowledge the SMS-code request (no disabled/countdown state)"};o("cn_send_code_acknowledged","Tencent accepted the SMS-code request"),o("cn_waiting_for_sms","Waiting for SMS verification code from 5sim (timer starts now)");try{let a;if("function"==typeof e)a=Promise.resolve().then(()=>e());else if(d)a=d;else throw Error("No waitForSms/pollSmsPromise provided");f=await V(a,{timeoutMs:m,signal:i})}catch(a){if(a&&"FiveSimTimeoutError"===a.name)throw a;return(i?.aborted||a?.code==="JOB_CANCELLED")&&p(),{status:"failed",error:`Failed to receive SMS code: ${a.message}`}}if(!f)return{status:"failed",error:"Received empty SMS code from 5sim"};o("cn_sms_received",`SMS code received: ${f}`),o("cn_entering_code","Entering SMS verification code");let E=j.locator(J).first();try{await E.waitFor({state:"visible",timeout:l})}catch{return{status:"failed",error:"Could not find the verification code input (#code) inside the iframe"}}if(!await _(E,f))return{status:"failed",error:"Verification code input did not retain the expected value"};o("cn_code_entered","Verification code entered");let H=1200+Math.floor(1800*Math.random());o("cn_pre_submit_pause",`Waiting ${H}ms before submit (humanize)`),await a.waitForTimeout(H);let I=Math.max(n,12e3);o("cn_submitting","Submitting the registration form once");let K=await X(a);if(!K)return{status:"failed",error:"Lost phone iframe before submit"};let L=await ac(K,l);if(!L.ok)return{status:"failed",error:"Could not submit the Keycloak login form"};if(o("cn_submitted",`Registration form submitted once via ${L.method}`),await a.waitForLoadState("domcontentloaded",{timeout:5e3}).catch(()=>{}),await a.waitForTimeout(1800),K=await X(a)||K,await ae(a,K))return o("cn_account_restricted","Account restricted after the OTP submit"),P("restriction message detected");if(o("cn_checking_captcha","Checking for captcha"),await ag(a,K,3e3))return o("cn_captcha_detected","Captcha appeared during registration - manual assist needed"),{status:"needs_manual",error:"A captcha appeared during registration. Complete it in the existing browser session.",captcha:!0};let M=await af(K);if(M)return{status:"failed",error:`Form error after submit: ${M}`};o("cn_waiting_session",`Waiting up to ${Math.round(I/1e3)}s for Keycloak session cookies`);let O=await ab(a,{timeoutMs:I,reportStep:o,alsoCheckFrame:()=>X(a)});if(O.ok)return o("cn_session_cookies",`Keycloak session cookies present (${O.cookie}) - registration success`),{status:"success"};if("restricted"===O.reason||function(a=[]){return a.some(a=>N.has(a?.name))}(O.cookies))return o("cn_account_restricted","Restriction detected while waiting for the login session"),P("restriction evidence detected during session handoff");if(K=await X(a)||K,await ag(a,K,2e3))return o("cn_captcha_detected","Captcha appeared while waiting for the login session"),{status:"needs_manual",error:"A captcha appeared while establishing the login session. Complete it in the existing browser.",captcha:!0};let R=await ad(a);return o("cn_success_unconfirmed",`No Keycloak session after submit — ${R.summary}`),{status:"needs_manual",error:`Login submit finished but no Keycloak session yet (${R.summary}). Complete login in the headed browser or retry with a fresh China proxy.`}}catch(a){if((i?.aborted||"function"==typeof j&&j())&&p(),a&&"FiveSimTimeoutError"===a.name||a?.code==="JOB_CANCELLED"||a?.code==="CN_ACCOUNT_HARD_TIMEOUT")throw a;return o("cn_automation_error",`Phone registration automation error: ${a.message}`),{status:"failed",error:a.message||"Unexpected error during phone registration"}}}async function X(a){try{await a.locator(F).waitFor({state:"attached",timeout:5e3});let b=await a.locator(F).elementHandle({timeout:2e3});if(b){let a=await b.contentFrame();if(a)return a}}catch{}for(let b of a.frames()){let a=b.url();if(a.includes("codebuddy.cn/auth/realms/copilot")||a.includes("protocol/openid-connect"))return b}return null}async function Y(a,b,c,d){if(!b)return!1;let e=Math.min(Number(c)||15e3,1e4),f=async()=>{let c=a.locator(I).first(),f=String(await c.textContent({timeout:3e3}).catch(()=>"")).trim();if(f===b)return d?.("cn_country_already_selected",`Country code already ${b}`),!0;d?.("cn_opening_country_dropdown",`Opening country dropdown (current: ${f}, target: ${b})`);let g=a.locator(".kc-country-selector").first();for(let c of(await g.waitFor({state:"visible",timeout:Math.min(e,5e3)}),await g.click({timeout:3e3}).catch(()=>{}),await a.locator(H).first().waitFor({state:"visible",timeout:3e3}).catch(()=>{}),({"+852":["中国香港","香港","Hong Kong","+852"],"+86":["中国大陆","中国","China","+86"],"+853":["中国澳门","澳门","Macau","+853"],"+886":["中国台湾","台湾","Taiwan","+886"]})[b]||[b]))for(let e of[a.locator(`${H}:has-text("${c}")`).first(),a.getByText(c,{exact:!1}).first()]){if(!await e.isVisible({timeout:1500}).catch(()=>!1))continue;let f=await e.textContent({timeout:1500}).catch(()=>c);if(await e.click({timeout:2e3}).then(()=>!0).catch(()=>!1)&&await a.locator(I).filter({hasText:b}).first().waitFor({state:"visible",timeout:2e3}).then(()=>!0).catch(()=>!1))return d?.("cn_country_selected",`Country selected: ${String(f||c).trim()}`),!0}return d?.("cn_country_not_found",`Country code ${b} not found in dropdown`),await a.locator("body").click({timeout:1e3}).catch(()=>{}),!1},g=null;try{return await Promise.race([f(),new Promise((a,b)=>{g=setTimeout(()=>b(Error(`selectCountry timed out after ${e}ms`)),e),g.unref?.()})])}catch(a){return d?.("cn_country_select_error",`Country selection error: ${a.message}`),!1}finally{g&&clearTimeout(g)}}async function Z(a,b,{timeout:c=1e4}={}){for(let d of b)try{let b=a.locator(d).first();return await b.waitFor({state:"visible",timeout:Math.min(c,5e3)}),b}catch{}return null}async function $(a,b,c=15e3){let d=Date.now()+c;for(;Date.now()<d;){for(let c of b)try{let b=a.locator(c).first();if(await b.isVisible().catch(()=>!1))return!0}catch{}await new Promise(a=>setTimeout(a,250))}return!1}async function _(a,b){let c=String(b??""),d=async()=>await a.inputValue().catch(()=>null)===c;try{if(await a.click(),await a.fill(""),await a.fill(c),await d())return!0}catch{}try{return await a.click(),await a.press("ControlOrMeta+a"),await a.type(c,{delay:50}),d()}catch{return!1}}let aa=["KEYCLOAK_IDENTITY","KEYCLOAK_SESSION","KEYCLOAK_IDENTITY_LEGACY","KEYCLOAK_SESSION_LEGACY"];async function ab(a,{timeoutMs:b=2e4,reportStep:c,alsoCheckFrame:d}={}){let e=Date.now()+b,f=0;for(;Date.now()<e;){let b=await a.context().cookies().catch(()=>[]),g=function(a=[]){for(let b of aa)if(a.some(a=>a.name===b))return b;let b=a.find(a=>a.name.startsWith("KEYCLOAK_")&&!/locale|theme|restart/i.test(a.name));return b?.name||null}(b);if(g)return{ok:!0,cookie:g,cookies:b};try{let c=a.url();if(c&&!c.includes("/login")&&!c.includes("/auth/realms")){let a=b.find(a=>/^(access_token|cb_token|codebuddy)/i.test(a.name)||"token"===a.name&&a.domain?.includes("codebuddy"));if(a)return{ok:!0,cookie:a.name,cookies:b}}}catch{}let h=d?await d().catch(()=>null):null;if(await ae(a,h))return{ok:!1,cookies:b,reason:"restricted"};if(h){let a=await af(h);if(a)return{ok:!1,cookies:b,reason:`form_error:${a}`}}if(c&&Date.now()-f>4e3){f=Date.now();let a=Math.max(0,Math.round((e-Date.now())/1e3));c("cn_waiting_session",`Still waiting for Keycloak session… ${a}s left`)}await a.waitForTimeout(500)}return{ok:!1,cookies:await a.context().cookies().catch(()=>[])}}async function ac(a,b=15e3){let c=a.locator("#kc-login").first();try{return await c.waitFor({state:"visible",timeout:b}),await c.click({timeout:5e3}),{ok:!0,method:"click"}}catch{}try{return await a.evaluate(()=>{let a=document.querySelector("#kc-form-login")||document.querySelector("form");if(!a)return!1;if("function"==typeof a.requestSubmit){let b=a.querySelector("#kc-login")||a.querySelector('[type="submit"]');b?a.requestSubmit(b):a.requestSubmit()}else a.submit();return!0})?{ok:!0,method:"requestSubmit"}:{ok:!1,method:null}}catch{let b=await a.locator(J).first().press("Enter").then(()=>!0).catch(()=>!1);return{ok:b,method:b?"enter":null}}}async function ad(a){let b="";try{b=a.url()}catch{b="(unknown)"}let c=(await a.context().cookies().catch(()=>[])).map(a=>a.name).slice(0,20).join(",")||"(none)",d="";try{d=await a.evaluate(()=>(document.body?.innerText||"").replace(/\s+/g," ").trim().slice(0,120))}catch{d=""}let e=await X(a),f="no-iframe";if(e)try{f=(await e.url()).slice(0,80)}catch{f="iframe-detached"}return{summary:`url=${b.slice(0,60)} cookies=[${c}] frame=${f}${d?` text="${d}"`:""}`,url:b,cookieNames:c,bodySnippet:d}}async function ae(a,b){for(let c of[b,a])if(c)try{let a=await c.evaluate(()=>document.body?.innerText||"");if(function(a){let b=String(a||"").toLowerCase();return O.some(a=>b.includes(a.toLowerCase()))}(a))return!0}catch{}return!1}async function af(a){for(let b of M)try{let c=a.locator(b).first();if(await c.isVisible({timeout:1500}).catch(()=>!1)){let a=await c.textContent().catch(()=>""),b=String(a).trim();if(b&&b.length>1)return b}}catch{}try{let b=await a.evaluate(()=>(document.body?.innerText||"").replace(/\s+/g," ").trim());for(let a of["验证码错误","验证码已过期","验证码无效","请输入正确的验证码","手机号格式","发送过于频繁","Invalid","incorrect"])if(b.includes(a)){let c=b.indexOf(a);return b.slice(Math.max(0,c-10),c+a.length+40).trim()}}catch{}return null}async function ag(a,b,c=5e3){for(let b of L)try{let d=a.locator(b).first();if(await d.isVisible({timeout:Math.min(c,2e3)}).catch(()=>!1))return!0}catch{}if(b)for(let a of L)try{let d=b.locator(a).first();if(await d.isVisible({timeout:Math.min(c,2e3)}).catch(()=>!1))return!0}catch{}return!1}var ah=c(40891),ai=c(75949);let aj=200,ak=Number.parseInt(process.env.ZEVAI_CN_ACCOUNT_TIMEOUT_MS||"",10)||3e5,al="CN_API_KEY_OUTCOME_UNKNOWN",am="CN_API_KEY_AUTOMATIC_RETRY_STOPPED",an="CN_ACCOUNT_RESTRICTED",ao=new Set(["KEYCLOAK_IDENTITY","KEYCLOAK_SESSION","KEYCLOAK_IDENTITY_LEGACY","KEYCLOAK_SESSION_LEGACY"]),ap=new Set(["hongkong","china"]),aq="hongkong",ar=new Set(["queued","running","needs_manual"]),as=new Set(["queued","running","needs_manual"]);function at(a){return String(a||"").trim()}function au(a,b,c){return a.manualSession={context:b,page:c,opened:!1,openedAt:null},a.manualSession}function av(){try{let{totalMemGb:a}=(0,l.si)();return Number.isFinite(a)&&a>0&&a<3}catch{return!1}}function aw(a){return!!a?.proxyUrls?.length&&["manual","all","single"].includes(a?.proxyPoolMode)}async function ax(a,{timeoutMs:b=6e3}={}){let c=null;try{c=a?.request||null}catch{c=null}if(!c||"function"!=typeof c.get)return{ok:!1,ip:null,ips:[],samples:0,error:"context request unavailable"};let d=[],e=null;for(let a of ai.PROXY_EGRESS_ECHO_URLS){d.push(a);let g=null;try{var f;if(g=await c.get(a,{timeout:b,failOnStatusCode:!1,headers:{Accept:"text/plain, application/json;q=0.9, */*;q=0.1","Cache-Control":"no-cache"}}),200>g.status()||g.status()>=300){e=`HTTP ${g.status()}`;continue}let h=(f=await g.text().catch(()=>""),(0,ai.parseProxyEgressIp)(f));if(!h){e="exit-IP response was not recognized";continue}return{ok:!0,ip:h,ips:[h],samples:1,attempts:d.length,attemptedUrls:d,unstable:!1,error:null}}catch(a){e=a?.name==="TimeoutError"?`timed out after ${b}ms`:"request failed"}finally{"function"==typeof g?.dispose&&await Promise.resolve(g.dispose()).catch(()=>null)}}return{ok:!1,ip:null,ips:[],samples:0,attempts:d.length,attemptedUrls:d,unstable:!1,error:e||"all exit-IP services failed"}}function ay(a,b=null){if(a?.unstable)throw Object.assign(Error("Manual proxy rotated between exit IPs during preflight; no phone number was purchased"),{code:"CN_PROXY_EGRESS_UNSTABLE"});if(!a?.ok||!a?.ip)throw Object.assign(Error(`Manual proxy exit IP could not be verified (${a?.error||"no response"}); no phone number was purchased`),{code:"CN_PROXY_EGRESS_UNVERIFIED"});if(b&&a.ip!==b)throw Object.assign(Error("Manual proxy browser exit IP changed before the 5sim purchase; no phone number was purchased"),{code:"CN_PROXY_EGRESS_CHANGED"});return a.ip}async function az(a,{timeoutMs:b,message:c,code:d,onTimeout:e,onLateResolve:f}){let g=Promise.resolve(a),h=null,i=!1,j=new Promise((a,f)=>{"function"==typeof(h=setTimeout(()=>{i=!0;try{"function"==typeof e&&e()}catch{}f(Object.assign(Error(c),{code:d}))},b)).unref&&h.unref()});try{return await Promise.race([g,j])}finally{h&&clearTimeout(h),i&&"function"==typeof f&&g.then(f).catch(()=>null)}}function aA(a,b="API key request"){let c=Number(a?.status);if(429===c)throw Object.assign(Error(`${b} was rate limited (HTTP 429); automatic POST retries stopped`),{code:am});if(Number.isFinite(c)&&c>=500)throw Object.assign(Error(`${b} returned HTTP ${c}; creation outcome may be unknown and automatic POST retries stopped`),{code:al});return a}function aB(a){let b=`${a?.text||""} ${a?.data?._raw||""} ${a?.url||""}`;return/<!doctype html|<html|login-pf|\/auth\/realms\//i.test(b)}function aC(a=[]){let b=a instanceof Set?a:new Set(Array.from(a,a=>"string"==typeof a?a:a?.name));return[...ao].some(a=>b.has(a))}function aD(a,b=[]){let c=b instanceof Set?b:new Set(b),d=`${a?.text||""} ${a?.data?._raw||""}`;return!!/账号访问受限|安全策略限制|访问受限|account restricted|access restricted/i.test(d)||!!c.has("login_risk_state")&&(aB(a)||a?.status===0||a?.status===401||a?.status===403)}async function aE({context:a,page:b,timeoutMs:c=1e4}){let d={Accept:"application/json, text/plain, */*","x-requested-with":"XMLHttpRequest","X-Domain":"www.codebuddy.cn","X-Product":"SaaS"},e=null;try{e=a?.request||null}catch{e=null}if(e&&"function"==typeof e.get)try{let a=await e.get("https://www.codebuddy.cn/console/accounts",{headers:d,timeout:c,failOnStatusCode:!1}),b=await a.text().catch(()=>"");return function(a,b,c={}){let d=String(b||""),e=null;try{e=d?JSON.parse(d):null}catch{e={_raw:d.slice(0,240),_notJson:!0}}return{status:Number(a)||0,data:e,text:d.slice(0,240),...c}}(a.status(),b,{source:"context-request",url:a.url(),contentType:a.headers()?.["content-type"]||""})}catch{}return az(b.evaluate(async({requestTimeoutMs:a,requestHeaders:b})=>{let c=new AbortController,d=setTimeout(()=>c.abort(),a);try{let a=window.location.hostname||"www.codebuddy.cn",d="www.codebuddy.cn"===a?`${window.location.origin}`:"https://www.codebuddy.cn",e=await fetch(`${d}/console/accounts`,{credentials:"include",signal:c.signal,headers:b}),f=await e.text().catch(()=>""),g=null;try{g=f?JSON.parse(f):null}catch{g={_raw:String(f||"").slice(0,240),_notJson:!0}}return{status:e.status,data:g,text:String(f||"").slice(0,240),source:"page-fetch",url:e.url,contentType:e.headers.get("content-type")||""}}catch(a){return{status:0,timedOut:a?.name==="AbortError",error:a?.message||String(a),source:"page-fetch"}}finally{clearTimeout(d)}},{requestTimeoutMs:c,requestHeaders:d}),{timeoutMs:c,message:`Console account probe timed out after ${c/1e3}s`,code:"CN_CONSOLE_PROBE_TIMEOUT"}).catch(a=>({status:0,timedOut:a?.code==="CN_CONSOLE_PROBE_TIMEOUT",error:a?.message||String(a),source:"page-fetch"}))}async function aF(a){if(!a||"function"!=typeof a.close)return!0;try{return await az(Promise.resolve().then(()=>a.close()),{timeoutMs:5e3,message:"Browser resource close timed out after 5s",code:"CN_RESOURCE_CLOSE_TIMEOUT"}),!0}catch{return!1}}async function aG(a,b){if(await aF(a)||!b?.browser)return;let c=b.browser;b.browser=null,await (0,ai.forceCloseBrowser)(c).catch(()=>null)}async function aH(a){try{return await az(Promise.resolve().then(a),{timeoutMs:12e3,message:"5sim order settlement timed out after 12s",code:"CN_FIVESIM_SETTLE_TIMEOUT"})}catch{return!1}}async function aI({apiKey:a,phone:b,region:d,fiveSimOrderId:e,account:f}){let{createProviderConnection:g}=await Promise.resolve().then(c.bind(c,71998)),h={provider:"codebuddy-cn",authType:"apikey",apiKey:a,accessToken:a,name:b||`5sim-${e}`,email:b||`5sim-${e}`,providerSpecificData:{domain:"www.codebuddy.cn",phoneNumber:b,fiveSimOrderId:e,region:d,automation:"5sim-phone-bulk"},testStatus:"active"};return{connection:await g(h)}}class aJ extends i.Q6{constructor({browserLauncher:a,requestDeviceCodeFn:b=ah.cT,pollToken:d=ah.ZV,fetchLoginAccountFn:e=ah.w8,saveConnection:g=aI,fiveSimClientFactory:i=aK,phoneAutomation:j=W,phoneFormatter:k=at,pollIntervalMs:l=n.ne.pollInterval,storageName:m="codebuddy-cn-bulk-import"}={}){super({browserLauncher:a||(async a=>{let{forceCloseBrowser:b,launchBulkImportBrowser:d}=await Promise.resolve().then(c.bind(c,75949)),e=Array.isArray(a?.proxyUrls)&&a.proxyUrls.length?a.proxyUrls[0]:null,f=process.env.ZEVAI_CN_HEADLESS,g=!1;return("0"===f||"false"===f)&&(g=!1),("1"===f||"true"===f)&&(g=!0),az(d({engine:a?.engine||"cloakbrowser",proxyUrl:e,headless:g,windowSize:{width:1280,height:900},requireProxyGeoip:a?.proxyPoolMode==="manual"&&!!e}),{timeoutMs:9e4,message:"CloakBrowser launch timed out after 90s",code:"CN_BROWSER_LAUNCH_TIMEOUT",onLateResolve:a=>b(a)})}),storageName:m}),this.latestJobId&&this.readPersistedJob(this.latestJobId)||(this.latestJobId=function(a){try{let b=f().readdirSync(a).filter(a=>a.endsWith(".json")&&"meta.json"!==a).map(b=>{let c=h().join(a,b);try{let a=JSON.parse(f().readFileSync(c,"utf8"));if(!a?.jobId)return null;let b=Date.parse(a.createdAt||""),d=Number.isFinite(b)?b:f().statSync(c).mtimeMs;return{jobId:a.jobId,sortTime:d}}catch{return null}}).filter(Boolean).sort((a,b)=>b.sortTime-a.sortTime);return b[0]?.jobId||null}catch{return null}}(this.storageDir),this.latestJobId&&this.persistLatestJobId(this.latestJobId)),this.requestDeviceCode=b,this.pollToken=d,this.fetchLoginAccount=e,this.saveConnection=g,this.fiveSimClientFactory=i,this.phoneAutomation=j,this.phoneFormatter=k,this.pollIntervalMs=l}async startJob({count:a,concurrency:b,proxyPoolMode:c,proxyPoolId:e,manualProxyUrl:f,region:g}){let h=Number.parseInt(a,10);if(!Number.isFinite(h)||h<1)throw Object.assign(Error("At least one account is required (count >= 1)"),{error:"At least one account is required (count >= 1)"});if(h>aj)throw Object.assign(Error(`Count exceeds maximum of ${aj}`),{error:`Count exceeds maximum of ${aj}`});this.latestJobId&&!this.jobs.has(this.latestJobId)&&this.getJob(this.latestJobId);let k=[...this.jobs.values()].find(a=>a&&("running"===a.status||"queued"===a.status||"needs_manual"===a.status)&&!a.cancelRequested);if(k)throw Object.assign(Error(`Another CodeBuddy CN job is still active (${k.jobId}). Cancel it or wait before starting again.`),{error:`Another CodeBuddy CN job is still active (${k.jobId}). Cancel it or wait before starting again.`});let m=ap.has(g)?g:aq,n=[],o="string"==typeof f?f.trim():"";if(o){if(!/^(https?|socks4|socks5):\/\/.+/i.test(o))throw Object.assign(Error("manualProxyUrl must be a valid proxy URL (http://, https://, socks4://, or socks5://)"),{error:"manualProxyUrl must be a valid proxy URL (http://, https://, socks4://, or socks5://)"});n=[o]}else if("all"===c)n=(await (0,j.ui)({isActive:!0})).map(a=>a.proxyUrl).filter(Boolean);else if("single"===c&&e){let a=await (0,j.hr)(e);a?.isActive&&a?.proxyUrl&&(n=[a.proxyUrl])}o||function(a,b){if(!["all","single"].includes(a)||b.length>0)return;let c="single"===a?"Selected proxy is missing or inactive; no automation was started":"No active proxies are available in the selected pool; no automation was started";throw Object.assign(Error(c),{error:c,code:"CN_PROXY_SELECTION_EMPTY"})}(c,n);let p=(0,d.randomUUID)(),q=(0,i.kF)(),r={jobId:p,status:"running",concurrency:function(a,{manualProxy:b=!1,processBoundProxy:c=!1}={}){return b||c?1:function(a){let b=av()?1:8;if((0,l.uT)(a))return Math.min(b,Math.max(1,(0,l.q)()));let c=Number.parseInt(a,10);return Number.isFinite(c)?Math.min(b,Math.max(1,c)):Math.min(b,1)}(a)}(b,{manualProxy:!!o,processBoundProxy:n.length>0}),proxyPoolMode:o?"manual":c||"none",proxyUrls:n,region:m,createdAt:q,startedAt:q,finishedAt:null,error:null,cancelRequested:!1,browser:null,nextIndex:0,manualFollowups:new Set,persistPromise:Promise.resolve(),lastPreview:null,lastPreviewCapturedAt:0,accounts:Array.from({length:h},(a,b)=>({line:b+1,region:m,phone:null,fiveSimOrderId:null,fiveSimActivationId:null,fingerprintSeed:(0,d.randomUUID)(),proxyUrl:null,egressIp:null,proxyTimezone:null,proxyLocale:null,abortController:new AbortController,status:"queued",error:null,connectionId:null,workerId:null,manualSession:null,runtimeSession:null,currentStep:"queued",updatedAt:q,logs:[(0,i.hn)("queued","Queued and waiting for an available worker")]}))};return this.jobs.set(p,r),this.latestJobId=p,this.persistLatestJobId(p),await this.persistJobSnapshot(r,{forcePreview:!1}),this.runJob(p),aM(r)}buildPersistedSnapshot(a){return aM(a,{preview:a.lastPreview||null})}terminalizeInterruptedSnapshot(a){if(!a||!ar.has(a.status))return a;let b="CodeBuddy CN job was interrupted by a service restart. Browser and OTP sessions cannot be resumed safely; start a new job.",c=(a.accounts||[]).map(a=>{if(!as.has(a.status))return a;let c=(0,i.hn)("failed",b,"error");return{...a,status:"failed",error:b,currentStep:"failed",updatedAt:c.at,manualSessionAvailable:!1,logs:[...a.logs||[],c].slice(-40)}}),d={...a,status:"failed",error:a.error||b,finishedAt:a.finishedAt||(0,i.kF)(),accounts:c,summary:aL(c),preview:null};return this.writePersistedJob(a.jobId,d),d}getJob(a){let b=this.jobs.get(a);if(b)return aM(b);let c=this.readPersistedJob(a);return c?this.terminalizeInterruptedSnapshot(c):null}async getJobWithPreview(a){let b=this.jobs.get(a);return b?(await this.persistJobSnapshot(b,{forcePreview:!1}),aM(b,{preview:b.lastPreview||null})):this.getJob(a)}async processAccount(a,b,c){if(a.cancelRequested||!a.browser)return void this.finalizeAccount(b,"cancelled",{error:"Job cancelled"});let d=null,e=null,f=!1,g=null,h=null;try{let c;this.setAccountStep(b,"reading_settings","Reading 5sim API key from settings"),await this.persistJobSnapshot(a,{forcePreview:!0});let j=(await (0,k.mt)()).fiveSimApiKey;if(!j||!j.trim()){this.finalizeAccount(b,"failed",{error:"5sim API key not configured. Set it in the automation modal or dashboard settings.",step:"failed",message:"5sim API key not configured"}),await this.persistJobSnapshot(a,{forcePreview:!0});return}d=this.fiveSimClientFactory({apiKey:j,proxyOptions:null}),this.setAccountStep(b,"creating_browser","Creating browser context (before 5sim order)"),await this.persistJobSnapshot(a,{forcePreview:!0});let l=(0,i.go)(a.browser,b.proxyUrl,{profile:"codebuddy-cn",region:a.region||"hongkong",fingerprintSeed:b.fingerprintSeed,lowMemory:av(),nativeCloakProfile:aw(a)&&!!b.proxyUrl}),m=await az(l,{timeoutMs:3e4,message:"Browser context creation timed out after 30s",code:"CN_CONTEXT_TIMEOUT",onLateResolve:a=>Promise.resolve(a?.context?.close?.()).catch(()=>null)});g=m.context;let n=m.page;if(b.runtimeSession={context:g,page:n},"manual"===a.proxyPoolMode&&b.proxyUrl){this.setAccountStep(b,"checking_proxy_egress","Verifying pasted proxy exit IP before opening the registration form"),await this.persistJobSnapshot(a,{forcePreview:!1});let c=(0,ai.getCloakProxyProfile)(a.browser),d=await ax(g);b.egressIp=h=ay(d),b.proxyTimezone=c?.timezone||null,b.proxyLocale=c?.locale||null,this.setAccountStep(b,"proxy_egress_ready",`Manual proxy verified: ${h} (${d.samples} checks, ${b.proxyTimezone||"timezone unknown"}, ${b.proxyLocale||"locale unknown"})`),await this.persistJobSnapshot(a,{forcePreview:!1})}if(a.cancelRequested)throw Error("Job cancelled before ordering phone number");this.setAccountStep(b,"registering","Running phone registration on CodeBuddy CN"),await this.persistJobSnapshot(a,{forcePreview:!0});try{n.setDefaultTimeout(2e4),n.setDefaultNavigationTimeout(45e3)}catch{}let o=null,p=new Promise((a,c)=>{o=setTimeout(()=>{let a=Object.assign(Error(`CodeBuddy CN account hard timeout after ${Math.round(ak/1e3)}s (browser will be force-closed)`),{code:"CN_ACCOUNT_HARD_TIMEOUT"});b.abortController&&!b.abortController.signal.aborted&&b.abortController.abort(a),c(a)},ak),"function"==typeof o.unref&&o.unref()});try{c=await Promise.race([this.phoneAutomation({page:n,signal:b.abortController?.signal,isCancelled:()=>!0===a.cancelRequested,resolvePhone:async()=>{if(a.cancelRequested)throw Error("Job cancelled before ordering phone number");if("manual"===a.proxyPoolMode&&b.proxyUrl){this.setAccountStep(b,"rechecking_proxy_egress","Registration form is ready — confirming the pasted proxy stayed sticky"),await this.persistJobSnapshot(a,{forcePreview:!1});let c=await ax(g);ay(c,h),this.setAccountStep(b,"proxy_egress_confirmed",`Manual proxy remained on ${h}; safe to purchase one phone number`),await this.persistJobSnapshot(a,{forcePreview:!1})}this.setAccountStep(b,"ordering_number",`Form ready — ordering ${a.region} phone from 5sim (single buy)`),await this.persistJobSnapshot(a,{forcePreview:!0});let c=await d.buyNumber({country:a.region,product:"codebuddy",allowProductFallback:!1,signal:b.abortController?.signal});return e=c.id,b.phone=c.phone,b.fiveSimOrderId=c.id,b.fiveSimActivationId=c.id,this.setAccountStep(b,"number_ordered",`Phone number ordered: ${c.phone} (1 buy, no re-order)`),await this.persistJobSnapshot(a,{forcePreview:!0}),c.phone},waitForSms:async()=>{if(!e)throw Error("Cannot poll SMS — no 5sim order id");this.setAccountStep(b,"sms_poll_started","SMS poll started (full 90s window after send-code)"),await this.persistJobSnapshot(a,{forcePreview:!1});let c=await d.pollCode(e,{timeoutMs:9e4,signal:b.abortController?.signal});return f=!0,c},onStep:(c,d)=>{this.setAccountStep(b,c,d),this.persistJobSnapshot(a,{forcePreview:!1})},phoneFormatter:this.phoneFormatter}),p])}finally{o&&clearTimeout(o)}if(String(c.status||"").startsWith("failed")){let h=c.error||"Phone registration failed before submit",i=c.status||"failed";this.finalizeAccount(b,i,{error:h,step:i,message:h}),d&&e&&(f?await aH(()=>d.finishOrder(e)):await aH(()=>d.cancelOrder(e))),b.runtimeSession=null,await aG(g,a),await this.persistJobSnapshot(a,{forcePreview:!0});return}if("needs_manual"===c.status){au(b,g,n),this.finalizeAccount(b,"needs_manual",{error:c.error||"Manual completion is required",step:"awaiting_manual",message:c.error||"Complete the existing CodeBuddy login session manually"}),d&&e&&f&&await aH(()=>d.finishOrder(e)),await this.persistJobSnapshot(a,{forcePreview:!0}),await this.runCnManualFollowup(a,b,b.workerId,g,n,d,e);return}if("success"!==c.status)throw Error(`Unexpected phone automation status: ${c.status||"unknown"}`);await this.captureApiKey(a,b,g,n,d,e);return}catch(j){let c=j instanceof t,h=a.cancelRequested||j?.code==="JOB_CANCELLED",i=h?"Job cancelled":c?"SMS OTP not received within 90s — number banned":j.message||"Unexpected CodeBuddy CN bulk import failure";if(this.finalizeAccount(b,h?"cancelled":"failed",{error:i,step:h?"cancelled":c?"sms_timeout":"failed",message:i}),d&&e&&(f?await aH(()=>d.finishOrder(e)):c?await aH(()=>d.banOrder(e)):await aH(()=>d.cancelOrder(e))),b.runtimeSession=null,await aG(g,a),(j?.code==="CN_ACCOUNT_HARD_TIMEOUT"||j?.code==="CN_CONTEXT_TIMEOUT"||a.cancelRequested)&&a.browser){let b=a.browser;a.browser=null,await (0,ai.forceCloseBrowser)(b).catch(()=>null)}await this.persistJobSnapshot(a,{forcePreview:!0})}}async captureApiKey(a,b,c,d,e,f){let g="personal-edition-user-id",h=null,i=async(a,{timeout:b=12e3,interval:c=150}={})=>{let d=Date.now()+b;for(;Date.now()<d;){try{if(await a())return!0}catch{}await new Promise(a=>setTimeout(a,c))}return!1};try{this.setAccountStep(b,"waiting_session","Establishing CodeBuddy console session (probe APIs, not just cookies)"),await this.persistJobSnapshot(a,{forcePreview:!0});let j=async()=>{let a=await c.cookies().catch(()=>[]);return{cookies:a,names:new Set(a.map(a=>a.name)),list:a.map(a=>a.name)}},k=a=>a.has("AUTH_SESSION_ID")||a.has("session")||a.has("qcloud_uid")||a.has("qcmainCSRFToken")||a.has("x_host_key_access"),l=()=>aE({context:c,page:d}),m=a=>{let b=a?.data;if(!b||"object"!=typeof b)return[];for(let a of[b?.data?.accounts,b?.accounts,b?.data?.list,b?.list,b?.data?.result,b?.result,b?.data?.items,b?.items,Array.isArray(b?.data)?b.data:null,Array.isArray(b)?b:null])if(Array.isArray(a)&&a.length>0)return a;return[]},n=async(a=2500)=>{let b=!1,c=null;try{await Promise.race([d.waitForLoadState("domcontentloaded",{timeout:a}).catch(()=>null),i(async()=>{if(b)return!0;let a=await j();return aC(a.names)},{timeout:a,interval:200}),new Promise(b=>{c=setTimeout(b,a)})])}finally{b=!0,c&&clearTimeout(c)}},o=async a=>{let b=Date.now();try{await d.goto(a,{waitUntil:"commit",timeout:18e3});let c=18e3-(Date.now()-b);return c>0&&await n(Math.min(2500,c)),!0}catch{return!1}},p=["https://www.codebuddy.cn/","https://www.codebuddy.cn/console","https://www.codebuddy.cn/console/","https://www.codebuddy.cn/profile","https://www.codebuddy.cn/profile/keys"],q=[],r=null,s=!1,t="",u=null,v=0;for(let c=0;c<6;c+=1){if(a.cancelRequested)throw Error("Job cancelled while establishing session");let e=await j(),f=aC(e.names),g=k(e.names),h=p[Math.min(c,p.length-1)];c<3||c%2==0||!g?(this.setAccountStep(b,"waiting_session",`OIDC handoff ${c+1}/6 → ${h.replace("https://www.codebuddy.cn","")} (${f?"KEYCLOAK":g?"soft-session":"weak"})`),await this.persistJobSnapshot(a,{forcePreview:!1}),await o(h)):await new Promise(a=>setTimeout(a,300)),/^https:\/\/www\.codebuddy\.cn(?:[/:]|$)/i.test(d.url?.()||"")||await o("https://www.codebuddy.cn/console"),r=await l(),q=m(r),(r?.status>0||r?.text||r?.data)&&(u=r),t=JSON.stringify(r?.data??r?.text??r?.error??null).slice(0,180);let i=aB(r),n=await j();if(!aC(n.names)&&aD(r,n.names)?v+=1:v=0,v>=2)throw Object.assign(Error(`Tencent restricted the post-OTP session (${v} console probes returned login/risk evidence; source=${r?.source||"unknown"})`),{code:an});if(r?.status===200&&!i&&Array.isArray(q)&&q.length>0){s=!0,this.setAccountStep(b,"session_ready",`Console session accepted (HTTP 200, ${q.length} account(s)${f?", KEYCLOAK ok":", soft session"})`),await this.persistJobSnapshot(a,{forcePreview:!0});break}if(g&&r?.status===200&&!i&&r?.data?._notJson!==!0&&Array.isArray(q)&&0===q.length&&c>=3){this.setAccountStep(b,"session_soft","Console HTTP 200 but 0 accounts — trying personal API key with soft session (cookies ok)"),await this.persistJobSnapshot(a,{forcePreview:!0}),s=!0;break}this.setAccountStep(b,"resolving_enterprise",`Console not ready (HTTP ${r?.status||0}, accounts=${q.length}${i?", login HTML":""}, source=${r?.source||"unknown"}) — ${c+1}/6 body=${t.slice(0,80)}`),await this.persistJobSnapshot(a,{forcePreview:!1})}if(!s){let a=await j(),b=u||r,c=aD(b,a.names)||a.names.has("login_risk_state")&&v>0;throw Object.assign(Error(c?`Tencent restricted the post-OTP session (HTTP ${b?.status||0}; login_risk_state present; source=${b?.source||"unknown"})`:`Console accounts unavailable after login (HTTP ${b?.status||0}; cookies: ${a.list.slice(0,18).join(",")||"(none)"}; body=${t.slice(0,120)}; probeError=${r?.error||"none"}) — session not accepted for API key`),{code:c?an:"CN_CONSOLE_SESSION_UNAVAILABLE"})}let w=g;if(Array.isArray(q)&&q.length>0){let a=q.find(a=>a?.lastLogin)||q[0];a?.type&&"personal"!==a.type&&a.enterpriseId?w=a.enterpriseId:a?.enterpriseId&&a?.type!=="personal"&&(w=a.enterpriseId)}this.setAccountStep(b,"creating_api_key",`Creating API key (enterprise=${w}, accounts=${q.length})`),await this.persistJobSnapshot(a,{forcePreview:!0});let x=`zevai-router-${b.workerId||"account"}-${Date.now()}`,y=async a=>d.evaluate(async({enterpriseId:a,keyName:b,timeoutMs:c})=>{let d=new AbortController,e=setTimeout(()=>d.abort(),c);try{let c=window.location.hostname||"www.codebuddy.cn",e="www.codebuddy.cn"===c?window.location.origin:"https://www.codebuddy.cn",f=await fetch(`${e}/console/api/client/v1/api-keys`,{method:"POST",credentials:"include",signal:d.signal,headers:{"Content-Type":"application/json",Accept:"application/json, text/plain, */*","x-requested-with":"XMLHttpRequest","X-Domain":"www.codebuddy.cn","X-Product":"SaaS"},body:JSON.stringify({name:b,expire_in_days:365,user_enterprise_id:a})}),g=await f.text().catch(()=>""),h=null;try{h=g?JSON.parse(g):null}catch{h={_raw:String(g||"").slice(0,200)}}return{ok:f.ok,status:f.status,data:h}}catch(a){return{ok:!1,status:0,outcomeUnknown:!0,timedOut:a?.name==="AbortError",error:a?.message||String(a)}}finally{clearTimeout(e)}},{enterpriseId:a,keyName:x,timeoutMs:6e4}),z=async(c,d)=>{let e,f=Date.now(),g=null,h=setInterval(()=>{if(g)return;let c=Math.max(5,Math.round((Date.now()-f)/1e3));this.setAccountStep(b,"creating_api_key",`${d} — waiting for CodeBuddy (${c}s)`),g=this.persistJobSnapshot(a,{forcePreview:!1}).catch(()=>null).finally(()=>{g=null})},5e3);"function"==typeof h.unref&&h.unref();try{e=await az(y(c),{timeoutMs:6e4,message:"API key request timed out after 60s; creation outcome is unknown",code:al})}catch(a){if(a?.code===al)throw a;throw Object.assign(Error(`API key request lost its response; creation outcome is unknown: ${a?.message||String(a)}`),{code:al})}finally{clearInterval(h),g&&await g.catch(()=>null)}if(e?.outcomeUnknown){let a=e.timedOut?"timed out after 60s":`lost its response (${e.error||"network error"})`;throw Object.assign(Error(`API key request ${a}; creation outcome is unknown`),{code:al})}return aA(e,d)};if(!await o("https://www.codebuddy.cn/profile/keys"))throw Object.assign(Error("Keys page navigation timed out after 18s"),{code:"CN_CONSOLE_NAV_TIMEOUT"});let A=await z(w,"Creating API key");A?.status===400&&w!==g&&(this.setAccountStep(b,"retrying_api_key","Retrying with personal-edition enterprise id"),await this.persistJobSnapshot(a,{forcePreview:!1}),A=await z(g,"Retrying personal API key"));let B=a=>a?.ok===!1&&(401===a.status||403===a.status);for(let c=1;c<=2&&B(A);c+=1){for(let d of(this.setAccountStep(b,"retrying_api_key",`API key 401/403 — OIDC re-handoff round ${c}/2 (waiting strong session)`),await this.persistJobSnapshot(a,{forcePreview:!0}),["https://www.codebuddy.cn/","https://www.codebuddy.cn/console","https://www.codebuddy.cn/profile/keys"]))await o(d);await i(async()=>{let a=await j();return aC(a.names)},{timeout:8e3*c,interval:300}).catch(()=>null),A=await z(g,`Retrying API key after OIDC handoff ${c}/2`)}let C=A?.data?.code;if(!A||!A.ok||!A.data||0!==C&&200!==C&&void 0!==C){let a="string"==typeof A?.data?._raw?A.data._raw.replace(/\s+/g," ").slice(0,120):null,b=a&&/openresty|nginx|Authorization Required/i.test(a)?" [edge proxy blocked — session half-baked]":"";throw Error(`API key creation failed (HTTP ${A?.status??"no-response"}, code=${C??"n/a"})${b}: ${JSON.stringify(A?.data??null).slice(0,200)}`)}let D=A.data?.data||A.data,E=D?.apiKey||D?.key||D?.token||D?.secret||D?.api_key||("string"==typeof D?D:null)||A.data.apiKey||A.data.key||A.data.token||A.data.secret;if(!E||"string"!=typeof E)throw Object.assign(Error(`API key response did not contain a key field; creation outcome is unknown: ${JSON.stringify(A.data).slice(0,300)}`),{code:al});h=E,this.setAccountStep(b,"api_key_created","API key created successfully"),await this.persistJobSnapshot(a,{forcePreview:!0}),this.setAccountStep(b,"saving_connection","Saving CodeBuddy CN connection"),await this.persistJobSnapshot(a,{forcePreview:!0});let{connection:F}=await this.saveConnection({apiKey:E,phone:b.phone,region:b.region,fiveSimOrderId:f,account:b});await aH(()=>e.finishOrder(f)),this.finalizeAccount(b,"success",{connectionId:F.id,step:"connection_saved",message:`CodeBuddy CN connection saved (phone: ${b.phone})`}),b.runtimeSession=null,await aG(c,a),await this.persistJobSnapshot(a,{forcePreview:!0})}catch(m){let g=m?.code===an,i=m?.code===al,j=m?.code===am,k=i||j;if(g){this.finalizeAccount(b,"failed_restricted",{error:`${m.message}. Use a different residential CN/HK proxy with concurrency 1.`,step:"failed_restricted",message:"Tencent restricted the post-OTP session; API-key capture was not attempted"}),await aH(()=>e.finishOrder(f)),b.runtimeSession=null,await aG(c,a),await this.persistJobSnapshot(a,{forcePreview:!0});return}let l=i?`${m.message}. Check the CodeBuddy keys page before creating another key.`:m.message;if(k||au(b,c,d),this.finalizeAccount(b,"needs_manual",{error:`Registration succeeded but API key capture failed: ${l}`,step:i?"api_key_outcome_unknown":j?"api_key_retry_stopped":"awaiting_manual",message:i?"Registration done; API key request outcome is unknown. Check existing keys before retrying.":j?"Registration done; API key request was rate limited. Automatic POST retries stopped.":h?`API key captured; retrying local connection save without creating another key: ${m.message}`:`Registration done, API key capture failed: ${m.message}`}),await aH(()=>e.finishOrder(f)),await this.persistJobSnapshot(a,{forcePreview:!0}),k){b.runtimeSession=null,await aG(c,a);return}await this.runCnManualFollowup(a,b,b.workerId,c,d,e,f,h)}}async runCnManualFollowup(a,b,c,d,e,f,g,h=null){let i=(async()=>{let c=async()=>{let c=b.manualSession,e=c?.context||d,f=c?.headedBrowser||null;await aG(e,a),f&&await (0,ai.forceCloseBrowser)(f).catch(()=>null)};try{this.setAccountStep(b,"manual_waiting","Waiting for operator to complete in headed browser"),await this.persistJobSnapshot(a,{forcePreview:!0});let c=av()?18e4:48e4,f=Date.now()+c,i="string"==typeof h&&h?h:null,j=!!i;for(;!j&&Date.now()<f&&!a.cancelRequested;){let a=await d.cookies().catch(()=>[]);if(aC(a)){j=!0;break}let b=await aE({context:d,page:e}).catch(()=>null);if(function(a){let b=a?.data?.code;return a?.status===200&&!aB(a)&&a?.data!==null&&"object"==typeof a?.data&&a.data?._notJson!==!0&&(void 0===b||0===b||200===b)}(b)){j=!0;break}await new Promise(a=>setTimeout(a,1e4))}if(a.cancelRequested){this.finalizeAccount(b,"cancelled",{error:"Job cancelled",step:"cancelled",message:"Job cancelled while waiting for manual completion"}),await this.persistJobSnapshot(a,{forcePreview:!0});return}if(!j)throw Error("Manual assist timed out — CodeBuddy login was not authenticated");if(!i){this.setAccountStep(b,"manual_authenticated","Manual login authenticated; creating one API key"),await this.persistJobSnapshot(a,{forcePreview:!0}),await e.goto("https://www.codebuddy.cn/profile/keys",{waitUntil:"commit",timeout:18e3});let c=`zevai-router-manual-${b.workerId||"account"}-${Date.now()}`,d=await az(e.evaluate(async({keyName:a,timeoutMs:b})=>{let c=new AbortController,d=setTimeout(()=>c.abort(),b);try{let b=await fetch("https://www.codebuddy.cn/console/api/client/v1/api-keys",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/plain, */*","x-requested-with":"XMLHttpRequest","X-Domain":"www.codebuddy.cn","X-Product":"SaaS"},credentials:"include",signal:c.signal,body:JSON.stringify({name:a,expire_in_days:365,user_enterprise_id:"personal-edition-user-id"})}),d=await b.json().catch(()=>null);return{ok:b.ok,status:b.status,data:d}}catch(a){return{ok:!1,status:0,outcomeUnknown:!0,error:a?.message||String(a)}}finally{clearTimeout(d)}},{keyName:c,timeoutMs:6e4}),{timeoutMs:6e4,message:"Manual API key request timed out; creation outcome is unknown",code:al});if(d?.outcomeUnknown)throw Object.assign(Error(`Manual API key request lost its response; creation outcome is unknown: ${d.error||"network error"}`),{code:al});if(aA(d,"Manual API key request"),!d?.ok)throw Error(`Manual API key request failed (HTTP ${d?.status||0}); it was not retried`);let f=d.data?.data||d.data;if(!(i=f?.apiKey||f?.key||f?.token||f?.secret||f?.api_key||("string"==typeof f?f:null))||"string"!=typeof i)throw Object.assign(Error("Manual API key response was successful but did not contain the key; creation outcome is unknown"),{code:al})}this.setAccountStep(b,"saving_connection","Saving CodeBuddy CN connection (manual)"),await this.persistJobSnapshot(a,{forcePreview:!0});let{connection:k}=await this.saveConnection({apiKey:i,phone:b.phone,region:b.region,fiveSimOrderId:g,account:b});this.finalizeAccount(b,"success",{connectionId:k.id,step:"connection_saved",message:`CodeBuddy CN connection saved via manual assist (phone: ${b.phone||"N/A"})`}),await this.persistJobSnapshot(a,{forcePreview:!0})}catch(c){if(a.cancelRequested)this.finalizeAccount(b,"cancelled",{error:"Job cancelled",step:"cancelled",message:"Job cancelled while waiting for manual completion"});else c?.code===al||c?.code===am?this.finalizeAccount(b,"needs_manual",{error:`${c.message}. Check existing CodeBuddy keys before retrying manually.`,step:c?.code===al?"api_key_outcome_unknown":"api_key_retry_stopped",message:"Manual API key POST retries stopped"}):this.finalizeAccount(b,"failed",{error:c.message||"Manual assist flow failed",step:"failed",message:c.message||"Manual assist flow failed"});await this.persistJobSnapshot(a,{forcePreview:!0})}finally{await c(),b.manualSession=null,b.runtimeSession=null,a.manualFollowups.delete(i),await this.persistJobSnapshot(a,{forcePreview:!0})}})();a.manualFollowups.add(i)}async runWorker(a,b){if(!aw(a))return super.runWorker(a,b);for(;!a.cancelRequested;){let c=this.dequeueAccount(a,b);if(!c)return;if(!a.browser)try{a.browser=await this.browserLauncher({...a,proxyUrls:c.proxyUrl?[c.proxyUrl]:a.proxyUrls})}catch(b){this.finalizeAccount(c,"failed",{error:b?.message||"Manual proxy browser launch failed",step:"failed",message:b?.message||"Manual proxy browser launch failed"}),await this.persistJobSnapshot(a,{forcePreview:!0});continue}try{await this.processAccount(a,c,b)}catch(b){"running"===c.status&&(this.finalizeAccount(c,"failed",{error:b?.message||"Unexpected manual proxy worker failure",step:"failed",message:b?.message||"Unexpected manual proxy worker failure"}),await this.persistJobSnapshot(a,{forcePreview:!0}))}finally{if(a.manualFollowups.size>0&&await Promise.allSettled([...a.manualFollowups]),a.browser){let b=a.browser;a.browser=null,await (0,ai.forceCloseBrowser)(b).catch(()=>null)}}}}shouldPrelaunchBrowser(a){return!aw(a)}cancelJob(a){let b=this.jobs.get(a);if(!b)return null;for(let a of(b.cancelRequested=!0,b.accounts)){a.abortController&&!a.abortController.signal.aborted&&a.abortController.abort();let b=a.manualSession,c=a.runtimeSession,d=new Set([b?.context,c?.context].filter(Boolean)),e=new Set([b?.headedBrowser,b?.ownedBrowser].filter(Boolean));Promise.allSettled([...[...d].map(a=>aF(a)),...[...e].map(a=>(0,ai.forceCloseBrowser)(a))]),a.runtimeSession=null,a.manualSession=null,as.has(a.status)&&this.finalizeAccount(a,"cancelled",{error:"Job cancelled",step:"cancelled",message:"Job cancelled by user"})}if(b.browser){let a=b.browser;b.browser=null,(0,ai.forceCloseBrowser)(a).catch(()=>null)}return ar.has(b.status)&&(b.status="cancelled",b.finishedAt=b.finishedAt||(0,i.kF)()),this.persistJobSnapshot(b,{forcePreview:!0}),aM(b)}}function aK({apiKey:a,proxyOptions:b}){return new y({apiKey:a,proxyOptions:b})}function aL(a=[]){let b={total:a.length,queued:0,running:0,completed:0,success:0,failed:0,needs_manual:0,cancelled:0};for(let c of a){let a=c.status||"queued";"success"===a?(b.success+=1,b.completed+=1):a.startsWith("failed")?(b.failed+=1,b.completed+=1):"needs_manual"===a?b.needs_manual+=1:"cancelled"===a?(b.cancelled+=1,b.completed+=1):"running"===a?b.running+=1:b.queued+=1}return b}function aM(a,b={}){return a?{jobId:a.jobId,status:a.status,summary:aL(a.accounts),concurrency:a.concurrency,proxyPoolMode:a.proxyPoolMode,region:a.region,createdAt:a.createdAt,startedAt:a.startedAt,finishedAt:a.finishedAt,error:(0,m.yr)(a.error),cancelRequested:a.cancelRequested,accounts:(a.accounts||[]).map(a=>({line:a.line,region:a.region,phone:a.phone,fiveSimOrderId:a.fiveSimOrderId,proxyUrl:a.proxyUrl?function(a){if(!a)return null;let b=String(a),c=()=>b.length>20?`${b.slice(0,10)}***${b.slice(-10)}`:"***";try{let a=new URL(b);if(!/^(https?|socks4|socks5):$/.test(a.protocol))return c();return(0,m.Eq)(b)}catch{return c()}}(a.proxyUrl):null,egressIp:a.egressIp||null,proxyTimezone:a.proxyTimezone||null,proxyLocale:a.proxyLocale||null,status:a.status,error:(0,m.yr)(a.error),connectionId:a.connectionId,workerId:a.workerId,manualSessionAvailable:!!a.manualSession,currentStep:a.currentStep,updatedAt:a.updatedAt,logs:(a.logs||[]).map(a=>({...a,message:(0,m.yr)(a.message)}))})),preview:void 0!==b.preview?b.preview:a.lastPreview||null,...b}:null}function aN(){return(!globalThis.__codeBuddyCnBulkImportSingleton&&(globalThis.__codeBuddyCnBulkImportSingleton={manager:new aJ}),globalThis.__codeBuddyCnBulkImportSingleton).manager}}};