@overdeck/core 0.50.3 → 0.50.4

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 (208) hide show
  1. package/dist/agents-DNMRPC8n.js.map +1 -1
  2. package/dist/{build-info-BJuEVWOh.js → build-info-ioRdOmqT.js} +3 -3
  3. package/dist/{build-info-BJuEVWOh.js.map → build-info-ioRdOmqT.js.map} +1 -1
  4. package/dist/build-info-kMMitDOP.js +2 -0
  5. package/dist/cli/index.js +4 -4
  6. package/dist/conversation-compaction-GFfO5UZL.js.map +1 -1
  7. package/dist/dashboard/{advancing-selfheal-Bq8V0QUa.js → advancing-selfheal-Dp5_Gai3.js} +3 -3
  8. package/dist/dashboard/{advancing-selfheal-Bq8V0QUa.js.map → advancing-selfheal-Dp5_Gai3.js.map} +1 -1
  9. package/dist/dashboard/{agent-gc-Coz8zQt_.js → agent-gc-JzoSs5Pi.js} +3 -3
  10. package/dist/dashboard/{agent-gc-Coz8zQt_.js.map → agent-gc-JzoSs5Pi.js.map} +1 -1
  11. package/dist/dashboard/{agent-idle-CAwB-K6M.js → agent-idle-D-Qy5BN_.js} +2 -2
  12. package/dist/dashboard/{agent-idle-CAwB-K6M.js.map → agent-idle-D-Qy5BN_.js.map} +1 -1
  13. package/dist/dashboard/{agent-state-Ci6PhjOE.js → agent-state-B196fj1h.js} +38 -16
  14. package/dist/dashboard/agent-state-B196fj1h.js.map +1 -0
  15. package/dist/dashboard/{agent-state-CbUEwUEQ.js → agent-state-IpWnw8lv.js} +1 -1
  16. package/dist/dashboard/{agent-state-service-D6IVrX3B.js → agent-state-service-CCo5-9DR.js} +3 -3
  17. package/dist/dashboard/{agent-state-service-D6IVrX3B.js.map → agent-state-service-CCo5-9DR.js.map} +1 -1
  18. package/dist/dashboard/{agent-state-service-DcN1j6eK.js → agent-state-service-D_F3VZ23.js} +1 -1
  19. package/dist/dashboard/{agents-BVvL4o_4.js → agents-CkGhnAmu.js} +1 -1
  20. package/dist/dashboard/{backlog-auto-trigger-BuSBqG2V.js → backlog-auto-trigger-B5Z2zBtC.js} +2 -2
  21. package/dist/dashboard/{backlog-auto-trigger-BuSBqG2V.js.map → backlog-auto-trigger-B5Z2zBtC.js.map} +1 -1
  22. package/dist/dashboard/build-info-BTjOB0Xr.js +2 -0
  23. package/dist/dashboard/{build-info-Cj3Y0K87.js → build-info-D0EJNj6C.js} +3 -3
  24. package/dist/dashboard/{build-info-Cj3Y0K87.js.map → build-info-D0EJNj6C.js.map} +1 -1
  25. package/dist/dashboard/cli-CIznFrcE.js +2 -0
  26. package/dist/dashboard/{cli-DIhQieif.js → cli-DCbVrSsg.js} +2 -2
  27. package/dist/dashboard/{cli-DIhQieif.js.map → cli-DCbVrSsg.js.map} +1 -1
  28. package/dist/dashboard/{close-issue-CRlmrE5g.js → close-issue-Bmu9aOIx.js} +2 -2
  29. package/dist/dashboard/{close-issue-CRlmrE5g.js.map → close-issue-Bmu9aOIx.js.map} +1 -1
  30. package/dist/dashboard/{closed-issue-reaper-DrHyYgJR.js → closed-issue-reaper-COxfTtLz.js} +5 -5
  31. package/dist/dashboard/{closed-issue-reaper-DrHyYgJR.js.map → closed-issue-reaper-COxfTtLz.js.map} +1 -1
  32. package/dist/dashboard/{closed-issue-reaper-DWlw2EtL.js → closed-issue-reaper-DwMwG_Pz.js} +1 -1
  33. package/dist/dashboard/{compaction-continuation-DhYgsXmF.js → compaction-continuation-Bqc212Zm.js} +2 -2
  34. package/dist/dashboard/{compaction-continuation-DhYgsXmF.js.map → compaction-continuation-Bqc212Zm.js.map} +1 -1
  35. package/dist/dashboard/{conflict-gate-vczgdVTa.js → conflict-gate-9mPVg7-5.js} +1 -1
  36. package/dist/dashboard/{conflict-gate-Bt-lLgYf.js → conflict-gate-CGQTcR0I.js} +3 -3
  37. package/dist/dashboard/{conflict-gate-Bt-lLgYf.js.map → conflict-gate-CGQTcR0I.js.map} +1 -1
  38. package/dist/dashboard/{conversation-compaction-CsdCbcQB.js → conversation-compaction-C7P6V8Iw.js} +5 -5
  39. package/dist/dashboard/{conversation-compaction-CsdCbcQB.js.map → conversation-compaction-C7P6V8Iw.js.map} +1 -1
  40. package/dist/dashboard/{conversation-compaction-D0zgWM1f.js → conversation-compaction-Cck5oi-V.js} +1 -1
  41. package/dist/dashboard/{conversation-service-6LaymUV-.js → conversation-service-CsOpwI9Y.js} +37 -5
  42. package/dist/dashboard/{conversation-service-6LaymUV-.js.map → conversation-service-CsOpwI9Y.js.map} +1 -1
  43. package/dist/dashboard/conversation-service-plOFkoMo.js +3 -0
  44. package/dist/dashboard/dashboard-db-worker.js +1 -1
  45. package/dist/dashboard/{deacon-CU47dU7U.js → deacon-B8oMMIgN.js} +62 -62
  46. package/dist/dashboard/{deacon-CU47dU7U.js.map → deacon-B8oMMIgN.js.map} +1 -1
  47. package/dist/dashboard/{deacon-DYsOa_ss.js → deacon-b7J57Svt.js} +2 -2
  48. package/dist/dashboard/{deacon-pending-lifecycle-ijGX8wLb.js → deacon-pending-lifecycle-3NIJ7ew5.js} +2 -2
  49. package/dist/dashboard/{deacon-pending-lifecycle-ijGX8wLb.js.map → deacon-pending-lifecycle-3NIJ7ew5.js.map} +1 -1
  50. package/dist/dashboard/deacon.js +5 -5
  51. package/dist/dashboard/{delivery-DMYxIE0J.js → delivery-lnI-gQKo.js} +1 -1
  52. package/dist/dashboard/{deploy-patrol-C4eXco1S.js → deploy-patrol-u3v2krg9.js} +2 -2
  53. package/dist/dashboard/{deploy-patrol-C4eXco1S.js.map → deploy-patrol-u3v2krg9.js.map} +1 -1
  54. package/dist/dashboard/{feedback-stuck-retirement-Dd5XNrMr.js → feedback-stuck-retirement-CoFNqjCc.js} +2 -2
  55. package/dist/dashboard/{feedback-stuck-retirement-Dd5XNrMr.js.map → feedback-stuck-retirement-CoFNqjCc.js.map} +1 -1
  56. package/dist/dashboard/{feedback-target-BzdJ2wIR.js → feedback-target-BBCh3RRq.js} +1 -1
  57. package/dist/dashboard/{feedback-target-BcsA_GRV.js → feedback-target-CeCq6EhW.js} +5 -5
  58. package/dist/dashboard/{feedback-target-BcsA_GRV.js.map → feedback-target-CeCq6EhW.js.map} +1 -1
  59. package/dist/dashboard/{flywheel-Is3w2lcT.js → flywheel-DKldI63J.js} +7 -7
  60. package/dist/dashboard/{flywheel-Is3w2lcT.js.map → flywheel-DKldI63J.js.map} +1 -1
  61. package/dist/dashboard/{flywheel-D0guNqkh.js → flywheel-DpRPLErh.js} +7 -7
  62. package/dist/dashboard/{flywheel-D0guNqkh.js.map → flywheel-DpRPLErh.js.map} +1 -1
  63. package/dist/dashboard/{flywheel-B34cdfbd.js → flywheel-jeZFYvm-.js} +1 -1
  64. package/dist/dashboard/{flywheel-merge-order-6HiPR2WG.js → flywheel-merge-order-0OnoosaO.js} +1 -1
  65. package/dist/dashboard/{flywheel-merge-order-BsNPMu0S.js → flywheel-merge-order-PG5op4j7.js} +2 -2
  66. package/dist/dashboard/{flywheel-merge-order-BsNPMu0S.js.map → flywheel-merge-order-PG5op4j7.js.map} +1 -1
  67. package/dist/dashboard/{harness-resolve-CzTFVZ5l.js → harness-resolve-C0HWj3H9.js} +2 -2
  68. package/dist/dashboard/{harness-resolve-CzTFVZ5l.js.map → harness-resolve-C0HWj3H9.js.map} +1 -1
  69. package/dist/dashboard/{identity-Dc7rQLln.js → identity-Cot1Hg4G.js} +2 -2
  70. package/dist/dashboard/{identity-Dc7rQLln.js.map → identity-Cot1Hg4G.js.map} +1 -1
  71. package/dist/dashboard/{inspect-agent-CP7Bu47O.js → inspect-agent-BDmLWbGx.js} +3 -3
  72. package/dist/dashboard/{inspect-agent-CP7Bu47O.js.map → inspect-agent-BDmLWbGx.js.map} +1 -1
  73. package/dist/dashboard/inspect-agent-BcOkA-hC.js +2 -0
  74. package/dist/dashboard/{issue-lifecycle-BPbczKyy.js → issue-lifecycle-1B_v8Rf5.js} +6 -6
  75. package/dist/dashboard/{issue-lifecycle-BPbczKyy.js.map → issue-lifecycle-1B_v8Rf5.js.map} +1 -1
  76. package/dist/dashboard/{issue-lifecycle-FaugTi39.js → issue-lifecycle-CIrfbIbj.js} +1 -1
  77. package/dist/dashboard/{issue-service-singleton-Dsad9NTt.js → issue-service-singleton-BVwPzjwF.js} +1 -1
  78. package/dist/dashboard/{issue-service-singleton-BrZQJLRI.js → issue-service-singleton-KcRrOiFD.js} +2 -2
  79. package/dist/dashboard/{issue-service-singleton-BrZQJLRI.js.map → issue-service-singleton-KcRrOiFD.js.map} +1 -1
  80. package/dist/dashboard/{jsonl-resolver-DQEe0DHM.js → jsonl-resolver-jxbif7MD.js} +3 -3
  81. package/dist/dashboard/{jsonl-resolver-DQEe0DHM.js.map → jsonl-resolver-jxbif7MD.js.map} +1 -1
  82. package/dist/dashboard/{kimi-code-Cx5YUJpS.js → kimi-code-BZh3NgcN.js} +1 -1
  83. package/dist/dashboard/{lifecycle-DZFHmpGI.js → lifecycle-CvcZ4_fA.js} +4 -4
  84. package/dist/dashboard/{lifecycle-DZFHmpGI.js.map → lifecycle-CvcZ4_fA.js.map} +1 -1
  85. package/dist/dashboard/{linear-mcp-auth-DylPJABZ.js → linear-mcp-auth-CZoj_-d7.js} +1 -1
  86. package/dist/dashboard/{linear-mcp-auth-BFlpMvWh.js → linear-mcp-auth-Dx74yCAY.js} +2 -2
  87. package/dist/dashboard/{linear-mcp-auth-BFlpMvWh.js.map → linear-mcp-auth-Dx74yCAY.js.map} +1 -1
  88. package/dist/dashboard/{memory-governor-B7uDWRo9.js → memory-governor-Bv3LAqk3.js} +5 -5
  89. package/dist/dashboard/{memory-governor-B7uDWRo9.js.map → memory-governor-Bv3LAqk3.js.map} +1 -1
  90. package/dist/dashboard/{merge-agent-ddEcZDZD.js → merge-agent-1zVLl6k_.js} +1 -1
  91. package/dist/dashboard/{merge-agent-ttRY053V.js → merge-agent-8zrQu48t.js} +8 -8
  92. package/dist/dashboard/{merge-agent-ttRY053V.js.map → merge-agent-8zrQu48t.js.map} +1 -1
  93. package/dist/dashboard/merge-ops-CFJaMPLu.js +2 -0
  94. package/dist/dashboard/{merge-train-f_un38UJ.js → merge-train-BYH_cF7G.js} +2 -2
  95. package/dist/dashboard/{merge-train-f_un38UJ.js.map → merge-train-BYH_cF7G.js.map} +1 -1
  96. package/dist/dashboard/{merge-train-deps-GPlHOjK6.js → merge-train-deps-BTfXM5AR.js} +2 -2
  97. package/dist/dashboard/{merge-train-deps-GPlHOjK6.js.map → merge-train-deps-BTfXM5AR.js.map} +1 -1
  98. package/dist/dashboard/{messaging-BasbftDu.js → messaging-Bk6vGsMw.js} +1 -1
  99. package/dist/dashboard/{orphan-proposed-reconciler-DFHdQSEg.js → orphan-proposed-reconciler-B898fk26.js} +6 -6
  100. package/dist/dashboard/{orphan-proposed-reconciler-DFHdQSEg.js.map → orphan-proposed-reconciler-B898fk26.js.map} +1 -1
  101. package/dist/dashboard/{orphan-proposed-reconciler-DzAxrM99.js → orphan-proposed-reconciler-Bx_aWS4B.js} +1 -1
  102. package/dist/dashboard/{parked-residue-DMtbxJml.js → parked-residue-q2kzrYSm.js} +9 -9
  103. package/dist/dashboard/{parked-residue-DMtbxJml.js.map → parked-residue-q2kzrYSm.js.map} +1 -1
  104. package/dist/dashboard/{post-merge-lifecycle-worker-jzN2g_EY.js → post-merge-lifecycle-worker-Cl7-uf4g.js} +2 -2
  105. package/dist/dashboard/{post-merge-lifecycle-worker-jzN2g_EY.js.map → post-merge-lifecycle-worker-Cl7-uf4g.js.map} +1 -1
  106. package/dist/dashboard/{project-resource-refresh-queue-cqOeJ0fB.js → project-resource-refresh-queue-O_dRfPHn.js} +1 -1
  107. package/dist/dashboard/{project-resource-refresh-queue-DebwjPPA.js → project-resource-refresh-queue-se3T9IYP.js} +4 -4
  108. package/dist/dashboard/{project-resource-refresh-queue-DebwjPPA.js.map → project-resource-refresh-queue-se3T9IYP.js.map} +1 -1
  109. package/dist/dashboard/{reconstruct-cache-Bb2Jg2DZ.js → reconstruct-cache-XpWC9L0F.js} +2 -2
  110. package/dist/dashboard/{reconstruct-cache-Bb2Jg2DZ.js.map → reconstruct-cache-XpWC9L0F.js.map} +1 -1
  111. package/dist/dashboard/{release-engine-78iCajIc.js → release-engine-BuzxOamf.js} +2 -2
  112. package/dist/dashboard/{release-engine-78iCajIc.js.map → release-engine-BuzxOamf.js.map} +1 -1
  113. package/dist/dashboard/{remote-completion-D5wzZCte.js → remote-completion-BCZgeKPS.js} +3 -3
  114. package/dist/dashboard/{remote-completion-D5wzZCte.js.map → remote-completion-BCZgeKPS.js.map} +1 -1
  115. package/dist/dashboard/{resolver-BGZh3lXA.js → resolver-BeNrqNou.js} +5 -5
  116. package/dist/dashboard/{resolver-BGZh3lXA.js.map → resolver-BeNrqNou.js.map} +1 -1
  117. package/dist/dashboard/{resource-pressure-patrol-Bg23rPV-.js → resource-pressure-patrol-Ccg_aCgO.js} +3 -3
  118. package/dist/dashboard/{resource-pressure-patrol-Bg23rPV-.js.map → resource-pressure-patrol-Ccg_aCgO.js.map} +1 -1
  119. package/dist/dashboard/{resume-BKyB4hA1.js → resume-KGCrn0DV.js} +1 -1
  120. package/dist/dashboard/{review-agent-ZdP-HmwY.js → review-agent-BmM6YMZW.js} +1 -1
  121. package/dist/dashboard/{review-agent-DHs-JngN.js → review-agent-DRWVU8fP.js} +13 -13
  122. package/dist/dashboard/{review-agent-DHs-JngN.js.map → review-agent-DRWVU8fP.js.map} +1 -1
  123. package/dist/dashboard/{review-convoy-liveness-BTMvU4CA.js → review-convoy-liveness-EvCDv8Q_.js} +3 -3
  124. package/dist/dashboard/{review-convoy-liveness-BTMvU4CA.js.map → review-convoy-liveness-EvCDv8Q_.js.map} +1 -1
  125. package/dist/dashboard/{review-run-recovery-BYalQzbh.js → review-run-recovery-Ctm48Snt.js} +1 -1
  126. package/dist/dashboard/{review-run-recovery-BvVG3oUr.js → review-run-recovery-DNDI58cM.js} +2 -2
  127. package/dist/dashboard/{review-run-recovery-BvVG3oUr.js.map → review-run-recovery-DNDI58cM.js.map} +1 -1
  128. package/dist/dashboard/{review-status-DXTFzCmR.js → review-status-FnlvQuPI.js} +1 -1
  129. package/dist/dashboard/{review-status-emit-C9YW6SQL.js → review-status-emit-CeMS31DX.js} +2 -2
  130. package/dist/dashboard/{review-status-emit-C9YW6SQL.js.map → review-status-emit-CeMS31DX.js.map} +1 -1
  131. package/dist/dashboard/{review-status-BegAr86G.js → review-status-yY5qt7Rl.js} +5 -5
  132. package/dist/dashboard/{review-status-BegAr86G.js.map → review-status-yY5qt7Rl.js.map} +1 -1
  133. package/dist/dashboard/{review-verdict-feedback-qlVBi19-.js → review-verdict-feedback-BNgRj1e3.js} +4 -4
  134. package/dist/dashboard/{review-verdict-feedback-qlVBi19-.js.map → review-verdict-feedback-BNgRj1e3.js.map} +1 -1
  135. package/dist/dashboard/{review-verdict-feedback-Dp139Lmv.js → review-verdict-feedback-D39cuSV1.js} +1 -1
  136. package/dist/dashboard/{review-verdict-writer-CJr_Ob0Y.js → review-verdict-writer-DvFfKAn-.js} +2 -2
  137. package/dist/dashboard/{review-verdict-writer-CJr_Ob0Y.js.map → review-verdict-writer-DvFfKAn-.js.map} +1 -1
  138. package/dist/dashboard/{review-verdict-writer-BVco3WoI.js → review-verdict-writer-PcGBkvJ4.js} +1 -1
  139. package/dist/dashboard/{sequence-io-iljWlslY.js → sequence-io-DZyschsf.js} +2 -2
  140. package/dist/dashboard/{sequence-io-iljWlslY.js.map → sequence-io-DZyschsf.js.map} +1 -1
  141. package/dist/dashboard/{sequencer-agent-BGGVKxtw.js → sequencer-agent-BXDw5cNx.js} +5 -5
  142. package/dist/dashboard/{sequencer-agent-BGGVKxtw.js.map → sequencer-agent-BXDw5cNx.js.map} +1 -1
  143. package/dist/dashboard/server.js +79 -72
  144. package/dist/dashboard/server.js.map +1 -1
  145. package/dist/dashboard/{service-kzhN0DLg.js → service-DP50Omvn.js} +33 -33
  146. package/dist/dashboard/{service-kzhN0DLg.js.map → service-DP50Omvn.js.map} +1 -1
  147. package/dist/dashboard/{smart-compaction-owKHJDbL.js → smart-compaction-944GL8PN.js} +1 -1
  148. package/dist/dashboard/{smart-compaction-C96F2aFQ.js → smart-compaction-BzDfF6yb.js} +2 -2
  149. package/dist/dashboard/{smart-compaction-C96F2aFQ.js.map → smart-compaction-BzDfF6yb.js.map} +1 -1
  150. package/dist/dashboard/{spawn-planning-session-CiJdOHTD.js → spawn-planning-session-BcVnHJjm.js} +1 -1
  151. package/dist/dashboard/{spawn-planning-session-FmJa6PCS.js → spawn-planning-session-CH8IYli7.js} +3 -3
  152. package/dist/dashboard/{spawn-planning-session-FmJa6PCS.js.map → spawn-planning-session-CH8IYli7.js.map} +1 -1
  153. package/dist/dashboard/{specialist-context-_ootmzn2.js → specialist-context-DhDTXVht.js} +3 -3
  154. package/dist/dashboard/{specialist-context-_ootmzn2.js.map → specialist-context-DhDTXVht.js.map} +1 -1
  155. package/dist/dashboard/{specialist-logs-BbAX221-.js → specialist-logs-C1bcnZ-G.js} +2 -2
  156. package/dist/dashboard/{specialist-logs-BbAX221-.js.map → specialist-logs-C1bcnZ-G.js.map} +1 -1
  157. package/dist/dashboard/{specialists-COZoYaiz.js → specialists-BKmReEWT.js} +53 -53
  158. package/dist/dashboard/{specialists-COZoYaiz.js.map → specialists-BKmReEWT.js.map} +1 -1
  159. package/dist/dashboard/{specialists-RPLJnYc1.js → specialists-Bvrvt0br.js} +12 -12
  160. package/dist/dashboard/{specialists-RPLJnYc1.js.map → specialists-Bvrvt0br.js.map} +1 -1
  161. package/dist/dashboard/{specialists-DTAOVZpU.js → specialists-CD6GEKXk.js} +1 -1
  162. package/dist/dashboard/{specialists-D8sYZnPb.js → specialists-eFWpJRBc.js} +1 -1
  163. package/dist/dashboard/{stall-sweeper-9bRBZhrQ.js → stall-sweeper-D3fZvg7O.js} +3 -3
  164. package/dist/dashboard/{stall-sweeper-9bRBZhrQ.js.map → stall-sweeper-D3fZvg7O.js.map} +1 -1
  165. package/dist/dashboard/{state-migrate-J3tFJnbd.js → state-migrate-KZ2goscQ.js} +2 -2
  166. package/dist/dashboard/{state-migrate-J3tFJnbd.js.map → state-migrate-KZ2goscQ.js.map} +1 -1
  167. package/dist/dashboard/{stuck-remediation-BvTK_NYN.js → stuck-remediation-Cb2V1roj.js} +1 -1
  168. package/dist/dashboard/{stuck-remediation-4Rf_xMEb.js → stuck-remediation-CnoV0kcv.js} +5 -5
  169. package/dist/dashboard/{stuck-remediation-4Rf_xMEb.js.map → stuck-remediation-CnoV0kcv.js.map} +1 -1
  170. package/dist/dashboard/{summary-fork-PLcckTRE.js → summary-fork-CxuNBM0F.js} +2 -2
  171. package/dist/dashboard/{summary-fork-D-cylknJ.js → summary-fork-lC2vMXly.js} +4 -4
  172. package/dist/dashboard/{summary-fork-D-cylknJ.js.map → summary-fork-lC2vMXly.js.map} +1 -1
  173. package/dist/dashboard/{teardown-workspace-CTL16rnG.js → teardown-workspace-C-9murBw.js} +4 -4
  174. package/dist/dashboard/{teardown-workspace-CTL16rnG.js.map → teardown-workspace-C-9murBw.js.map} +1 -1
  175. package/dist/dashboard/{test-agent-queue-CMgYZiR_.js → test-agent-queue-YCBRzaAB.js} +3 -3
  176. package/dist/dashboard/{test-agent-queue-CMgYZiR_.js.map → test-agent-queue-YCBRzaAB.js.map} +1 -1
  177. package/dist/dashboard/{uat-failure-feedback-DS6W9X3I.js → uat-failure-feedback-B-1mL8Zp.js} +3 -3
  178. package/dist/dashboard/{uat-failure-feedback-DS6W9X3I.js.map → uat-failure-feedback-B-1mL8Zp.js.map} +1 -1
  179. package/dist/dashboard/{uat-promote-verification-CRsIHE_q.js → uat-promote-verification-BEBPcpPg.js} +2 -2
  180. package/dist/dashboard/{uat-promote-verification-CRsIHE_q.js.map → uat-promote-verification-BEBPcpPg.js.map} +1 -1
  181. package/dist/dashboard/{uat-train-BoA9r6_I.js → uat-train-BFo3OQUB.js} +1 -1
  182. package/dist/dashboard/{uat-train-Cd8CJeNe.js → uat-train-COgoJomz.js} +8 -8
  183. package/dist/dashboard/{uat-train-Cd8CJeNe.js.map → uat-train-COgoJomz.js.map} +1 -1
  184. package/dist/dashboard/{validate-BdmvTIym.js → validate-069_N1e2.js} +2 -2
  185. package/dist/dashboard/{validate-BdmvTIym.js.map → validate-069_N1e2.js.map} +1 -1
  186. package/dist/dashboard/{verification-runner-BO0K3xNA.js → verification-runner-CQnZyC5A.js} +1 -1
  187. package/dist/dashboard/{verification-runner-fEY1Qj-l.js → verification-runner-fy3wNrWn.js} +4 -4
  188. package/dist/dashboard/{verification-runner-fEY1Qj-l.js.map → verification-runner-fy3wNrWn.js.map} +1 -1
  189. package/dist/dashboard/workflows-Bk6Kt0ZQ.js +2 -0
  190. package/dist/dashboard/{workflows-CxVnygYU.js → workflows-N4QMkDzN.js} +10 -10
  191. package/dist/dashboard/{workflows-CxVnygYU.js.map → workflows-N4QMkDzN.js.map} +1 -1
  192. package/dist/dashboard/{workspaces-Cpz0xJWQ.js → workspaces-DmoyfHoU.js} +33 -33
  193. package/dist/dashboard/{workspaces-Cpz0xJWQ.js.map → workspaces-DmoyfHoU.js.map} +1 -1
  194. package/dist/{lifecycle-C6k0HWEO.js → lifecycle-DCFcjg7y.js} +1 -1
  195. package/dist/{lifecycle-D5oRpvvB.js → lifecycle-GkaHQJNK.js} +2 -2
  196. package/dist/{lifecycle-D5oRpvvB.js.map → lifecycle-GkaHQJNK.js.map} +1 -1
  197. package/dist/{merge-agent-Drufc7tU.js → merge-agent-CogNFasY.js} +2 -2
  198. package/dist/{merge-agent-Drufc7tU.js.map → merge-agent-CogNFasY.js.map} +1 -1
  199. package/dist/{merge-agent-CBOVY_eC.js → merge-agent-eteKQ9Rb.js} +1 -1
  200. package/package.json +1 -1
  201. package/dist/build-info-BgrwLUy6.js +0 -2
  202. package/dist/dashboard/agent-state-Ci6PhjOE.js.map +0 -1
  203. package/dist/dashboard/build-info-CYlxvZSQ.js +0 -2
  204. package/dist/dashboard/cli-ZAS502uC.js +0 -2
  205. package/dist/dashboard/conversation-service-Dlks_hSS.js +0 -3
  206. package/dist/dashboard/inspect-agent-DTuSg95i.js +0 -2
  207. package/dist/dashboard/merge-ops-Bgc-EScO.js +0 -2
  208. package/dist/dashboard/workflows-CgGNyl1z.js +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"review-status-BegAr86G.js","names":["existsSync","fsp","readFileSync","readdirSync","existsSync","join","dirname","sep","posix","PostHogPersistedProperty","createReadStream","ErrorTracking.ReduceableCache","sep","isAbsolute","relative","error_tracking","PostHogPersistedProperty","#_","ErrorTracking.ErrorPropertiesBuilder","ErrorTracking.EventCoercer","ErrorTracking.ErrorCoercer","ErrorTracking.ObjectCoercer","ErrorTracking.StringCoercer","ErrorTracking.PrimitiveCoercer","ErrorTracking.createStackParser","ErrorTracking.nodeStackLineParser","readFileSync","statSync","readFileSync","join","dbDelete"],"sources":["../../src/lib/pan-dir/record-lock.ts","../../src/lib/pan-dir/pipeline-verdict-merge.ts","../../src/lib/pan-dir/records.ts","../../src/lib/overdeck/review-status-record-sync.ts","../../src/lib/review-findings.ts","../../src/lib/cloister/review-convergence.ts","../../src/lib/review-status-reconcile.ts","../../src/lib/review-dispatch-decision.ts","../../src/lib/review-status-read.ts","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/featureFlagUtils.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/types.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/gzip.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/utils/bot-detection.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/utils/string-utils.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/utils/type-utils.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/utils/number-utils.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/utils/bucketed-rate-limiter.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/vendor/uuidv7.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/utils/promise-queue.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/utils/logger.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/utils/user-agent-utils.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/utils/index.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/logs/logs-utils.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/logs/index.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/metrics/metrics-utils.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/metrics/config.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/metrics/index.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/cookie.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/eventemitter.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/chunk-ids.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/error-properties-builder.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/parsers/base.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/parsers/safari.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/parsers/chrome.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/parsers/gecko.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/parsers/winjs.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/parsers/opera.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/parsers/node.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/parsers/index.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/coercers/dom-exception-coercer.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/coercers/error-coercer.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/coercers/error-event-coercer.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/coercers/string-coercer.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/types.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/coercers/utils.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/coercers/event-coercer.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/coercers/primitive-coercer.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/coercers/promise-rejection-event.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/coercers/index.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/utils.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/exception-steps.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/index.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/posthog-core-stateless.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/posthog-core.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/tracing-headers.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/index.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/context-lines.node.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/relative-path.node.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/version.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/types.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/feature-flag-evaluations.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/extensions/feature-flags/crypto.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/extensions/feature-flags/feature-flags.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/extensions/error-tracking/autocapture.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/extensions/error-tracking/index.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/storage-memory.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/capture-v1/config.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/capture-v1/routing.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/capture-v1/errors.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/capture-v1/transform.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/capture-v1/sender.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/client.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/extensions/context/context.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/extensions/sentry-integration.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/extensions/url-utils.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/extensions/express.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/exports.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/entrypoints/index.node.mjs","../../src/lib/telemetry/config.ts","../../src/lib/telemetry/install-id.ts","../../src/lib/telemetry/service.ts","../../src/lib/telemetry/pipeline.ts","../../src/lib/review-verdict-guards.ts","../../src/lib/review-status.ts"],"sourcesContent":["const issueRecordLocks = new Map<string, Promise<void>>();\n\n/**\n * Serialize async read-modify-write rebuilds for a single issue record.\n *\n * Synchronous record writers remain synchronous; async flows that read, await,\n * then write the whole record must use this lock so same-issue rebuilds cannot\n * overwrite each other's final re-read.\n */\nexport async function withIssueRecordLock<T>(\n issueId: string,\n fn: () => T | Promise<T>,\n): Promise<T> {\n const key = issueId.toUpperCase();\n const previous = issueRecordLocks.get(key) ?? Promise.resolve();\n let release: () => void = () => {};\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n const chain = previous.catch(() => undefined).then(() => current);\n issueRecordLocks.set(key, chain);\n\n await previous.catch(() => undefined);\n\n try {\n return await fn();\n } finally {\n release();\n if (issueRecordLocks.get(key) === chain) {\n issueRecordLocks.delete(key);\n }\n }\n}\n","/**\n * PAN-3092: verdict-aware pipeline merge.\n *\n * `pipeline.updatedAt` is stamped on EVERY status write (projectPipeline,\n * records.ts), verdict or not, so a plain newer-wins comparison conflates\n * write-recency with verdict-truth: a verdict-free write that lands a second\n * after a reviewer's `passed` makes the passed verdict look like the older\n * truth and silently drops it (observed on MIN-902, where the review verdict\n * ended up in no persisted plane at all).\n *\n * The rule here keeps PAN-2587's newer-wins default for every non-verdict\n * field while refusing to regress a gate that already reached a terminal\n * verdict inside the same review cycle. A strictly newer `reviewSpawnedAt`\n * (a genuinely new review cycle) and a newer terminal verdict both still win.\n */\n\nimport type { PanIssuePipelineRecord } from './record.js';\n\n/**\n * Terminal verdict values per gate. Everything else — pending, reviewing,\n * testing, merging, queued, dispatch_failed, undefined — is a non-verdict\n * state that must never overwrite a terminal one inside the same cycle.\n */\nexport const TERMINAL_GATE_VALUES = {\n reviewStatus: ['passed', 'blocked', 'failed', 'skipped'],\n testStatus: ['passed', 'failed'],\n uatStatus: ['passed', 'failed'],\n verificationStatus: ['passed', 'failed', 'skipped'],\n inspectStatus: ['passed', 'blocked', 'failed'],\n mergeStatus: ['merged', 'failed'],\n} as const satisfies Record<string, readonly string[]>;\n\n/** Fields that carry a gate's evidence and must move with its status as one unit. */\nexport const GATE_COMPANIONS = {\n reviewStatus: ['reviewNotes', 'reviewedAtCommit'],\n testStatus: ['testNotes'],\n uatStatus: ['uatNotes'],\n verificationStatus: ['verificationNotes', 'lastVerifiedCommit'],\n inspectStatus: ['inspectNotes'],\n mergeStatus: ['mergeNotes', 'mergeStep'],\n} as const satisfies Record<keyof typeof TERMINAL_GATE_VALUES, readonly string[]>;\n\ntype GateName = keyof typeof TERMINAL_GATE_VALUES;\n\nconst GATE_NAMES = Object.keys(TERMINAL_GATE_VALUES) as GateName[];\n\n/**\n * Field-level view of a pipeline block. The two callers pass different declared\n * shapes (the record's `PanIssuePipelineRecord`, the fallback's\n * `Partial<ReviewStatus>` subset) and neither declares every gate, so gate\n * access goes through one loose view rather than six casts.\n */\ntype PipelineFields = Record<string, unknown>;\n\nfunction fields(pipeline: unknown): PipelineFields {\n return pipeline as PipelineFields;\n}\n\nfunction isTerminal(gate: GateName, value: unknown): boolean {\n return typeof value === 'string' && (TERMINAL_GATE_VALUES[gate] as readonly string[]).includes(value);\n}\n\n/** Milliseconds for an ISO/epoch cycle marker, or undefined when it does not parse. */\nfunction cycleMs(value: unknown): number | undefined {\n if (typeof value === 'number') return Number.isFinite(value) ? value : undefined;\n if (typeof value !== 'string') return undefined;\n const parsed = Date.parse(value);\n return Number.isNaN(parsed) ? undefined : parsed;\n}\n\nfunction reviewCycleMs(pipeline: PipelineFields): number | undefined {\n const spawned = cycleMs(pipeline.reviewSpawnedAt);\n const requested = cycleMs(pipeline.reviewRequestedAt);\n if (spawned === undefined) return requested;\n if (requested === undefined) return spawned;\n return Math.max(spawned, requested);\n}\n\nfunction carriesTerminalVerdict(pipeline: PipelineFields): boolean {\n return GATE_NAMES.some((gate) => isTerminal(gate, pipeline[gate]));\n}\n\nexport interface StaleVerdictSnapshot {\n liveCycle: number;\n snapshotCycle?: number;\n liveHead?: string;\n snapshotHead?: string;\n}\n\n/**\n * A pending/reviewing row with a newer review obligation owns the current cycle.\n * An older terminal snapshot is historical evidence and must not replace it,\n * regardless of which whole-pipeline `updatedAt` happens to be newer.\n */\nexport function staleVerdictSnapshotAgainstLiveCycle(\n live: PipelineFields,\n snapshot: PipelineFields,\n): StaleVerdictSnapshot | null {\n const liveReviewStatus = live.reviewStatus;\n const liveSpawned = cycleMs(live.reviewSpawnedAt);\n const liveRequested = cycleMs(live.reviewRequestedAt);\n const liveCycle = reviewCycleMs(live);\n const snapshotCycle = reviewCycleMs(snapshot);\n const liveCycleActive = liveReviewStatus === 'reviewing'\n || (liveReviewStatus === 'pending'\n && liveRequested !== undefined\n && (liveSpawned === undefined || liveRequested > liveSpawned));\n\n if (\n !liveCycleActive\n || liveCycle === undefined\n || snapshotCycle === undefined\n || !carriesTerminalVerdict(snapshot)\n || snapshotCycle >= liveCycle\n ) return null;\n\n return {\n liveCycle,\n snapshotCycle,\n liveHead: typeof live.prHeadSha === 'string'\n ? live.prHeadSha\n : typeof live.lastVerifiedCommit === 'string'\n ? live.lastVerifiedCommit\n : typeof live.reviewedAtCommit === 'string'\n ? live.reviewedAtCommit\n : undefined,\n snapshotHead: typeof snapshot.reviewedAtCommit === 'string'\n ? snapshot.reviewedAtCommit\n : typeof snapshot.lastVerifiedCommit === 'string'\n ? snapshot.lastVerifiedCommit\n : typeof snapshot.prHeadSha === 'string'\n ? snapshot.prHeadSha\n : undefined,\n };\n}\n\n/**\n * Merge a freshly-read on-disk pipeline over a rebuilt one without losing a\n * terminal verdict the rebuild carries.\n *\n * Order of rules:\n * 1. Either side lacks `updatedAt` → the rebuilt block wins (PAN-2587 guard).\n * 2. The rebuilt block is at least as new → it wins outright (PAN-2587).\n * 3. Otherwise `fresh` is the base — newer-wins for every non-verdict field.\n * 4. `fresh` belongs to a strictly newer review cycle → it wins wholesale;\n * a new cycle legitimately resets the previous cycle's verdicts.\n * 5. Any gate where `rebuilt` holds a terminal verdict and the base does not\n * keeps the rebuilt status plus its companion fields.\n */\nexport function mergePipelineVerdictAware(\n rebuilt: PanIssuePipelineRecord,\n fresh: PanIssuePipelineRecord | undefined,\n): PanIssuePipelineRecord {\n if (!fresh?.updatedAt || !rebuilt?.updatedAt) return rebuilt;\n if (!(rebuilt.updatedAt < fresh.updatedAt)) return rebuilt;\n\n const rebuiltCycle = reviewCycleMs(fields(rebuilt));\n const freshCycle = reviewCycleMs(fields(fresh));\n if (rebuiltCycle !== undefined && freshCycle !== undefined && freshCycle > rebuiltCycle) {\n return fresh;\n }\n\n // Cloned lazily: when no gate needs preserving the caller gets the identical\n // `fresh` object back, which is exactly PAN-2587's behavior.\n let merged: PanIssuePipelineRecord | undefined;\n for (const gate of GATE_NAMES) {\n if (!isTerminal(gate, fields(rebuilt)[gate]) || isTerminal(gate, fields(fresh)[gate])) continue;\n merged ??= structuredClone(fresh);\n const target = fields(merged);\n const source = fields(rebuilt);\n for (const field of [gate, ...GATE_COMPANIONS[gate]]) {\n if (source[field] === undefined) delete target[field];\n else target[field] = source[field];\n }\n }\n return merged ?? fresh;\n}\n\n/**\n * Does this status update drive some gate to a terminal verdict it was not\n * already at? That is the write an agent cannot cheaply retry — losing it\n * strands the verdict in the agent's pane — so the journal writer waits out lock\n * contention for it instead of dropping to the workspace fallback on the first\n * collision (PAN-3092). Bookkeeping writes stay single-shot; retrying those\n * would only add lock pressure.\n */\nexport function carriesNewTerminalVerdict(\n previous: PipelineFields,\n update: PipelineFields,\n): boolean {\n return GATE_NAMES.some((gate) => {\n const next = update[gate];\n return next !== undefined && next !== previous[gate] && isTerminal(gate, next);\n });\n}\n\n/**\n * Has the journal settled every gate the workspace fallback holds a terminal\n * verdict for? The drain asks this before deleting a fallback as superseded: a\n * newer-but-verdict-free journal write must not consume a verdict that never\n * landed anywhere (PAN-3092; MIN-902 lost its review verdict exactly this way).\n *\n * Coverage is per-gate VALUE equality, not merely \"the journal reached some\n * terminal value\". `pipeline.updatedAt` is restamped by unrelated bookkeeping —\n * the root defect this issue exists for — so a later whole-pipeline timestamp is\n * no evidence that a journal's differing terminal value is the newer one; it may\n * be an older verdict carried forward while the newer specialist result waits in\n * the fallback. When the values differ the fallback is folded instead, and\n * `mergePipelineVerdictAware` decides the winner from per-gate evidence.\n */\nexport function pipelineCoversFallbackVerdicts(\n journal: PanIssuePipelineRecord,\n fallback: { updatedAt: string; pipeline: PipelineFields },\n): boolean {\n const journalCycle = reviewCycleMs(fields(journal));\n const fallbackCycle = reviewCycleMs(fallback.pipeline);\n const fallbackWrittenMs = cycleMs(fallback.updatedAt);\n if (\n journalCycle !== undefined\n && ((fallbackCycle !== undefined && journalCycle > fallbackCycle)\n || (fallbackCycle === undefined && fallbackWrittenMs !== undefined && journalCycle > fallbackWrittenMs))\n ) {\n return true;\n }\n\n const journalFields = fields(journal);\n const fallbackFields = fields(fallback.pipeline);\n for (const gate of GATE_NAMES) {\n const held = fallbackFields[gate];\n if (!isTerminal(gate, held)) continue;\n if (journalFields[gate] !== held) return false;\n }\n return true;\n}\n\n/** One gate holding two different written terminal verdicts. */\nexport interface VerdictConflict {\n gate: string;\n journalValue: string;\n fallbackValue: string;\n}\n\n/**\n * Which gates hold DIFFERENT terminal verdicts in the journal and the fallback,\n * within the same review cycle?\n *\n * This is the one case the drain cannot resolve: two written terminal verdicts\n * for one gate, and no per-gate timestamp to order them by. The whole-pipeline\n * `updatedAt` is restamped by unrelated bookkeeping, so \"the journal's is newer\"\n * is exactly the inference PAN-3092 exists to stop making. Callers preserve the\n * fallback and let the stranded-fallback sweep put the conflict in front of an\n * operator rather than picking a winner.\n */\nexport function findFallbackVerdictConflicts(\n journal: PanIssuePipelineRecord,\n fallback: { updatedAt: string; pipeline: PipelineFields },\n): VerdictConflict[] {\n const journalCycle = reviewCycleMs(fields(journal));\n const fallbackCycle = reviewCycleMs(fallback.pipeline);\n const fallbackWrittenMs = cycleMs(fallback.updatedAt);\n // A newer review cycle legitimately resets the previous cycle's verdicts.\n if (\n journalCycle !== undefined\n && ((fallbackCycle !== undefined && journalCycle > fallbackCycle)\n || (fallbackCycle === undefined && fallbackWrittenMs !== undefined && journalCycle > fallbackWrittenMs))\n ) {\n return [];\n }\n\n const journalFields = fields(journal);\n const fallbackFields = fields(fallback.pipeline);\n const conflicts: VerdictConflict[] = [];\n for (const gate of GATE_NAMES) {\n const held = fallbackFields[gate];\n if (!isTerminal(gate, held)) continue;\n const settled = journalFields[gate];\n if (!isTerminal(gate, settled) || settled === held) continue;\n conflicts.push({ gate, journalValue: String(settled), fallbackValue: String(held) });\n }\n return conflicts;\n}\n\n/** Boolean form of {@link findFallbackVerdictConflicts} for the drain's withhold decision. */\nexport function pipelineConflictsWithFallbackVerdicts(\n journal: PanIssuePipelineRecord,\n fallback: { updatedAt: string; pipeline: PipelineFields },\n): boolean {\n return findFallbackVerdictConflicts(journal, fallback).length > 0;\n}\n","/**\n * PAN-1908 / PAN-1919: per-issue permanent-record builder.\n *\n * Builds a single JSON record per issue from SQLite (pipeline verdicts, usage,\n * merges) plus the legacy project-side continue file. The actual read/write/path\n * helpers live in `record.ts` (PAN-1919 single-writer module) and write the\n * record onto the feature branch at `<workspace>/.pan/records/<issue>.json`.\n */\n\nimport { hostname } from 'node:os';\nimport { join } from 'node:path';\nimport { existsSync, promises as fsp } from 'node:fs';\nimport { PAN_CONTINUES_DIRNAME, PAN_DIRNAME } from './types.js';\n\n// ─── Types ────────────────────────────────────────────────────────────────────\nimport {\n getCostBreakdownByStageAndModelSync,\n getCostForIssueSync,\n} from '../overdeck/cost-sync.js';\nimport { getMergeSetSync } from '../merge-set.js';\nimport {\n findProjectByPathSync,\n getProjectSync,\n resolveProjectFromIssueSync,\n type ProjectConfig,\n} from '../projects.js';\nimport { resolveStateReadHomeSync } from '../state-read-home.js';\nimport type { ReviewStatus } from '../review-status-types.js';\nimport type { RuntimeName } from '../runtimes/types.js';\nimport type {\n ContinueDecision,\n ContinueFeedbackEntry,\n ContinueHazard,\n ContinueResumePoint,\n ContinueSessionEntry,\n ScopeDriftRecord,\n} from '../xbrief/continue-state.js';\nimport {\n LEGACY_VBRIEF_FILENAME_SUFFIX,\n XBRIEF_FILENAME_SUFFIX,\n} from '../xbrief/lifecycle.js';\nimport { listOverdeckAgentStatesSync } from '../overdeck/agent-state-sync.js';\nimport {\n getIssueWorkspacePath,\n RECORD_SCHEMA_VERSION,\n readIssueRecord,\n readIssueRecordSync,\n type PanIssueRecord,\n type PanIssuePipelineRecord,\n type PanIssueUsageRecord,\n} from './record.js';\nimport { updateIssueRecord } from './record-update.js';\nimport { withIssueRecordLock } from './record-lock.js';\nimport { mergePipelineVerdictAware } from './pipeline-verdict-merge.js';\n\nexport type {\n PanIssueRecord,\n PanIssueCloseOutRecord,\n PanIssuePipelineRecord,\n PanIssueUsageRecord,\n} from './record.js';\n\n// ─── Continue projection ──────────────────────────────────────────────────────\n\ninterface ContinueFile {\n issueId?: string;\n gitState?: { branch?: string };\n decisions?: ContinueDecision[];\n hazards?: ContinueHazard[];\n resumePoint?: ContinueResumePoint | null;\n sessionHistory?: ContinueSessionEntry[];\n feedback?: ContinueFeedbackEntry[];\n agentModel?: string;\n scopeDrift?: ScopeDriftRecord;\n}\n\nfunction projectContinue(raw: ContinueFile | null): Pick<PanIssueRecord, 'decisions' | 'hazards' | 'resumePoint' | 'sessionHistory' | 'feedback' | 'scopeDrift'> {\n return {\n decisions: raw?.decisions,\n hazards: raw?.hazards,\n resumePoint: raw?.resumePoint,\n sessionHistory: raw?.sessionHistory,\n feedback: raw?.feedback ?? [],\n scopeDrift: raw?.scopeDrift,\n };\n}\n\n// ─── Pipeline projection ──────────────────────────────────────────────────────\n\nexport function projectPipeline(\n issueId: string,\n status: ReviewStatus | null,\n existing?: PanIssuePipelineRecord,\n): PanIssuePipelineRecord {\n const base: PanIssuePipelineRecord = {\n issueId,\n reviewStatus: status?.reviewStatus ?? 'pending',\n testStatus: status?.testStatus ?? 'pending',\n // PAN-3092: no 'pending' default — an absent uatStatus means \"UAT not\n // required\", which the merge-eligibility predicates treat as satisfied.\n uatStatus: status?.uatStatus,\n verificationStatus: status?.verificationStatus,\n inspectStatus: status?.inspectStatus,\n mergeStatus: status?.mergeStatus,\n mergeStep: status?.mergeStep,\n releaseStatus: status?.releaseStatus ?? 'pending',\n ship: existing?.ship,\n readyForMerge: status?.readyForMerge ?? false,\n closedOut: existing?.closedOut,\n closedOutAt: existing?.closedOutAt,\n reopenedAt: existing?.reopenedAt,\n // PAN-2587: the tombstone lives only in the record — a rebuild that projects\n // from ReviewStatus (which has no such field) must not erase it, or the\n // orphaned-completions patrol re-arms the same issue forever (36x on PAN-399).\n panDoneRecoveredAt: existing?.panDoneRecoveredAt,\n updatedAt: status?.updatedAt ?? new Date().toISOString(),\n };\n\n if (!status) return base;\n\n return {\n ...base,\n reviewNotes: status.reviewNotes,\n testNotes: status.testNotes,\n uatNotes: status.uatNotes,\n verificationNotes: status.verificationNotes,\n inspectNotes: status.inspectNotes,\n mergeNotes: status.mergeNotes,\n blockerReasons: status.blockerReasons,\n prUrl: status.prUrl,\n prNumber: status.prNumber,\n prHeadSha: status.prHeadSha,\n reviewedAtCommit: status.reviewedAtCommit,\n lastVerifiedCommit: status.lastVerifiedCommit,\n reviewRequestedAt: status.reviewRequestedAt,\n reviewSpawnedAt: typeof status.reviewSpawnedAt === 'number'\n ? new Date(status.reviewSpawnedAt).toISOString()\n : status.reviewSpawnedAt,\n scopeDrift: status.scopeDrift,\n autoMerge: status.autoMerge,\n deaconIgnored: status.deaconIgnored,\n deaconIgnoredAt: status.deaconIgnoredAt,\n deaconIgnoredReason: status.deaconIgnoredReason,\n reviewCycleHistory: (status as { reviewCycleHistory?: unknown }).reviewCycleHistory,\n strikeReadyHead: status.strikeReadyHead,\n strikeReadyAt: status.strikeReadyAt,\n strikeLandingState: status.strikeLandingState,\n strikeRecoveryCount: status.strikeRecoveryCount,\n strikeTransportRetryCount: status.strikeTransportRetryCount,\n strikeNextAttemptAt: status.strikeNextAttemptAt,\n strikeLandingAttempts: status.strikeLandingAttempts,\n };\n}\n\n// ─── Usage projection ─────────────────────────────────────────────────────────\n\nfunction projectUsage(issueId: string): PanIssueUsageRecord {\n const { byStage, totals } = getCostBreakdownByStageAndModelSync(issueId);\n const aggregate = getCostForIssueSync(issueId);\n\n return {\n byStage,\n totals,\n costAtCloseOut: {\n usd: aggregate?.totalCost ?? 0,\n pricingAsOf: new Date().toISOString(),\n },\n };\n}\n\n// ─── Merge projection ─────────────────────────────────────────────────────────\n\nfunction projectMerges(issueId: string): string[] {\n const mergeSet = getMergeSetSync(issueId);\n if (!mergeSet) return [];\n return mergeSet.repos\n .map(r => r.artifactUrl)\n .filter((url): url is string => typeof url === 'string' && url.length > 0);\n}\n\n// ─── Record builder ───────────────────────────────────────────────────────────\n\nexport function resolveContinuePath(projectRoot: string, issueId: string): string {\n const project: ProjectConfig = findProjectByPathSync(projectRoot) ?? {\n name: projectRoot,\n path: projectRoot,\n };\n const stateHome = resolveStateReadHomeSync(project);\n const continuesDir = stateHome.migrated\n ? join(stateHome.root, PAN_CONTINUES_DIRNAME)\n : join(stateHome.root, PAN_DIRNAME, PAN_CONTINUES_DIRNAME);\n const basePath = join(continuesDir, issueId.toLowerCase());\n const canonicalPath = `${basePath}${XBRIEF_FILENAME_SUFFIX}`;\n const legacyPath = `${basePath}${LEGACY_VBRIEF_FILENAME_SUFFIX}`;\n if (existsSync(canonicalPath)) return canonicalPath;\n if (existsSync(legacyPath)) return legacyPath;\n return canonicalPath;\n}\n\nasync function readLegacyContinueText(projectRoot: string, issueId: string): Promise<string | null> {\n try {\n return await fsp.readFile(resolveContinuePath(projectRoot, issueId), 'utf-8');\n } catch {\n return null;\n }\n}\n\n/** Read workspace continue.json and return its statusOverrides (if any). */\nasync function readWorkspaceContinueStatusOverrides(issueId: string): Promise<Record<string, string> | undefined> {\n const workspacePath = getIssueWorkspacePath(issueId);\n if (!workspacePath || !existsSync(workspacePath)) return undefined;\n const continuePath = join(workspacePath, '.pan', 'continue.json');\n try {\n const text = await fsp.readFile(continuePath, 'utf-8');\n const parsed = JSON.parse(text) as { statusOverrides?: Record<string, string> };\n return parsed.statusOverrides ?? undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Read harness/model for an issue from the overdeck agents table (most recent work agent). */\nfunction projectAgentHarnessModel(issueId: string): { harness?: RuntimeName; model?: string } {\n try {\n const agents = listOverdeckAgentStatesSync().filter(\n (a) => a.issueId?.toUpperCase() === issueId.toUpperCase(),\n );\n const workAgent =\n agents\n .filter((a) => a.role === 'work')\n .sort((a, b) => (b.startedAt ?? '').localeCompare(a.startedAt ?? ''))[0]\n ?? agents[agents.length - 1];\n // Mid-spawn placeholder row (spawn routes write model 'pending-work-spawn'\n // with a defaulted harness) — not authoritative yet.\n if (workAgent?.model === 'pending-work-spawn') return {};\n return {\n harness: workAgent?.harness,\n model: workAgent?.model ?? undefined,\n };\n } catch {\n return {};\n }\n}\n\nexport interface BuildIssueRecordOptions {\n closedAt?: string;\n owner?: string;\n reviewStatus?: ReviewStatus | null;\n}\n\nexport async function buildIssueRecord(\n project: ProjectConfig,\n issueId: string,\n opts: BuildIssueRecordOptions = {},\n): Promise<PanIssueRecord> {\n const existing = await readIssueRecord(project, issueId);\n const legacyContinueText = await readLegacyContinueText(project.path, issueId);\n const continueSubset = projectContinue(legacyContinueText ? (JSON.parse(legacyContinueText) as ContinueFile) : null);\n const pipelineRecord = projectPipeline(issueId, opts.reviewStatus ?? null, existing?.pipeline);\n const usageRecord = projectUsage(issueId);\n const merges = projectMerges(issueId);\n\n // PAN-1919: fold workspace continue statusOverrides; fall back to existing.\n const workspaceStatusOverrides = await readWorkspaceContinueStatusOverrides(issueId);\n const mergedStatusOverrides = workspaceStatusOverrides\n ? { ...(existing?.statusOverrides ?? {}), ...workspaceStatusOverrides }\n : existing?.statusOverrides;\n\n // PAN-2686: live agents-table harness/model wins so a restart-fresh with a\n // new model refreshes the record; the existing record survives as fallback\n // when no agent row remains (PAN-1919's rebuild idempotency).\n const liveHM = projectAgentHarnessModel(issueId);\n const agentHM = {\n harness: liveHM.harness ?? existing?.harness,\n model: liveHM.model ?? existing?.model,\n };\n\n return {\n issueId: issueId.toUpperCase(),\n schemaVersion: RECORD_SCHEMA_VERSION,\n ...continueSubset,\n ...existing,\n harness: agentHM.harness,\n model: agentHM.model,\n statusOverrides: mergedStatusOverrides,\n pipeline: pipelineRecord,\n closeOut: {\n usage: usageRecord,\n merges,\n ranOn: hostname(),\n closedAt: opts.closedAt,\n },\n owner: opts.owner ?? existing?.owner,\n };\n}\n\n// Re-export core record I/O from the PAN-1919 single-writer module.\nexport {\n getIssueRecordPath,\n markRecordPipelineClosedOutSync,\n readIssueRecord,\n queueIssueRecordCommit,\n} from './record.js';\n\n// ─── Owner-URI lease (PAN-1908, CP-3) ─────────────────────────────────────────\n\nexport {\n buildOwnUri,\n claimIssueOwner,\n clearIssueOwner,\n type ClaimResult,\n} from './record.js';\n\n/**\n * PAN-2587: never regress the pipeline block during a whole-record rebuild. A\n * concurrent writer (e.g. a reviewer's verdict landing between the rebuild's\n * `existing` snapshot and its write) may have put a NEWER pipeline on disk than\n * the status the rebuild projects — observed clobbering PAN-399's passed\n * verdict back to a pre-verdict snapshot. Same newer-wins rule (ISO `updatedAt`\n * comparison) the journal readers use.\n *\n * PAN-3092: newer-wins alone conflates write-recency with verdict-truth, because\n * `projectPipeline` stamps `updatedAt` on every write, verdict or not. The\n * comparison now runs through `mergePipelineVerdictAware`, which keeps\n * newer-wins for every non-verdict field but refuses to drop a terminal verdict\n * in favour of a same-cycle verdict-free write.\n */\nexport function pickNewerPipeline(\n rebuilt: PanIssuePipelineRecord,\n fresh: PanIssuePipelineRecord | undefined,\n): PanIssuePipelineRecord {\n return mergePipelineVerdictAware(rebuilt, fresh);\n}\n\n/**\n * PAN-1908 / PAN-1919: rebuild and queue the per-issue permanent record for a\n * given issue. Fire-and-forget: failures are logged, never thrown, so\n * review-status writes stay synchronous and fast.\n *\n * PAN-2583: returns whether the durable write actually landed, so the caller\n * can fall back to a sandbox-writable verdict drop when it did not (a sandboxed\n * reviewer cannot write ${OVERDECK_HOME}/state, and swallowing that here was\n * how blocked review verdicts silently vanished).\n */\nexport async function updateIssueRecordForIssue(\n issueId: string,\n reviewStatus?: ReviewStatus | null,\n): Promise<boolean> {\n try {\n const resolved = resolveProjectFromIssueSync(issueId);\n if (!resolved) return false;\n const project = getProjectSync(resolved.projectKey);\n if (!project) return false;\n\n await withIssueRecordLock(issueId, async () => {\n const record = await buildIssueRecord(project, issueId, { reviewStatus });\n await updateIssueRecord(project, issueId, (fresh) => {\n // buildIssueRecord's `existing` snapshot is read at the top of several awaits;\n // anything written to the record during that window would be erased by this\n // whole-record write (lost update). Observed twice on PAN-1791: wiped swarm\n // slot assignments during the runaway, then wiped item statusOverrides right\n // after `pan done` — which made every completed item dispatchable again and\n // re-spawned slots for finished work. Re-read both blocks synchronously\n // immediately before writing so the freshest values survive the rebuild.\n if (fresh?.swarm) record.swarm = fresh.swarm;\n if (fresh?.statusOverrides && Object.keys(fresh.statusOverrides).length > 0) {\n record.statusOverrides = { ...record.statusOverrides, ...fresh.statusOverrides };\n }\n record.pipeline = pickNewerPipeline(record.pipeline, fresh?.pipeline);\n return record;\n });\n });\n return true;\n } catch (err) {\n console.warn(`[pan-dir/records] Failed to update record for ${issueId}: ${(err as Error).message}`);\n return false;\n }\n}\n","import { existsSync, linkSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';\nimport { readFile, readdir } from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\nimport type { ReviewStatus } from '../review-status-types.js';\nimport { updateIssueRecordForIssue, type PanIssuePipelineRecord } from '../pan-dir/records.js';\nimport { readIssueRecord, readIssueRecordSync } from '../pan-dir/record.js';\nimport {\n findFallbackVerdictConflicts,\n pipelineConflictsWithFallbackVerdicts,\n pipelineCoversFallbackVerdicts,\n staleVerdictSnapshotAgainstLiveCycle,\n type VerdictConflict,\n} from '../pan-dir/pipeline-verdict-merge.js';\nimport { resolveProjectFromIssueSync, getProjectSync } from '../projects.js';\n\n// PAN-2689: fire-and-forget journal writes die with the process in a short-lived\n// CLI (pan admin specialists done exits in <1s; the record write + fallback chain\n// takes seconds). Track every in-flight write so CLI entry points can drain them\n// before process.exit — the long-lived server never needs to await these.\nconst pendingJournalWrites = new Set<Promise<void>>();\n\n/**\n * PAN-3092: a journal write carrying a NEW terminal verdict retries under lock\n * contention instead of dropping straight to the workspace fallback. MIN-902's\n * reviewer re-ran `pan admin specialists done` for an hour at LLM-turn cost\n * (~$5/hr) because the only retry available to it was another agent turn; this\n * schedule (~2.6 min total) does the same waiting in-process for free. The long\n * tail belongs to the deacon sweep, not to the agent.\n */\nconst DEFAULT_VERDICT_BACKOFF_DELAYS_MS = [2_000, 5_000, 10_000, 20_000, 40_000, 80_000] as const;\n\nfunction verdictWriteBackoffDelaysMs(): readonly number[] {\n const raw = process.env.OVERDECK_VERDICT_BACKOFF_DELAYS_MS;\n if (!raw) return DEFAULT_VERDICT_BACKOFF_DELAYS_MS;\n const parsed = raw\n .split(',')\n .map((part) => Number(part.trim()))\n .filter((ms) => Number.isFinite(ms) && ms >= 0);\n return parsed.length > 0 ? parsed : DEFAULT_VERDICT_BACKOFF_DELAYS_MS;\n}\n\n/**\n * One journal-write attempt. `false` means the durable write definitively\n * failed; `undefined` (a test double, say) is \"unknown\", not \"failed\", and only\n * a definite `true` is safe to treat as a landed write.\n */\nasync function attemptJournalWrite(\n issueId: string,\n status: ReviewStatus,\n): Promise<boolean | undefined> {\n try {\n return await updateIssueRecordForIssue(issueId, status);\n } catch {\n return false;\n }\n}\n\nexport function updateIssueRecordForReviewStatusSync(\n issueId: string,\n status: ReviewStatus,\n options?: { verdictWrite?: boolean },\n): void {\n // PAN-2583: the state-dir journal is the durable home, but a sandboxed reviewer\n // (codex workspace-write) cannot write ${OVERDECK_HOME}/state — and swallowing that\n // failure here is how blocked review verdicts silently vanished for hours. When the\n // journal write does not land, drop the durable verdict into the workspace runtime\n // dir (the one place a sandboxed agent can always write); readJournalStatusSync\n // overlays it on the next host-side read.\n const delays = options?.verdictWrite ? verdictWriteBackoffDelaysMs() : [];\n const write = (async () => {\n for (let attempt = 0; ; attempt += 1) {\n const landed = await attemptJournalWrite(issueId, status);\n if (landed !== false) {\n // PAN-2989: a landed journal write is the earliest safe moment to fold any\n // pending workspace fallback back into the canonical record.\n if (landed === true) trackVerdictFallbackDrain(issueId);\n return;\n }\n const delay = delays[attempt];\n if (delay === undefined) break;\n await new Promise<void>((resolve) => { setTimeout(resolve, delay); });\n }\n writeWorkspaceVerdictFallbackSync(issueId, status);\n scheduleVerdictFallbackDrain(issueId);\n })();\n pendingJournalWrites.add(write);\n void write.finally(() => pendingJournalWrites.delete(write));\n}\n\n/**\n * PAN-2689: await every in-flight journal write. A short-lived CLI process MUST\n * call this before process.exit or the verdict written by setReviewStatusSync is\n * silently lost (the DB write already fails readonly in a sandbox, so the dying\n * journal write was the only durable copy).\n */\nexport async function flushReviewStatusJournalWrites(): Promise<void> {\n while (pendingJournalWrites.size > 0) {\n await Promise.allSettled([...pendingJournalWrites]);\n }\n}\n\n/** Resolve and read the per-issue journal record's pipeline block, or null. Best-effort. */\nfunction readPipelineSync(issueId: string): PanIssuePipelineRecord | null {\n try {\n const resolved = resolveProjectFromIssueSync(issueId);\n if (!resolved) return null;\n const project = getProjectSync(resolved.projectKey);\n if (!project) return null;\n const record = readIssueRecordSync(project, issueId);\n return record?.pipeline ?? null;\n } catch {\n return null;\n }\n}\n\nasync function readPipeline(issueId: string): Promise<PanIssuePipelineRecord | null> {\n try {\n const resolved = resolveProjectFromIssueSync(issueId);\n if (!resolved) return null;\n const project = getProjectSync(resolved.projectKey);\n if (!project) return null;\n const record = await readIssueRecord(project, issueId);\n return record?.pipeline ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * PAN-1988: feedback TEXT (review / test / merge / inspect / verification notes) is durable\n * JOURNAL state, not DB-cache state. The SQLite row holds only the queryable status flags;\n * the human-readable notes live in the per-issue git record (`<workspace>/.pan/records/<issue>.json`,\n * PAN-1908). This overlays those notes onto a DB-sourced status so every reader (deacon\n * CI-failure detection, dashboard panels) stays transparent while the DB stops storing them.\n */\nexport function enrichReviewNotesFromRecordSync(issueId: string, status: ReviewStatus): ReviewStatus {\n const pipeline = readPipelineSync(issueId);\n if (!pipeline) return status;\n return {\n ...status,\n reviewNotes: pipeline.reviewNotes ?? status.reviewNotes,\n testNotes: pipeline.testNotes ?? status.testNotes,\n uatNotes: pipeline.uatNotes ?? status.uatNotes,\n mergeNotes: pipeline.mergeNotes ?? status.mergeNotes,\n inspectNotes: pipeline.inspectNotes ?? status.inspectNotes,\n verificationNotes: pipeline.verificationNotes ?? status.verificationNotes,\n scopeDrift: pipeline.scopeDrift ?? status.scopeDrift,\n // PAN-1988 auto-heal: the durable review-request intent is journal-only — overlay it on every\n // read so the merge base preserves it through partial updates and the dispatch reconcile sees it.\n reviewRequestedAt: pipeline.reviewRequestedAt ?? status.reviewRequestedAt,\n };\n}\n\ntype DurableStatusFields = Partial<ReviewStatus> & { closedOut?: boolean; closedOutAt?: string };\n\nconst FALLBACK_CLEARABLE_FIELDS = [\n 'strikeTransportRetryCount',\n 'strikeNextAttemptAt',\n 'reviewRequestedAt',\n] as const;\ntype FallbackClearableField = typeof FALLBACK_CLEARABLE_FIELDS[number];\n\n/**\n * The durable field subset shared by the journal record's pipeline block and the\n * workspace verdict fallback (PAN-2583). Derived/live columns (readyForMerge,\n * blockerReasons) are intentionally omitted — the reader recomputes them.\n */\nfunction durableSubset(p: PanIssuePipelineRecord): DurableStatusFields {\n return {\n reviewStatus: p.reviewStatus as ReviewStatus['reviewStatus'],\n testStatus: p.testStatus as ReviewStatus['testStatus'],\n // PAN-3092: UAT gates merge eligibility, so a contended UAT verdict must\n // survive in the fallback like every other gate's.\n uatStatus: (p.uatStatus as ReviewStatus['uatStatus']) ?? undefined,\n uatNotes: p.uatNotes,\n mergeStatus: (p.mergeStatus as ReviewStatus['mergeStatus']) ?? undefined,\n mergeStep: p.mergeStep,\n inspectStatus: (p.inspectStatus as ReviewStatus['inspectStatus']) ?? undefined,\n verificationStatus: (p.verificationStatus as ReviewStatus['verificationStatus']) ?? undefined,\n reviewNotes: p.reviewNotes,\n testNotes: p.testNotes,\n mergeNotes: p.mergeNotes,\n inspectNotes: p.inspectNotes,\n verificationNotes: p.verificationNotes,\n scopeDrift: p.scopeDrift,\n prUrl: p.prUrl,\n prNumber: p.prNumber,\n prHeadSha: p.prHeadSha,\n reviewedAtCommit: p.reviewedAtCommit,\n lastVerifiedCommit: p.lastVerifiedCommit,\n reviewRequestedAt: p.reviewRequestedAt,\n reviewSpawnedAt: p.reviewSpawnedAt,\n reviewCycleHistory: p.reviewCycleHistory as ReviewStatus['reviewCycleHistory'],\n autoMerge: p.autoMerge,\n deaconIgnored: p.deaconIgnored,\n deaconIgnoredAt: p.deaconIgnoredAt,\n deaconIgnoredReason: p.deaconIgnoredReason,\n strikeReadyHead: p.strikeReadyHead,\n strikeReadyAt: p.strikeReadyAt,\n strikeLandingState: p.strikeLandingState,\n strikeRecoveryCount: p.strikeRecoveryCount,\n strikeTransportRetryCount: p.strikeTransportRetryCount,\n strikeNextAttemptAt: p.strikeNextAttemptAt,\n strikeLandingAttempts: p.strikeLandingAttempts,\n closedOut: p.closedOut,\n closedOutAt: p.closedOutAt,\n };\n}\n\n/**\n * PAN-2583: sandbox-writable emergency drop for a verdict whose state-dir journal\n * write failed. Lives in the workspace runtime dir (gitignored), swept by\n * readJournalStatusSync on the next host-side read.\n */\nexport interface WorkspaceVerdictFallback {\n issueId: string;\n updatedAt: string;\n pipeline: DurableStatusFields;\n clearedFields?: FallbackClearableField[];\n}\n\nexport function workspaceVerdictFallbackPath(issueId: string): string | null {\n try {\n const resolved = resolveProjectFromIssueSync(issueId);\n if (!resolved) return null;\n return join(\n resolved.projectPath,\n 'workspaces',\n `feature-${issueId.toLowerCase()}`,\n '.overdeck',\n 'pipeline-verdict.json',\n );\n } catch {\n return null;\n }\n}\n\nfunction writeWorkspaceVerdictFallbackSync(issueId: string, status: ReviewStatus): void {\n try {\n const path = workspaceVerdictFallbackPath(issueId);\n if (!path) {\n console.error(\n `[review-status] PAN-2583: journal write failed for ${issueId} and no workspace could be resolved — the verdict is NOT durable`,\n );\n return;\n }\n mkdirSync(dirname(path), { recursive: true });\n const clearedFields = FALLBACK_CLEARABLE_FIELDS.filter(\n (field) => status[field] === undefined,\n );\n const payload: WorkspaceVerdictFallback = {\n issueId: issueId.toUpperCase(),\n updatedAt: status.updatedAt ?? new Date().toISOString(),\n pipeline: durableSubset(status as unknown as PanIssuePipelineRecord),\n ...(clearedFields.length > 0 ? { clearedFields } : {}),\n };\n // Atomic replace: a drain may claim the live path by rename at any moment,\n // and a plain writeFileSync could be renamed aside mid-write and fold a\n // torn payload into the canonical record.\n const tmpPath = `${path}.tmp-${process.pid}`;\n writeFileSync(tmpPath, JSON.stringify(payload, null, 2));\n renameSync(tmpPath, path);\n console.warn(\n `[review-status] journal write failed for ${issueId} — durable verdict written to workspace fallback ${path}; the host sweeps it on the next status read (PAN-2583)`,\n );\n } catch (err) {\n console.error(\n `[review-status] PAN-2583: could not persist verdict for ${issueId} anywhere durable: ${(err as Error).message}`,\n );\n }\n}\n\nfunction decodeWorkspaceVerdictFallback(raw: string): WorkspaceVerdictFallback | null {\n try {\n const parsed = JSON.parse(raw) as WorkspaceVerdictFallback;\n if (!parsed?.updatedAt || !parsed.pipeline) return null;\n const clearedFields = Array.isArray(parsed.clearedFields)\n ? parsed.clearedFields.filter((field): field is FallbackClearableField =>\n typeof field === 'string' && (FALLBACK_CLEARABLE_FIELDS as readonly string[]).includes(field))\n : [];\n return { ...parsed, clearedFields };\n } catch {\n return null;\n }\n}\n\nfunction parseWorkspaceVerdictFallback(path: string): WorkspaceVerdictFallback | null {\n try {\n return decodeWorkspaceVerdictFallback(readFileSync(path, 'utf-8'));\n } catch {\n return null;\n }\n}\n\nasync function parseWorkspaceVerdictFallbackAsync(path: string): Promise<WorkspaceVerdictFallback | null> {\n try {\n return decodeWorkspaceVerdictFallback(await readFile(path, 'utf-8'));\n } catch {\n return null;\n }\n}\n\nfunction isPidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction drainClaimPid(entry: string, prefix: string): number | null {\n const pid = Number(entry.slice(prefix.length).split('-')[0]);\n return Number.isInteger(pid) && pid > 0 ? pid : null;\n}\n\nlet drainClaimCounter = 0;\n\ninterface ClaimedFallbackGeneration {\n claimPath: string;\n fallback: WorkspaceVerdictFallback;\n}\n\n/**\n * Claim every drainable fallback generation — the live path plus any claims\n * whose owning process is dead — by renaming each onto a unique path owned by\n * this drain. Live-pid claims belong to in-flight drains and are left alone.\n *\n * Race safety: every rename target is a fresh, unique path, so no concurrent\n * verdict writer's file is ever replaced (POSIX rename onto an existing path\n * overwrites it — that is exactly the loss this protocol avoids). The payload\n * is parsed only AFTER the claim, so the generation compared and folded is\n * precisely the one this drain owns, never a stale pre-check snapshot.\n */\nfunction claimWorkspaceVerdictFallbackSync(\n issueId: string,\n): ClaimedFallbackGeneration[] | null {\n const path = workspaceVerdictFallbackPath(issueId);\n if (!path) return null;\n const dir = dirname(path);\n const prefix = `${basename(path)}.drain-`;\n let entries: string[];\n try {\n entries = readdirSync(dir);\n } catch {\n return null;\n }\n const candidates: string[] = [];\n if (entries.includes(basename(path))) candidates.push(path);\n for (const entry of entries) {\n if (!entry.startsWith(prefix)) continue;\n const pid = drainClaimPid(entry, prefix);\n if (pid !== null && isPidAlive(pid)) continue; // an in-flight drain owns it\n candidates.push(join(dir, entry));\n }\n const claims: ClaimedFallbackGeneration[] = [];\n for (const candidate of candidates) {\n drainClaimCounter += 1;\n const claimPath = `${path}.drain-${process.pid}-${drainClaimCounter}`;\n try {\n renameSync(candidate, claimPath);\n } catch {\n continue; // raced another drain; that drain owns the generation\n }\n const fallback = parseWorkspaceVerdictFallback(claimPath);\n if (!fallback) {\n rmSync(claimPath, { force: true });\n continue;\n }\n claims.push({ claimPath, fallback });\n }\n return claims.length > 0 ? claims : null;\n}\n\nexport function readWorkspaceVerdictFallbackSync(issueId: string): WorkspaceVerdictFallback | null {\n try {\n const path = workspaceVerdictFallbackPath(issueId);\n if (!path) return null;\n // Read-only newest-wins overlay across the live path AND all drain\n // claims: a drain holds its generations at claim paths for the full\n // duration of the record write, and every verdict must stay visible to\n // readers throughout — otherwise status reads fall back to the older\n // journal for up to the entire durability budget. Reads never mutate;\n // folding and cleanup are the drain's job alone.\n let newest: WorkspaceVerdictFallback | null = null;\n const consider = (candidate: WorkspaceVerdictFallback | null): void => {\n if (candidate && (!newest || newest.updatedAt < candidate.updatedAt)) newest = candidate;\n };\n if (existsSync(path)) consider(parseWorkspaceVerdictFallback(path));\n const prefix = `${basename(path)}.drain-`;\n for (const entry of readdirSync(dirname(path))) {\n if (!entry.startsWith(prefix)) continue;\n consider(parseWorkspaceVerdictFallback(join(dirname(path), entry)));\n }\n return newest;\n } catch {\n return null;\n }\n}\n\nexport async function readWorkspaceVerdictFallback(issueId: string): Promise<WorkspaceVerdictFallback | null> {\n try {\n const path = workspaceVerdictFallbackPath(issueId);\n if (!path) return null;\n const dir = dirname(path);\n const prefix = `${basename(path)}.drain-`;\n const entries = await readdir(dir);\n const candidates = [path, ...entries\n .filter((entry) => entry.startsWith(prefix))\n .map((entry) => join(dir, entry))];\n const fallbacks = await Promise.all(candidates.map(parseWorkspaceVerdictFallbackAsync));\n return fallbacks.reduce<WorkspaceVerdictFallback | null>((newest, candidate) => (\n candidate && (!newest || newest.updatedAt < candidate.updatedAt) ? candidate : newest\n ), null);\n } catch {\n return null;\n }\n}\n\n// PAN-2989: proactive drain of the workspace verdict fallback. Before this, nothing\n// ever folded a fallback back into the canonical record — observed 2026-07-21 on\n// PAN-806: the canonical journal lagged the truth for ~an hour after a stalled lock\n// forced verdict writes to the fallback. The drain runs after every landed journal\n// write for the issue, and on unref'd scheduled retries after a fallback write.\nconst DRAIN_RETRY_DELAYS_MS = [5_000, 30_000, 120_000] as const;\nconst drainTimers = new Map<string, NodeJS.Timeout>();\n\n/**\n * Fold a pending workspace verdict fallback into the canonical record and delete\n * it, without waiting for the next status read. Newer-wins on ISO `updatedAt` —\n * the same rule readJournalStatusSync uses — so a journal that already moved past\n * the fallback just cleans up the file. Returns true when no fallback remains\n * pending (drained, superseded, or never written).\n *\n * Generation-aware: the drain claims every drainable generation (the live\n * path plus stranded claims) onto unique paths it owns, folds the newest, and\n * deletes only its own claims. A newer fallback written while the record\n * write was in flight stays at the live path for its own drain schedule, and\n * no step ever renames onto a path another process may have just created.\n */\n/**\n * PAN-3092: why is a fallback still pending? A failed drain returns `false` for\n * two materially different reasons — the record write lost to a contended lock,\n * or the fold was deliberately withheld because the journal and the fallback\n * hold different terminal verdicts for one gate. Only the first clears on its\n * own; the second is permanent until an operator picks a verdict, so the sweep\n * must be able to tell them apart before it tells anyone to wait.\n *\n * Read-only and lock-free: the caller is already reporting lock contention.\n */\nexport async function findWorkspaceVerdictConflicts(\n issueId: string,\n fallback: { updatedAt: string; pipeline: DurableStatusFields },\n): Promise<VerdictConflict[]> {\n const journal = await readPipeline(issueId);\n if (!journal?.updatedAt || journal.updatedAt < fallback.updatedAt) return [];\n return findFallbackVerdictConflicts(journal, fallback);\n}\n\nexport async function drainWorkspaceVerdictFallback(issueId: string): Promise<boolean> {\n const claims = claimWorkspaceVerdictFallbackSync(issueId);\n if (!claims) return true;\n // Newest-wins across every claimed generation — the same rule the read\n // overlay uses. Older claims are superseded by the winner and are removed\n // once the winner's outcome is known.\n let winner = claims[0]!;\n for (const claim of claims) {\n if (winner.fallback.updatedAt < claim.fallback.updatedAt) winner = claim;\n }\n const losers = claims.filter((claim) => claim !== winner);\n const { fallback } = winner;\n const journal = readPipelineSync(issueId);\n const staleFallback = journal\n ? staleVerdictSnapshotAgainstLiveCycle(\n journal as unknown as Record<string, unknown>,\n fallback.pipeline as unknown as Record<string, unknown>,\n )\n : null;\n if (staleFallback) {\n console.warn(\n `[review-status] Refusing stale fallback fold for ${issueId}: `\n + `live cycle ${new Date(staleFallback.liveCycle).toISOString()} at HEAD ${staleFallback.liveHead ?? 'unknown'} `\n + `supersedes fallback cycle ${staleFallback.snapshotCycle ? new Date(staleFallback.snapshotCycle).toISOString() : 'unknown'} `\n + `at HEAD ${staleFallback.snapshotHead ?? 'unknown'}.`,\n );\n for (const claim of claims) rmSync(claim.claimPath, { force: true });\n return true;\n }\n // PAN-3092: a newer `updatedAt` alone is not evidence the journal carries the\n // verdict — `projectPipeline` stamps it on every write, verdict or not, so a\n // bookkeeping write landing after a contended verdict used to make the drain\n // delete the only surviving copy (MIN-902). Supersede only when the journal\n // has actually settled the gates the fallback holds, or has moved to a newer\n // review cycle.\n const journalAtLeastAsNew = !!journal?.updatedAt && !(journal.updatedAt < fallback.updatedAt);\n if (journalAtLeastAsNew && pipelineCoversFallbackVerdicts(journal!, fallback)) {\n for (const claim of claims) rmSync(claim.claimPath, { force: true });\n return true;\n }\n // PAN-3092: the journal and the fallback hold different terminal verdicts for\n // the same gate and nothing can order them — the whole-pipeline `updatedAt`\n // is restamped by bookkeeping, so it is not evidence either way. Folding would\n // be declined by the verdict-aware merge and deleting would destroy the only\n // written copy of one verdict, so preserve the fallback and let the sweep put\n // the conflict in front of an operator.\n const conflicted = journalAtLeastAsNew && pipelineConflictsWithFallbackVerdicts(journal!, fallback);\n // projectPipeline projects only from the ReviewStatus, so fields the fallback\n // cleared (clearedFields) stay absent and do not resurrect from the record.\n const status = {\n issueId: fallback.issueId,\n ...fallback.pipeline,\n updatedAt: fallback.updatedAt,\n readyForMerge: false, // derived on read; the stored value is never consulted\n } as ReviewStatus;\n const landed = conflicted ? false : await updateIssueRecordForIssue(issueId, status);\n if (landed) {\n for (const claim of claims) rmSync(claim.claimPath, { force: true });\n return true;\n }\n // The fold failed or was withheld as conflicting: superseded generations are\n // dropped, and the winner is\n // published back to the live path with ATOMIC no-replace semantics —\n // linkSync fails with EEXIST when a concurrent writer already created a\n // live file, so a newer verdict that arrived during the await can never be\n // overwritten. If the live generation is somehow the older one, the winner\n // stays as a stranded (non-pid) claim: the read overlay still surfaces it\n // and the next drain folds it.\n for (const claim of losers) rmSync(claim.claimPath, { force: true });\n const livePath = workspaceVerdictFallbackPath(issueId);\n if (livePath) {\n let published = false;\n try {\n linkSync(winner.claimPath, livePath);\n published = true;\n } catch {\n // A live generation already exists (or the fs rejected the link).\n }\n if (published) {\n rmSync(winner.claimPath, { force: true });\n return false;\n }\n const live = existsSync(livePath) ? parseWorkspaceVerdictFallback(livePath) : null;\n if (live && !(live.updatedAt < fallback.updatedAt)) {\n // The live generation is newer-or-equal: it carries the winning verdict.\n rmSync(winner.claimPath, { force: true });\n return false;\n }\n }\n // Keep the winner claim, but mark it stranded so a later drain reclaims it\n // (a live-pid claim would look owned by this process forever).\n drainClaimCounter += 1;\n try {\n renameSync(winner.claimPath, `${winner.claimPath.split('.drain-')[0]}.drain-republish-${drainClaimCounter}`);\n } catch {\n // Leave the claim as-is; it remains readable and recoverable.\n }\n return false;\n}\n\n/** Track a fire-and-forget drain so short-lived CLIs await it before exit. */\nfunction trackVerdictFallbackDrain(issueId: string): void {\n const drain = drainWorkspaceVerdictFallback(issueId)\n .then(() => undefined)\n .catch(() => undefined);\n pendingJournalWrites.add(drain);\n void drain.finally(() => pendingJournalWrites.delete(drain));\n}\n\n/**\n * Schedule unref'd drain retries after a fallback write. One timer per issue —\n * a new fallback write resets the schedule. Retries stop on success, on\n * exhaustion, or when the fallback file is gone.\n */\nfunction scheduleVerdictFallbackDrain(issueId: string): void {\n const key = issueId.toUpperCase();\n const existing = drainTimers.get(key);\n if (existing) clearTimeout(existing);\n\n const attempt = (index: number): void => {\n const delay = DRAIN_RETRY_DELAYS_MS[index];\n if (delay === undefined) {\n drainTimers.delete(key);\n return;\n }\n const timer = setTimeout(() => {\n drainTimers.delete(key);\n void drainWorkspaceVerdictFallback(key)\n .catch(() => false)\n .then((drained) => {\n if (!drained) attempt(index + 1);\n });\n }, delay);\n timer.unref?.();\n drainTimers.set(key, timer);\n };\n attempt(0);\n}\n\n/**\n * PAN-1988: read the journal record's durable verdict for an issue — the SOURCE OF TRUTH.\n * Returns the record `updatedAt` (used to decide whether the journal is newer than the DB\n * cache) plus the durable status fields (flags + feedback notes). Derived/live columns\n * (readyForMerge, blockerReasons) are intentionally omitted — the reader recomputes them.\n *\n * This is what makes verdict writes host-owned: a sandboxed agent can always write the journal\n * (workspace-local) even when it cannot write `~/.overdeck/overdeck.db`. The host reconciles\n * the cache from this on read, so no agent has to escalate out of its sandbox to record a verdict.\n *\n * PAN-2583: since the records migration (PAN-2541) the journal itself lives in\n * ${OVERDECK_HOME}/state, which a sandboxed reviewer cannot write either. When such a\n * writer dropped its verdict into the workspace fallback instead, overlay it here —\n * a strictly newer fallback wins over the record, and the host's own next journal\n * write folds it back into the canonical record.\n */\ntype JournalStatus = {\n updatedAt: string;\n durable: DurableStatusFields;\n clearedFields?: FallbackClearableField[];\n};\n\nfunction projectJournalStatus(\n pipeline: PanIssuePipelineRecord | null,\n fallback: WorkspaceVerdictFallback | null,\n): JournalStatus | null {\n const staleFallback = pipeline && fallback\n ? staleVerdictSnapshotAgainstLiveCycle(\n pipeline as unknown as Record<string, unknown>,\n fallback.pipeline as unknown as Record<string, unknown>,\n )\n : null;\n if (staleFallback) {\n console.warn(\n `[review-status] Refusing stale workspace fallback for ${pipeline!.issueId}: `\n + `live cycle ${new Date(staleFallback.liveCycle).toISOString()} at HEAD ${staleFallback.liveHead ?? 'unknown'} `\n + `supersedes fallback cycle ${staleFallback.snapshotCycle ? new Date(staleFallback.snapshotCycle).toISOString() : 'unknown'} `\n + `at HEAD ${staleFallback.snapshotHead ?? 'unknown'}.`,\n );\n }\n const fallbackNewer = !!fallback\n && !staleFallback\n && (!pipeline || (pipeline.updatedAt ?? '') < fallback.updatedAt);\n if (fallback && fallbackNewer) {\n const base = pipeline ? durableSubset(pipeline) : {};\n const overlay = Object.fromEntries(\n Object.entries(fallback.pipeline).filter(([, value]) => value !== undefined),\n ) as DurableStatusFields;\n const durable = { ...base, ...overlay };\n for (const field of fallback.clearedFields ?? []) delete durable[field];\n return {\n updatedAt: fallback.updatedAt,\n durable,\n ...(fallback.clearedFields?.length ? { clearedFields: fallback.clearedFields } : {}),\n };\n }\n if (!pipeline) return null;\n return { updatedAt: pipeline.updatedAt, durable: durableSubset(pipeline) };\n}\n\nexport function readJournalStatusSync(issueId: string): JournalStatus | null {\n return projectJournalStatus(\n readPipelineSync(issueId),\n readWorkspaceVerdictFallbackSync(issueId),\n );\n}\n\n/** Async journal reader for patrols that must not block the dashboard event loop. */\nexport async function readJournalStatus(issueId: string): Promise<JournalStatus | null> {\n const [pipeline, fallback] = await Promise.all([\n readPipeline(issueId),\n readWorkspaceVerdictFallback(issueId),\n ]);\n return projectJournalStatus(pipeline, fallback);\n}\n","/**\n * Review findings parsing and analysis.\n * Shared utilities for extracting and counting blocking findings from report and synthesis formats.\n */\n\nexport interface ReviewCycleEntry {\n cycle: number;\n runId: string;\n atCommit?: string;\n blockingCount: number;\n recordedAt: string;\n}\n\n/**\n * Extract a markdown section by heading.\n * Returns the content between a heading (e.g., \"## Findings\") and the next heading or EOF.\n */\nexport function extractMarkdownSection(markdown: string, heading: string): string {\n const pattern = new RegExp(`^##\\\\s+${heading}\\\\s*\\\\r?\\\\n([\\\\s\\\\S]*?)(?=^##\\\\s+|(?![\\\\s\\\\S]))`, 'im');\n return markdown.match(pattern)?.[1]?.trim() ?? '';\n}\n\n/**\n * Find blocking findings in a report markdown section.\n * Returns titles of findings marked with '!' or '⊗'.\n */\nexport function findBlockingFindings(markdown: string): string[] {\n const findings = extractMarkdownSection(markdown, 'Findings');\n if (!findings || /^none\\.?$/i.test(findings)) return [];\n\n const blockers: string[] = [];\n const headingPattern = /^###\\s*(?:!|⊗)\\s+(.+)$/gm;\n let match: RegExpExecArray | null;\n while ((match = headingPattern.exec(findings)) !== null) {\n blockers.push(match[1]!.trim());\n }\n return blockers;\n}\n\n/**\n * Count blocking findings in a synthesis body.\n * Returns the count of '## Blocking Findings' section headings (### markers),\n * or 0 if the section is absent, empty, or contains only 'None'.\n */\nexport function countSynthesisBlockingFindings(body: string): number {\n const findings = extractMarkdownSection(body, 'Blocking Findings');\n if (!findings || /^none\\.?$/i.test(findings)) return 0;\n\n const headingPattern = /^###\\s+/gm;\n let count = 0;\n let match: RegExpExecArray | null;\n while ((match = headingPattern.exec(findings)) !== null) {\n count++;\n }\n return count;\n}\n","/**\n * Review convergence detection and cycle tracking.\n * Detects when a review loop is not making progress and should be gated.\n */\n\nimport { existsSync, readdirSync, readFileSync, statSync } from 'fs';\nimport { join } from 'path';\nimport { PAN_DIRNAME, WORKSPACE_RUNTIME_DIRNAME } from '../pan-dir/types.js';\nimport { countSynthesisBlockingFindings, findBlockingFindings } from '../review-findings.js';\n\nexport interface ReviewCycleEntry {\n cycle: number;\n runId: string;\n atCommit?: string;\n blockingCount: number;\n recordedAt: string;\n}\n\nexport const REVIEW_CONVERGENCE_MIN_CYCLES = 3;\n\n/**\n * Find the latest review run directory in a workspace.\n * Looks for 'agent-*-review-*' directories under .pan/review, falling back to .overdeck/review.\n * Returns null if no run directory is found.\n */\nexport function findLatestReviewRunDir(workspacePath: string): string | null {\n const paths = [\n join(workspacePath, PAN_DIRNAME, 'review'),\n join(workspacePath, WORKSPACE_RUNTIME_DIRNAME, 'review'),\n ];\n\n for (const reviewDir of paths) {\n if (!existsSync(reviewDir)) continue;\n\n try {\n const entries = readdirSync(reviewDir);\n const reviewDirs = entries.filter(name => /^agent-.*-review-/.test(name));\n if (reviewDirs.length === 0) continue;\n\n // Sort by mtime descending (newest first)\n const sorted = reviewDirs\n .map(name => ({ name, mtime: statSync(join(reviewDir, name)).mtime.getTime() }))\n .sort((a, b) => b.mtime - a.mtime);\n\n return join(reviewDir, sorted[0].name);\n } catch {\n continue;\n }\n }\n\n return null;\n}\n\n/**\n * Count blocking findings for a specific review run.\n * First tries synthesis.md '## Blocking Findings' heading count,\n * falls back to summing findBlockingFindings across .md report files,\n * returns null if no artifacts exist.\n */\nexport function countBlockingFindingsForRun(runDir: string): number | null {\n const synthesisPath = join(runDir, 'synthesis.md');\n\n // Try synthesis first\n if (existsSync(synthesisPath)) {\n try {\n const synthBody = readFileSync(synthesisPath, 'utf8');\n const count = countSynthesisBlockingFindings(synthBody);\n if (count > 0 || synthBody.includes('## Blocking Findings')) {\n return count;\n }\n } catch {\n // Fall through to report sum\n }\n }\n\n // Fall back to report sum\n try {\n const entries = readdirSync(runDir);\n const reportFiles = entries.filter(name => name.endsWith('.md') && name !== 'synthesis.md');\n\n if (reportFiles.length === 0) return null;\n\n let totalCount = 0;\n for (const file of reportFiles) {\n const content = readFileSync(join(runDir, file), 'utf8');\n const findings = findBlockingFindings(content);\n totalCount += findings.length;\n }\n\n return totalCount;\n } catch {\n return null;\n }\n}\n\n/**\n * Evaluate whether a review cycle series is converging.\n * Returns 'not-converging' when:\n * - counts.length >= 3 AND the series shows a reversal (count[n-1] > count[n-2]), OR\n * - the last two transitions are both non-decreases (going backwards)\n * Otherwise returns 'converging'.\n */\nexport function evaluateReviewConvergence(counts: number[]): 'converging' | 'not-converging' {\n if (counts.length < REVIEW_CONVERGENCE_MIN_CYCLES) {\n return 'converging';\n }\n\n const n = counts.length;\n\n // Check for reversal: the latest value > previous value (an increase after decreases)\n const hasReversal = counts[n - 1] > counts[n - 2];\n if (hasReversal) {\n return 'not-converging';\n }\n\n // Check for two consecutive non-decreases (stall):\n // counts[n-3] <= counts[n-2] AND counts[n-2] <= counts[n-1]\n const isFirstNonDecreasing = counts[n - 2] >= counts[n - 3];\n const isSecondNonDecreasing = counts[n - 1] >= counts[n - 2];\n if (isFirstNonDecreasing && isSecondNonDecreasing) {\n return 'not-converging';\n }\n\n return 'converging';\n}\n","import { normalizeReviewStatusSync } from './review-status-normalize.js';\nimport { upsertReviewStatusSync as dbUpsert, markWorkspaceStuck } from './overdeck/review-status-sync.js';\nimport type {\n BlockerReason,\n ReviewStatus,\n StatusHistoryEntry,\n} from './review-status-types.js';\nimport {\n countBlockingFindingsForRun,\n evaluateReviewConvergence,\n findLatestReviewRunDir,\n type ReviewCycleEntry,\n} from './cloister/review-convergence.js';\nimport { resolveProjectFromIssueSync } from './projects.js';\nimport { REVIEW_STATUS_HISTORY_LIMIT } from './review-status-limits.js';\n\nexport type { BlockerReason, ReviewStatus, StatusHistoryEntry } from './review-status-types.js';\n\nexport { REVIEW_STATUS_HISTORY_LIMIT };\n\ntype ReviewStatusJournal = {\n updatedAt: string;\n durable: Record<string, unknown>;\n clearedFields?: string[];\n};\n\nexport interface ReviewStatusReconcileHooks {\n notifyStatusChanged(issueId: string, status: ReviewStatus): void;\n deliverReviewVerdictFeedbackHostSide(issueId: string, status: ReviewStatus): Promise<void>;\n emitReactiveLifecycleEvent(type: 'review.approved' | 'test.passed', issueId: string): void;\n maybeAutoDispatchReviewHostSide(issueId: string, status: ReviewStatus): void;\n maybeRecoverTestVerdictHostSide(issueId: string, status: ReviewStatus): void;\n}\n\nexport function verificationSatisfied(\n status: Pick<ReviewStatus, 'verificationStatus'>,\n): boolean {\n return status.verificationStatus !== 'failed';\n}\n\n/**\n * The one reason a merged issue's verification is `skipped`. Every verification\n * run for a merged issue already returns this (`skipMergedVerification` in\n * cloister/verification-runner.ts).\n */\nexport const MERGED_VERIFICATION_REASON =\n 'Merge already landed; verify-on-main owns post-merge validation.';\n\n/**\n * PAN-3339: `pending` verification on a merged issue is a state with no owner.\n * Verification is dispatched only from inside the review pipeline, and that\n * pipeline never runs again once the issue merges — so the verdict recorded as\n * `pending` at finalization can never advance, and DoD row 3 blocks close-out\n * forever (observed on PAN-3296 with verificationCycleCount 0). The write door\n * settles it at the write that makes it unownable, using the same policy every\n * merged-issue verification run already applies. A merge lifecycle reset writes\n * mergeStatus 'pending' in the same update, so it never trips this.\n */\nexport function settleMergedVerification<\n T extends Pick<ReviewStatus, 'mergeStatus' | 'verificationStatus' | 'verificationNotes'>,\n>(status: T): T {\n if (status.mergeStatus !== 'merged' || status.verificationStatus !== 'pending') return status;\n return { ...status, verificationStatus: 'skipped', verificationNotes: MERGED_VERIFICATION_REASON };\n}\n\n/** PAN-1988: merge-gate predicate shared by direct writes and journal reconciliation. */\nexport function reviewGatesPassedSync(\n status: Pick<\n ReviewStatus,\n 'reviewStatus' | 'testStatus' | 'verificationStatus' | 'uatStatus' | 'mergeStatus'\n >,\n): boolean {\n return (\n (status.reviewStatus === 'passed' || status.reviewStatus === 'skipped') &&\n (status.testStatus === 'passed' || status.testStatus === 'skipped') &&\n verificationSatisfied(status) &&\n (status.uatStatus === undefined || status.uatStatus === 'passed') &&\n (status.mergeStatus === 'pending' ||\n status.mergeStatus === 'queued' ||\n status.mergeStatus === undefined ||\n status.mergeStatus === null)\n );\n}\n\n/** Reconcile a newer canonical journal verdict into the SQLite cache. */\nexport function reconcileJournalIntoCacheSync(\n issueId: string,\n dbStatus: ReviewStatus | null,\n journal: ReviewStatusJournal,\n hooks: ReviewStatusReconcileHooks,\n): ReviewStatus {\n const merged: ReviewStatus = {\n ...(dbStatus ?? {\n issueId,\n reviewStatus: 'pending' as const,\n testStatus: 'pending' as const,\n updatedAt: journal.updatedAt,\n readyForMerge: false,\n }),\n };\n for (const [key, value] of Object.entries(journal.durable)) {\n if (value !== undefined) (merged as unknown as Record<string, unknown>)[key] = value;\n }\n for (const key of journal.clearedFields ?? []) {\n delete (merged as unknown as Record<string, unknown>)[key];\n }\n merged.issueId = issueId;\n merged.updatedAt = journal.updatedAt;\n const hasBlockers = (merged.blockerReasons?.length ?? 0) > 0;\n merged.readyForMerge = hasBlockers ? false : reviewGatesPassedSync(merged);\n // PAN-3339: same settlement as the write door, so a journal record still\n // carrying the ownerless `pending` cannot reinstate it in the cache on read.\n const reconciled = normalizeReviewStatusSync(settleMergedVerification(merged));\n try {\n dbUpsert(reconciled);\n // PAN-2988 — the reconcile changed the effective status; the read model only\n // advances via events, so emit the transition the lost write never produced.\n hooks.notifyStatusChanged(issueId, reconciled);\n } catch {\n // Read-only DB (a sandboxed reader) — the host reconciles when it reads. Non-fatal.\n }\n\n const wasBlocked = dbStatus?.reviewStatus === 'blocked' || dbStatus?.reviewStatus === 'failed';\n const nowBlocked = reconciled.reviewStatus === 'blocked' || reconciled.reviewStatus === 'failed';\n if (nowBlocked && !wasBlocked) {\n // PAN-3151: record blocking-finding count and gate on convergence\n try {\n const project = resolveProjectFromIssueSync(issueId);\n if (!project) {\n console.warn(`[review-status] reconcile: cannot resolve project for ${issueId}, skipping cycle recording`);\n void hooks.deliverReviewVerdictFeedbackHostSide(issueId, reconciled);\n } else {\n const issueLower = issueId.toLowerCase();\n const workspacePath = `${project.projectPath}/workspaces/feature-${issueLower}`;\n const reviewRunDir = findLatestReviewRunDir(workspacePath);\n\n if (!reviewRunDir) {\n console.warn(`[review-status] reconcile: no review run dir found for ${issueId}, skipping cycle recording`);\n void hooks.deliverReviewVerdictFeedbackHostSide(issueId, reconciled);\n } else {\n const blockingCount = countBlockingFindingsForRun(reviewRunDir);\n if (blockingCount === null) {\n console.warn(`[review-status] reconcile: cannot count findings for ${issueId}, skipping cycle recording`);\n void hooks.deliverReviewVerdictFeedbackHostSide(issueId, reconciled);\n } else {\n // Use full directory basename as runId (format: agent-*-review-*)\n const runDirName = reviewRunDir.split('/').pop() ?? '';\n const runId = runDirName;\n\n // Ensure reviewCycleHistory is initialized\n if (!reconciled.reviewCycleHistory) {\n reconciled.reviewCycleHistory = [];\n }\n\n // Deduplicate by runId: if already recorded, skip appending\n const cycleNumber = reconciled.reviewCycleHistory.length + 1;\n const alreadyRecorded = reconciled.reviewCycleHistory.some(e => e.runId === runId);\n\n if (!alreadyRecorded) {\n const entry: ReviewCycleEntry = {\n cycle: cycleNumber,\n runId,\n atCommit: reconciled.reviewedAtCommit,\n blockingCount,\n recordedAt: new Date().toISOString(),\n };\n reconciled.reviewCycleHistory.push(entry);\n\n // Persist the appended cycle\n try {\n dbUpsert(reconciled);\n } catch {\n // Non-fatal: read-only DB\n }\n }\n\n // Evaluate convergence\n const counts = reconciled.reviewCycleHistory.map(e => e.blockingCount);\n const convergence = evaluateReviewConvergence(counts);\n\n if (convergence === 'not-converging') {\n // Gate engaged: mark stuck and emit error activity, skip feedback hook\n markWorkspaceStuck(issueId, 'review-not-converging', { counts });\n reconciled.stuck = true;\n reconciled.stuckReason = 'review-not-converging';\n reconciled.stuckAt = new Date().toISOString();\n reconciled.stuckDetails = JSON.stringify({ counts });\n\n // Persist stuck state\n try {\n dbUpsert(reconciled);\n } catch {\n // Non-fatal: read-only DB\n }\n\n // Emit error-level activity\n const countSeries = counts.join(' → ');\n console.error(\n `[review-status] reconcile: review loop not converging for ${issueId}: ${countSeries}. ` +\n `Consider decomposition (split the remaining work), or unstick to continue rework.`,\n );\n // TODO: emit activity entry to pipeline when activity recording is ready\n } else {\n // Converging: invoke feedback hook as normal\n void hooks.deliverReviewVerdictFeedbackHostSide(issueId, reconciled);\n }\n }\n }\n }\n } catch (error) {\n console.error(`[review-status] reconcile: cycle recording error for ${issueId}:`, error);\n // On any error, still deliver feedback (don't gate on an exception)\n void hooks.deliverReviewVerdictFeedbackHostSide(issueId, reconciled);\n }\n }\n\n const wasReviewPassed = dbStatus?.reviewStatus === 'passed';\n const nowReviewPassed = reconciled.reviewStatus === 'passed';\n if (nowReviewPassed && !wasReviewPassed && reconciled.testStatus === 'pending') {\n console.log(`[review-status] reconcile: review.approved for ${issueId} (host-owned handoff — sandboxed agent verdict from journal)`);\n hooks.emitReactiveLifecycleEvent('review.approved', issueId);\n }\n const wasTestPassed = dbStatus?.testStatus === 'passed';\n const nowTestPassed = reconciled.testStatus === 'passed';\n if (nowTestPassed && !wasTestPassed) {\n console.log(`[review-status] reconcile: test.passed for ${issueId} (host-owned handoff — sandboxed agent verdict from journal)`);\n hooks.emitReactiveLifecycleEvent('test.passed', issueId);\n }\n\n hooks.maybeAutoDispatchReviewHostSide(issueId, reconciled);\n hooks.maybeRecoverTestVerdictHostSide(issueId, reconciled);\n return reconciled;\n}\n","/**\n * PAN-1988 auto-heal — decide whether a review needs to be (re-)dispatched from the durable\n * journal intent, as a PURE function so it is locked by tests.\n *\n * The work agent's `pan done` writes a durable `reviewRequestedAt` into the journal/record (always\n * writable, even sandboxed) BEFORE it tries to reach the dashboard. If that reactive trigger is\n * dropped — the dashboard was mid-reload, the network blipped, the deacon is frozen — the intent\n * survives in the journal. The host reconciles on read: when a request is newer than the last\n * dispatch and nothing is currently reviewing, it dispatches review. This heals with NO deacon and\n * NO live dashboard event, on the next status read.\n *\n * Returns true when a review dispatch is owed:\n * - a request exists (`reviewRequestedAt` set), AND\n * - the request is no more than seven days old, AND\n * - it is newer than the last spawn (or there was never a spawn) — i.e. a genuinely un-serviced\n * request, not the request that produced the current review, AND\n * - review is pending rather than already reviewing or terminal, AND\n * - the issue is not already ready to merge or merged.\n *\n * Genuine re-review paths reset `reviewStatus` to `pending` before recording a fresh request: `pan\n * done` does this for a new commit, and the operator force-review route does it explicitly.\n */\nexport const REVIEW_REQUEST_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;\n\nexport function isReviewRequestStale(params: {\n reviewRequestedAt?: string;\n now?: number;\n maxAgeMs?: number;\n}): boolean {\n if (!params.reviewRequestedAt) return false;\n const now = params.now ?? Date.now();\n const maxAgeMs = params.maxAgeMs ?? REVIEW_REQUEST_MAX_AGE_MS;\n return now - Date.parse(params.reviewRequestedAt) > maxAgeMs;\n}\n\nexport function needsReviewDispatch(params: {\n reviewRequestedAt?: string;\n reviewSpawnedAt?: string | number;\n reviewStatus?: string;\n mergeStatus?: string;\n readyForMerge?: boolean;\n now?: number;\n maxRequestAgeMs?: number;\n}): boolean {\n if (!params.reviewRequestedAt) return false;\n if (isReviewRequestStale({\n reviewRequestedAt: params.reviewRequestedAt,\n now: params.now,\n maxAgeMs: params.maxRequestAgeMs,\n })) return false;\n if (params.reviewStatus === 'reviewing') return false;\n if (params.reviewStatus === 'passed' || params.reviewStatus === 'skipped') return false;\n if (params.readyForMerge) return false;\n if (params.mergeStatus === 'merged') return false;\n return !params.reviewSpawnedAt || Date.parse(params.reviewRequestedAt) > new Date(params.reviewSpawnedAt).getTime();\n}\n","import { readActiveReviewArtifactContext } from './agents/agent-state-source.js';\nimport { readMemoizedArtifactVerdict } from './cloister/synthesis-verdict.js';\nimport { enrichReviewNotesFromRecordSync, readJournalStatusSync } from './overdeck/review-status-record-sync.js';\nimport {\n reconcileJournalIntoCacheSync,\n type ReviewStatus,\n type ReviewStatusReconcileHooks,\n} from './review-status-reconcile.js';\nimport { staleVerdictSnapshotAgainstLiveCycle } from './pan-dir/pipeline-verdict-merge.js';\n\nexport interface ReviewStatusReadHooks extends ReviewStatusReconcileHooks {\n deleteStatus(issueId: string): void;\n}\n\nexport function resolveJournalReconciledReviewStatusSync(\n issueId: string,\n dbStatus: ReviewStatus | null | undefined,\n hooks: ReviewStatusReadHooks,\n): ReviewStatus | null {\n const journal = readJournalStatusSync(issueId);\n if (!journal) return dbStatus ?? null;\n\n if ((journal.durable as { closedOut?: boolean }).closedOut === true) {\n try {\n hooks.deleteStatus(issueId);\n } catch {\n // Read-only DB (a sandboxed reader) — the host clears residue when it reads. Non-fatal.\n }\n return null;\n }\n\n const journalNewer = !dbStatus || (dbStatus.updatedAt ?? '') < journal.updatedAt;\n if (journalNewer) {\n const staleSnapshot = dbStatus\n ? staleVerdictSnapshotAgainstLiveCycle(\n dbStatus as unknown as Record<string, unknown>,\n journal.durable as unknown as Record<string, unknown>,\n )\n : null;\n if (staleSnapshot) {\n const liveStatus = dbStatus!;\n // PAN-3511: the normal status-read path stays filesystem-free. Only after\n // the existing stale-refusal predicate matches do we consult the bounded\n // active-run memo, and only to corroborate a terminal journal verdict.\n const journalVerdict = (journal.durable as { reviewStatus?: unknown }).reviewStatus;\n const review = readActiveReviewArtifactContext(issueId);\n const artifact = typeof journalVerdict === 'string' && review\n ? readMemoizedArtifactVerdict(issueId, review)\n : null;\n const hostRunHeadMatchesLive = Boolean(\n review?.roleRunHead\n && liveStatus.lastVerifiedCommit\n && review.roleRunHead === liveStatus.lastVerifiedCommit,\n );\n const artifactHeadMatchesHostRun = Boolean(\n !artifact?.headSha || artifact.headSha === review?.roleRunHead,\n );\n if (\n artifact\n && artifact.verdict === journalVerdict\n && hostRunHeadMatchesLive\n && artifactHeadMatchesHostRun\n ) {\n console.log(\n `[review-status] Active-run artifact corroborated the stale journal verdict with a live review-head binding for ${issueId}; replaying the terminal journal result.`,\n );\n return reconcileJournalIntoCacheSync(issueId, dbStatus ?? null, journal, hooks);\n }\n console.warn(\n `[review-status] Refusing stale journal verdict replay for ${issueId}: `\n + `live cycle ${new Date(staleSnapshot.liveCycle).toISOString()} at HEAD ${staleSnapshot.liveHead ?? 'unknown'} `\n + `supersedes snapshot cycle ${staleSnapshot.snapshotCycle ? new Date(staleSnapshot.snapshotCycle).toISOString() : 'unknown'} `\n + `at HEAD ${staleSnapshot.snapshotHead ?? 'unknown'}.`,\n );\n return dbStatus ?? null;\n }\n return reconcileJournalIntoCacheSync(issueId, dbStatus ?? null, journal, hooks);\n }\n\n const enriched = enrichReviewNotesFromRecordSync(issueId, dbStatus!);\n hooks.maybeAutoDispatchReviewHostSide(issueId, enriched);\n hooks.maybeRecoverTestVerdictHostSide(issueId, enriched);\n return enriched;\n}\n","import { dirname, posix, sep } from \"path\";\nfunction createModulerModifier() {\n const getModuleFromFileName = createGetModuleFromFilename();\n return async (frames)=>{\n for (const frame of frames)frame.module = getModuleFromFileName(frame.filename);\n return frames;\n };\n}\nfunction createGetModuleFromFilename(basePath = process.argv[1] ? dirname(process.argv[1]) : process.cwd(), isWindows = '\\\\' === sep) {\n const normalizedBase = isWindows ? normalizeWindowsPath(basePath) : basePath;\n return (filename)=>{\n if (!filename) return;\n const normalizedFilename = isWindows ? normalizeWindowsPath(filename) : filename;\n let { dir, base: file, ext } = posix.parse(normalizedFilename);\n if ('.js' === ext || '.mjs' === ext || '.cjs' === ext) file = file.slice(0, -1 * ext.length);\n const decodedFile = decodeURIComponent(file);\n if (!dir) dir = '.';\n const n = dir.lastIndexOf('/node_modules');\n if (n > -1) return `${dir.slice(n + 14).replace(/\\//g, '.')}:${decodedFile}`;\n if (dir.startsWith(normalizedBase)) {\n const moduleName = dir.slice(normalizedBase.length + 1).replace(/\\//g, '.');\n return moduleName ? `${moduleName}:${decodedFile}` : decodedFile;\n }\n return decodedFile;\n };\n}\nfunction normalizeWindowsPath(path) {\n return path.replace(/^[A-Z]:/, '').replace(/\\\\/g, '/');\n}\nexport { createModulerModifier };\n","const normalizeFlagsResponse = (flagsResponse)=>{\n if ('flags' in flagsResponse) {\n const featureFlags = getFlagValuesFromFlags(flagsResponse.flags);\n const featureFlagPayloads = getPayloadsFromFlags(flagsResponse.flags);\n return {\n ...flagsResponse,\n featureFlags,\n featureFlagPayloads\n };\n }\n {\n const featureFlags = flagsResponse.featureFlags ?? {};\n const featureFlagPayloads = Object.fromEntries(Object.entries(flagsResponse.featureFlagPayloads || {}).map(([k, v])=>[\n k,\n parsePayload(v)\n ]));\n const flags = Object.fromEntries(Object.entries(featureFlags).map(([key, value])=>[\n key,\n getFlagDetailFromFlagAndPayload(key, value, featureFlagPayloads[key])\n ]));\n return {\n ...flagsResponse,\n featureFlags,\n featureFlagPayloads,\n flags\n };\n }\n};\nfunction getFlagDetailFromFlagAndPayload(key, value, payload) {\n return {\n key: key,\n enabled: 'string' == typeof value ? true : value,\n variant: 'string' == typeof value ? value : void 0,\n reason: void 0,\n metadata: {\n id: void 0,\n version: void 0,\n payload: payload ? JSON.stringify(payload) : void 0,\n description: void 0\n }\n };\n}\nconst getFlagValuesFromFlags = (flags)=>Object.fromEntries(Object.entries(flags ?? {}).map(([key, detail])=>[\n key,\n getFeatureFlagValue(detail)\n ]).filter(([, value])=>void 0 !== value));\nconst getPayloadsFromFlags = (flags)=>{\n const safeFlags = flags ?? {};\n return Object.fromEntries(Object.keys(safeFlags).filter((flag)=>{\n const details = safeFlags[flag];\n return details.enabled && details.metadata && void 0 !== details.metadata.payload;\n }).map((flag)=>{\n const payload = safeFlags[flag].metadata?.payload;\n return [\n flag,\n payload ? parsePayload(payload) : void 0\n ];\n }));\n};\nconst getFeatureFlagValue = (detail)=>void 0 === detail ? void 0 : detail.variant ?? detail.enabled;\nconst parsePayload = (response)=>{\n if ('string' != typeof response) return response;\n try {\n return JSON.parse(response);\n } catch {\n return response;\n }\n};\nconst createFlagsResponseFromFlagsAndPayloads = (featureFlags, featureFlagPayloads)=>{\n const allKeys = [\n ...new Set([\n ...Object.keys(featureFlags ?? {}),\n ...Object.keys(featureFlagPayloads ?? {})\n ])\n ];\n const enabledFlags = allKeys.filter((flag)=>!!featureFlags[flag] || !!featureFlagPayloads[flag]).reduce((res, key)=>(res[key] = featureFlags[key] ?? true, res), {});\n const flagDetails = {\n featureFlags: enabledFlags,\n featureFlagPayloads: featureFlagPayloads ?? {}\n };\n return normalizeFlagsResponse(flagDetails);\n};\nconst updateFlagValue = (flag, value)=>({\n ...flag,\n enabled: getEnabledFromValue(value),\n variant: getVariantFromValue(value)\n });\nfunction getEnabledFromValue(value) {\n return 'string' == typeof value ? true : value;\n}\nfunction getVariantFromValue(value) {\n return 'string' == typeof value ? value : void 0;\n}\nconst flagDetailsToResults = (flagDetails)=>Object.values(flagDetails).map((detail)=>{\n const value = detail.variant ?? detail.enabled;\n const rawPayload = detail.metadata?.payload;\n return {\n key: detail.key,\n enabled: getEnabledFromValue(value),\n variant: getVariantFromValue(value),\n payload: void 0 !== rawPayload ? parsePayload(rawPayload) : null\n };\n });\nconst MINIMAL_FLAG_CALLED_EVENT_PROPERTIES = [\n '$feature_flag',\n '$feature_flag_response',\n '$feature_flag_has_experiment',\n '$feature_flag_id',\n '$feature_flag_version',\n '$feature_flag_reason',\n '$feature_flag_request_id',\n '$feature_flag_evaluated_at',\n '$feature_flag_error',\n 'locally_evaluated',\n '$groups',\n '$process_person_profile',\n '$geoip_disable',\n '$current_url',\n '$pathname',\n '$session_id',\n '$window_id',\n '$lib',\n '$lib_version',\n '$device_id',\n '$is_server'\n];\nconst minimizeFlagCalledEventProperties = (properties, transportKeys = [])=>{\n const minimal = {};\n const copyKey = (key)=>{\n if (void 0 !== properties[key]) minimal[key] = properties[key];\n };\n MINIMAL_FLAG_CALLED_EVENT_PROPERTIES.forEach(copyKey);\n transportKeys.forEach(copyKey);\n return minimal;\n};\nexport { MINIMAL_FLAG_CALLED_EVENT_PROPERTIES, createFlagsResponseFromFlagsAndPayloads, flagDetailsToResults, getEnabledFromValue, getFeatureFlagValue, getFlagValuesFromFlags, getPayloadsFromFlags, getVariantFromValue, minimizeFlagCalledEventProperties, normalizeFlagsResponse, parsePayload, updateFlagValue };\n","var types_PostHogPersistedProperty = /*#__PURE__*/ function(PostHogPersistedProperty) {\n PostHogPersistedProperty[\"AnonymousId\"] = \"anonymous_id\";\n PostHogPersistedProperty[\"DistinctId\"] = \"distinct_id\";\n PostHogPersistedProperty[\"Props\"] = \"props\";\n PostHogPersistedProperty[\"EnablePersonProcessing\"] = \"enable_person_processing\";\n PostHogPersistedProperty[\"PersonMode\"] = \"person_mode\";\n PostHogPersistedProperty[\"FeatureFlagDetails\"] = \"feature_flag_details\";\n PostHogPersistedProperty[\"FeatureFlags\"] = \"feature_flags\";\n PostHogPersistedProperty[\"FeatureFlagPayloads\"] = \"feature_flag_payloads\";\n PostHogPersistedProperty[\"BootstrapFeatureFlagDetails\"] = \"bootstrap_feature_flag_details\";\n PostHogPersistedProperty[\"BootstrapFeatureFlags\"] = \"bootstrap_feature_flags\";\n PostHogPersistedProperty[\"BootstrapFeatureFlagPayloads\"] = \"bootstrap_feature_flag_payloads\";\n PostHogPersistedProperty[\"OverrideFeatureFlags\"] = \"override_feature_flags\";\n PostHogPersistedProperty[\"Queue\"] = \"queue\";\n PostHogPersistedProperty[\"AiQueue\"] = \"ai_queue\";\n PostHogPersistedProperty[\"LogsQueue\"] = \"logs_queue\";\n PostHogPersistedProperty[\"OptedOut\"] = \"opted_out\";\n PostHogPersistedProperty[\"SessionId\"] = \"session_id\";\n PostHogPersistedProperty[\"SessionStartTimestamp\"] = \"session_start_timestamp\";\n PostHogPersistedProperty[\"SessionLastTimestamp\"] = \"session_timestamp\";\n PostHogPersistedProperty[\"PersonProperties\"] = \"person_properties\";\n PostHogPersistedProperty[\"GroupProperties\"] = \"group_properties\";\n PostHogPersistedProperty[\"InstalledAppBuild\"] = \"installed_app_build\";\n PostHogPersistedProperty[\"InstalledAppVersion\"] = \"installed_app_version\";\n PostHogPersistedProperty[\"SessionReplay\"] = \"session_replay\";\n PostHogPersistedProperty[\"SessionReplayEventTriggerActivatedSession\"] = \"session_replay_event_trigger_activated_session\";\n PostHogPersistedProperty[\"SurveyLastSeenDate\"] = \"survey_last_seen_date\";\n PostHogPersistedProperty[\"SurveysSeen\"] = \"surveys_seen\";\n PostHogPersistedProperty[\"Surveys\"] = \"surveys\";\n PostHogPersistedProperty[\"RemoteConfig\"] = \"remote_config\";\n PostHogPersistedProperty[\"FlagsEndpointWasHit\"] = \"flags_endpoint_was_hit\";\n PostHogPersistedProperty[\"DeviceId\"] = \"device_id\";\n return PostHogPersistedProperty;\n}({});\nvar types_Compression = /*#__PURE__*/ function(Compression) {\n Compression[\"GZipJS\"] = \"gzip-js\";\n Compression[\"Base64\"] = \"base64\";\n return Compression;\n}({});\nconst FeatureFlagError = {\n ERRORS_WHILE_COMPUTING: 'errors_while_computing_flags',\n FLAG_MISSING: 'flag_missing',\n QUOTA_LIMITED: 'quota_limited',\n TIMEOUT: 'timeout',\n CONNECTION_ERROR: 'connection_error',\n UNKNOWN_ERROR: 'unknown_error',\n apiError: (status)=>`api_error_${status}`\n};\nconst SurveyPosition = {\n TopLeft: 'top_left',\n TopCenter: 'top_center',\n TopRight: 'top_right',\n MiddleLeft: 'middle_left',\n MiddleCenter: 'middle_center',\n MiddleRight: 'middle_right',\n Left: 'left',\n Right: 'right',\n Center: 'center'\n};\nconst SurveyWidgetType = {\n Button: 'button',\n Tab: 'tab',\n Selector: 'selector'\n};\nconst SurveyType = {\n Popover: 'popover',\n API: 'api',\n Widget: 'widget',\n ExternalSurvey: 'external_survey'\n};\nconst SurveyQuestionDescriptionContentType = {\n Html: 'html',\n Text: 'text'\n};\nconst SurveyValidationType = {\n MinLength: 'min_length',\n MaxLength: 'max_length'\n};\nconst SurveyRatingDisplay = {\n Number: 'number',\n Emoji: 'emoji'\n};\nconst SurveyQuestionType = {\n Open: 'open',\n MultipleChoice: 'multiple_choice',\n SingleChoice: 'single_choice',\n Rating: 'rating',\n Link: 'link'\n};\nconst SurveyQuestionBranchingType = {\n NextQuestion: 'next_question',\n End: 'end',\n ResponseBased: 'response_based',\n SpecificQuestion: 'specific_question'\n};\nconst SurveyMatchType = {\n Regex: 'regex',\n NotRegex: 'not_regex',\n Exact: 'exact',\n IsNot: 'is_not',\n Icontains: 'icontains',\n NotIcontains: 'not_icontains'\n};\nconst SurveySchedule = {\n Once: 'once',\n Recurring: 'recurring',\n Always: 'always'\n};\nconst ActionStepStringMatching = {\n Contains: 'contains',\n Exact: 'exact',\n Regex: 'regex'\n};\nconst knownUnsafeEditableEvent = [\n '$snapshot',\n '$pageview',\n '$pageleave',\n '$set',\n 'survey dismissed',\n 'survey sent',\n 'survey shown',\n '$identify',\n '$groupidentify',\n '$create_alias',\n '$$client_ingestion_warning',\n '$web_experiment_applied',\n '$feature_enrollment_update',\n '$feature_flag_called'\n];\nconst knownUnsafeEditableEventProperty = [\n 'token'\n];\nexport { ActionStepStringMatching, types_Compression as Compression, FeatureFlagError, types_PostHogPersistedProperty as PostHogPersistedProperty, SurveyMatchType, SurveyPosition, SurveyQuestionBranchingType, SurveyQuestionDescriptionContentType, SurveyQuestionType, SurveyRatingDisplay, SurveySchedule, SurveyType, SurveyValidationType, SurveyWidgetType, knownUnsafeEditableEvent, knownUnsafeEditableEventProperty };\n","import { Compression } from \"./types.mjs\";\nfunction isGzipSupported() {\n return 'CompressionStream' in globalThis && 'TextEncoder' in globalThis && 'Response' in globalThis && 'function' == typeof Response.prototype.blob;\n}\nconst NATIVE_GZIP_VALIDATION_ERROR = 'NativeGzipValidationError';\nconst GZIP_MAGIC_FIRST_BYTE = 0x1f;\nconst GZIP_MAGIC_SECOND_BYTE = 0x8b;\nconst GZIP_DEFLATE_METHOD = 0x08;\nconst hasGzipMagic = (bytes)=>bytes.length >= 2 && bytes[0] === GZIP_MAGIC_FIRST_BYTE && bytes[1] === GZIP_MAGIC_SECOND_BYTE;\nconst isGzipData = (body)=>{\n if (body instanceof ArrayBuffer) return hasGzipMagic(new Uint8Array(body));\n if (ArrayBuffer.isView(body)) return hasGzipMagic(new Uint8Array(body.buffer, body.byteOffset, body.byteLength));\n return false;\n};\nconst isGzipRequest = (compression, urlCompression)=>compression === Compression.GZipJS || urlCompression === Compression.GZipJS || 'gzip' === urlCompression;\nconst isNativeAsyncGzipReadError = (error)=>{\n if (!error || 'object' != typeof error) return false;\n const name = 'name' in error ? String(error.name) : '';\n return 'NotReadableError' === name;\n};\nconst isNativeAsyncGzipError = (error)=>{\n if (!error || 'object' != typeof error) return false;\n const name = 'name' in error ? String(error.name) : '';\n return isNativeAsyncGzipReadError(error) || name === NATIVE_GZIP_VALIDATION_ERROR;\n};\nlet crc32Table;\nconst getCrc32Table = ()=>{\n if (crc32Table) return crc32Table;\n crc32Table = [];\n for(let i = 0; i < 256; i++){\n let crc = i;\n for(let j = 0; j < 8; j++)crc = 1 & crc ? 0xedb88320 ^ crc >>> 1 : crc >>> 1;\n crc32Table[i] = crc >>> 0;\n }\n return crc32Table;\n};\nconst crc32 = (bytes)=>{\n const table = getCrc32Table();\n let crc = 0xffffffff;\n for(let i = 0; i < bytes.length; i++)crc = table[(crc ^ bytes[i]) & 0xff] ^ crc >>> 8;\n return (0xffffffff ^ crc) >>> 0;\n};\nconst throwNativeGzipValidationError = (reason)=>{\n const error = new Error(`Native gzip produced invalid output: ${reason}`);\n error.name = NATIVE_GZIP_VALIDATION_ERROR;\n throw error;\n};\nconst validateNativeGzip = async (compressed, inputBytes)=>{\n if (compressed.size < 18) throwNativeGzipValidationError('too-short');\n const header = new Uint8Array(await compressed.slice(0, 10).arrayBuffer());\n if (!hasGzipMagic(header) || header[2] !== GZIP_DEFLATE_METHOD) throwNativeGzipValidationError('invalid-header');\n const trailer = new DataView(await compressed.slice(compressed.size - 8).arrayBuffer());\n if (trailer.getUint32(0, true) !== crc32(inputBytes)) throwNativeGzipValidationError('invalid-crc');\n const inputSize = inputBytes.length >>> 0;\n if (trailer.getUint32(4, true) !== inputSize) throwNativeGzipValidationError('invalid-size');\n};\nasync function gzipCompress(input, isDebug = true, options) {\n try {\n const inputBytes = new TextEncoder().encode(input);\n const compressedStream = new globalThis.CompressionStream('gzip');\n const writer = compressedStream.writable.getWriter();\n const writePromise = writer.write(inputBytes).then(()=>writer.close()).catch(async (err)=>{\n try {\n await writer.abort(err);\n } catch {}\n throw err;\n });\n const responsePromise = new Response(compressedStream.readable).blob();\n const [compressed] = await Promise.all([\n responsePromise,\n writePromise\n ]);\n await validateNativeGzip(compressed, inputBytes);\n return compressed;\n } catch (error) {\n if (options?.rethrow) throw error;\n if (isDebug) console.error('Failed to gzip compress data', error);\n return null;\n }\n}\nexport { gzipCompress, isGzipData, isGzipRequest, isGzipSupported, isNativeAsyncGzipError, isNativeAsyncGzipReadError };\n","const DEFAULT_BLOCKED_UA_STRS = [\n 'amazonbot',\n 'amazonproductbot',\n 'app.hypefactors.com',\n 'applebot',\n 'archive.org_bot',\n 'awariobot',\n 'backlinksextendedbot',\n 'baiduspider',\n 'bingbot',\n 'bingpreview',\n 'chrome-lighthouse',\n 'dataforseobot',\n 'deepscan',\n 'duckduckbot',\n 'facebookexternal',\n 'facebookcatalog',\n 'http://yandex.com/bots',\n 'hubspot',\n 'ia_archiver',\n 'leikibot',\n 'linkedinbot',\n 'meta-externalagent',\n 'mj12bot',\n 'msnbot',\n 'nessus',\n 'petalbot',\n 'pinterest',\n 'prerender',\n 'rogerbot',\n 'screaming frog',\n 'sebot-wa',\n 'sitebulb',\n 'slackbot',\n 'slurp',\n 'trendictionbot',\n 'turnitin',\n 'twitterbot',\n 'vercel-screenshot',\n 'vercelbot',\n 'yahoo! slurp',\n 'yandexbot',\n 'zoombot',\n 'bot.htm',\n 'bot.php',\n '(bot;',\n 'bot/',\n 'crawler',\n 'ahrefsbot',\n 'ahrefssiteaudit',\n 'semrushbot',\n 'siteauditbot',\n 'splitsignalbot',\n 'gptbot',\n 'oai-searchbot',\n 'chatgpt-user',\n 'perplexitybot',\n 'better uptime bot',\n 'sentryuptimebot',\n 'uptimerobot',\n 'headlesschrome',\n 'cypress',\n 'google-hoteladsverifier',\n 'adsbot-google',\n 'apis-google',\n 'duplexweb-google',\n 'feedfetcher-google',\n 'google favicon',\n 'google web preview',\n 'google-read-aloud',\n 'googlebot',\n 'googleother',\n 'google-cloudvertexbot',\n 'googleweblight',\n 'mediapartners-google',\n 'storebot-google',\n 'google-inspectiontool',\n 'bytespider'\n];\nconst isBlockedUA = function(ua, customBlockedUserAgents = []) {\n if (!ua) return false;\n const uaLower = ua.toLowerCase();\n return DEFAULT_BLOCKED_UA_STRS.concat(customBlockedUserAgents).some((blockedUA)=>{\n const blockedUaLower = blockedUA.toLowerCase();\n return -1 !== uaLower.indexOf(blockedUaLower);\n });\n};\nexport { DEFAULT_BLOCKED_UA_STRS, isBlockedUA };\n","function includes(str, needle) {\n return -1 !== str.indexOf(needle);\n}\nconst trim = function(str) {\n return str.trim();\n};\nconst stripLeadingDollar = function(s) {\n return s.replace(/^\\$/, '');\n};\nfunction isDistinctIdStringLike(value) {\n return [\n 'distinct_id',\n 'distinctid'\n ].includes(value.toLowerCase());\n}\nfunction safeJsonStringify(value) {\n const ancestors = [];\n return JSON.stringify(value, function(_key, replacementValue) {\n if ('bigint' == typeof replacementValue) return replacementValue.toString();\n if ('function' == typeof replacementValue || 'symbol' == typeof replacementValue) return;\n if (replacementValue instanceof Error) return {\n name: replacementValue.name,\n message: replacementValue.message,\n stack: replacementValue.stack\n };\n if (replacementValue && 'object' == typeof replacementValue) {\n while(ancestors.length > 0 && ancestors[ancestors.length - 1] !== this)ancestors.pop();\n if (ancestors.includes(replacementValue)) return '[Circular]';\n ancestors.push(replacementValue);\n }\n return replacementValue;\n }) ?? 'null';\n}\nfunction deepSortKeys(value) {\n if (null === value || 'object' != typeof value) return value;\n if (Array.isArray(value)) return value.map(deepSortKeys);\n return Object.keys(value).sort().reduce((acc, key)=>{\n acc[key] = deepSortKeys(value[key]);\n return acc;\n }, {});\n}\nfunction getPersonPropertiesHash(distinct_id, userPropertiesToSet, userPropertiesToSetOnce) {\n return JSON.stringify({\n distinct_id,\n userPropertiesToSet: userPropertiesToSet ? deepSortKeys(userPropertiesToSet) : void 0,\n userPropertiesToSetOnce: userPropertiesToSetOnce ? deepSortKeys(userPropertiesToSetOnce) : void 0\n });\n}\nexport { getPersonPropertiesHash, includes, isDistinctIdStringLike, safeJsonStringify, stripLeadingDollar, trim };\n","import { knownUnsafeEditableEvent, knownUnsafeEditableEventProperty } from \"../types.mjs\";\nimport { includes } from \"./string-utils.mjs\";\nconst nativeIsArray = Array.isArray;\nconst ObjProto = Object.prototype;\nconst type_utils_hasOwnProperty = ObjProto.hasOwnProperty;\nconst type_utils_toString = ObjProto.toString;\nconst isArray = nativeIsArray || function(obj) {\n return '[object Array]' === type_utils_toString.call(obj);\n};\nconst isFunction = (x)=>'function' == typeof x;\nconst isNativeFunction = (x)=>isFunction(x) && -1 !== x.toString().indexOf('[native code]');\nconst isObject = (x)=>x === Object(x) && !isArray(x);\nconst isEmptyObject = (x)=>{\n if (isObject(x)) {\n for(const key in x)if (type_utils_hasOwnProperty.call(x, key)) return false;\n return true;\n }\n return false;\n};\nconst isUndefined = (x)=>void 0 === x;\nconst isString = (x)=>'[object String]' == type_utils_toString.call(x);\nconst isEmptyString = (x)=>isString(x) && 0 === x.trim().length;\nconst isNull = (x)=>null === x;\nconst isNullish = (x)=>isUndefined(x) || isNull(x);\nconst isNumber = (x)=>'[object Number]' == type_utils_toString.call(x) && x === x;\nconst isPositiveNumber = (value)=>isNumber(value) && value > 0;\nconst isBoolean = (x)=>'[object Boolean]' === type_utils_toString.call(x);\nconst isFormData = (x)=>x instanceof FormData;\nconst isFile = (x)=>x instanceof File;\nconst isPlainError = (x)=>x instanceof Error;\nconst isKnownUnsafeEditableEvent = (x)=>includes(knownUnsafeEditableEvent, x);\nconst isKnownUnsafeEditableEventProperty = (x)=>includes(knownUnsafeEditableEventProperty, x);\nfunction isPrimitive(value) {\n return null === value || 'object' != typeof value;\n}\nfunction isBuiltin(candidate, className) {\n return Object.prototype.toString.call(candidate) === `[object ${className}]`;\n}\nfunction isError(candidate) {\n switch(Object.prototype.toString.call(candidate)){\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n case '[object DOMError]':\n case '[object WebAssembly.Exception]':\n return true;\n default:\n return isInstanceOf(candidate, Error);\n }\n}\nfunction isErrorEvent(event) {\n return isBuiltin(event, 'ErrorEvent');\n}\nfunction isEvent(candidate) {\n return 'undefined' != typeof Event && isInstanceOf(candidate, Event);\n}\nfunction isPlainObject(candidate) {\n return isBuiltin(candidate, 'Object');\n}\nfunction isInstanceOf(candidate, base) {\n try {\n return candidate instanceof base;\n } catch {\n return false;\n }\n}\nconst yesLikeValues = [\n true,\n 'true',\n 1,\n '1',\n 'yes'\n];\nconst isYesLike = (val)=>includes(yesLikeValues, val);\nconst noLikeValues = [\n false,\n 'false',\n 0,\n '0',\n 'no'\n];\nconst isNoLike = (val)=>includes(noLikeValues, val);\nexport { type_utils_hasOwnProperty as hasOwnProperty, isArray, isBoolean, isBuiltin, isEmptyObject, isEmptyString, isError, isErrorEvent, isEvent, isFile, isFormData, isFunction, isKnownUnsafeEditableEvent, isKnownUnsafeEditableEventProperty, isNativeFunction, isNoLike, isNull, isNullish, isNumber, isObject, isPlainError, isPlainObject, isPositiveNumber, isPrimitive, isString, isUndefined, isYesLike, noLikeValues, yesLikeValues };\n","import { isNumber } from \"./type-utils.mjs\";\nfunction clampToRange(value, min, max, logger, fallbackValue) {\n if (min > max) {\n logger.warn('min cannot be greater than max.');\n min = max;\n }\n if (isNumber(value)) if (value > max) {\n logger.warn(' cannot be greater than max: ' + max + '. Using max value instead.');\n return max;\n } else {\n if (!(value < min)) return value;\n logger.warn(' cannot be less than min: ' + min + '. Using min value instead.');\n return min;\n }\n logger.warn(' must be a number. using max or fallback. max: ' + max + ', fallback: ' + fallbackValue);\n return clampToRange(fallbackValue || max, min, max, logger);\n}\nfunction getRemoteConfigBool(field, key, defaultValue = true) {\n if (null == field) return defaultValue;\n if ('boolean' == typeof field) return field;\n if ('object' == typeof field) {\n const value = field[key];\n return 'boolean' == typeof value ? value : defaultValue;\n }\n return defaultValue;\n}\nfunction getRemoteConfigNumber(field, key) {\n if (null == field || 'object' != typeof field) return;\n const value = field[key];\n if ('number' == typeof value && Number.isFinite(value)) return value;\n if ('string' == typeof value) {\n const trimmed = value.trim();\n if ('' === trimmed) return;\n const parsed = Number(trimmed);\n return Number.isFinite(parsed) ? parsed : void 0;\n }\n}\nfunction isValidSampleRate(value) {\n return 'number' == typeof value && Number.isFinite(value) && value >= 0 && value <= 1;\n}\nexport { clampToRange, getRemoteConfigBool, getRemoteConfigNumber, isValidSampleRate };\n","import { clampToRange } from \"./number-utils.mjs\";\nconst ONE_DAY_IN_MS = 86400000;\nconst DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE = 1;\nconst DEFAULT_EXCEPTION_RATE_LIMITER_BUCKET_SIZE = 10;\nfunction resolveExceptionRateLimiterConfig(config = {}) {\n return {\n refillRate: config.exceptionRateLimiterRefillRate ?? config.__exceptionRateLimiterRefillRate ?? DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE,\n bucketSize: config.exceptionRateLimiterBucketSize ?? config.__exceptionRateLimiterBucketSize ?? DEFAULT_EXCEPTION_RATE_LIMITER_BUCKET_SIZE\n };\n}\nclass BucketedRateLimiter {\n constructor(options){\n this._buckets = {};\n this._onBucketRateLimited = options._onBucketRateLimited;\n this._bucketSize = clampToRange(options.bucketSize, 0, 100, options._logger);\n this._refillRate = clampToRange(options.refillRate, 0, this._bucketSize, options._logger);\n this._refillInterval = clampToRange(options.refillInterval, 0, ONE_DAY_IN_MS, options._logger);\n }\n _applyRefill(bucket, now) {\n const elapsedMs = now - bucket.lastAccess;\n const refillIntervals = Math.floor(elapsedMs / this._refillInterval);\n if (refillIntervals > 0) {\n const tokensToAdd = refillIntervals * this._refillRate;\n bucket.tokens = Math.min(bucket.tokens + tokensToAdd, this._bucketSize);\n bucket.lastAccess = bucket.lastAccess + refillIntervals * this._refillInterval;\n }\n }\n consumeRateLimit(key) {\n const now = Date.now();\n const keyStr = String(key);\n let bucket = this._buckets[keyStr];\n if (bucket) this._applyRefill(bucket, now);\n else {\n bucket = {\n tokens: this._bucketSize,\n lastAccess: now\n };\n this._buckets[keyStr] = bucket;\n }\n if (0 === bucket.tokens) return true;\n bucket.tokens--;\n if (0 === bucket.tokens) this._onBucketRateLimited?.(key);\n return 0 === bucket.tokens;\n }\n stop() {\n this._buckets = {};\n }\n}\nexport { BucketedRateLimiter, DEFAULT_EXCEPTION_RATE_LIMITER_BUCKET_SIZE, DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE, resolveExceptionRateLimiterConfig };\n","/*! For license information please see uuidv7.mjs.LICENSE.txt */\n/**\n * uuidv7: An experimental implementation of the proposed UUID Version 7\n *\n * @license Apache-2.0\n * @copyright 2021-2023 LiosK\n * @packageDocumentation\n */ const DIGITS = \"0123456789abcdef\";\nclass UUID {\n constructor(bytes){\n this.bytes = bytes;\n }\n static ofInner(bytes) {\n if (16 === bytes.length) return new UUID(bytes);\n throw new TypeError(\"not 128-bit length\");\n }\n static fromFieldsV7(unixTsMs, randA, randBHi, randBLo) {\n if (!Number.isInteger(unixTsMs) || !Number.isInteger(randA) || !Number.isInteger(randBHi) || !Number.isInteger(randBLo) || unixTsMs < 0 || randA < 0 || randBHi < 0 || randBLo < 0 || unixTsMs > 0xffffffffffff || randA > 0xfff || randBHi > 0x3fffffff || randBLo > 0xffffffff) throw new RangeError(\"invalid field value\");\n const bytes = new Uint8Array(16);\n bytes[0] = unixTsMs / 2 ** 40;\n bytes[1] = unixTsMs / 2 ** 32;\n bytes[2] = unixTsMs / 2 ** 24;\n bytes[3] = unixTsMs / 2 ** 16;\n bytes[4] = unixTsMs / 256;\n bytes[5] = unixTsMs;\n bytes[6] = 0x70 | randA >>> 8;\n bytes[7] = randA;\n bytes[8] = 0x80 | randBHi >>> 24;\n bytes[9] = randBHi >>> 16;\n bytes[10] = randBHi >>> 8;\n bytes[11] = randBHi;\n bytes[12] = randBLo >>> 24;\n bytes[13] = randBLo >>> 16;\n bytes[14] = randBLo >>> 8;\n bytes[15] = randBLo;\n return new UUID(bytes);\n }\n static parse(uuid) {\n let hex;\n switch(uuid.length){\n case 32:\n hex = /^[0-9a-f]{32}$/i.exec(uuid)?.[0];\n break;\n case 36:\n hex = /^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(uuid)?.slice(1, 6).join(\"\");\n break;\n case 38:\n hex = /^\\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\\}$/i.exec(uuid)?.slice(1, 6).join(\"\");\n break;\n case 45:\n hex = /^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(uuid)?.slice(1, 6).join(\"\");\n break;\n default:\n break;\n }\n if (hex) {\n const inner = new Uint8Array(16);\n for(let i = 0; i < 16; i += 4){\n const n = parseInt(hex.substring(2 * i, 2 * i + 8), 16);\n inner[i + 0] = n >>> 24;\n inner[i + 1] = n >>> 16;\n inner[i + 2] = n >>> 8;\n inner[i + 3] = n;\n }\n return new UUID(inner);\n }\n throw new SyntaxError(\"could not parse UUID string\");\n }\n toString() {\n let text = \"\";\n for(let i = 0; i < this.bytes.length; i++){\n text += DIGITS.charAt(this.bytes[i] >>> 4);\n text += DIGITS.charAt(0xf & this.bytes[i]);\n if (3 === i || 5 === i || 7 === i || 9 === i) text += \"-\";\n }\n return text;\n }\n toHex() {\n let text = \"\";\n for(let i = 0; i < this.bytes.length; i++){\n text += DIGITS.charAt(this.bytes[i] >>> 4);\n text += DIGITS.charAt(0xf & this.bytes[i]);\n }\n return text;\n }\n toJSON() {\n return this.toString();\n }\n getVariant() {\n const n = this.bytes[8] >>> 4;\n if (n < 0) throw new Error(\"unreachable\");\n if (n <= 7) return this.bytes.every((e)=>0 === e) ? \"NIL\" : \"VAR_0\";\n if (n <= 11) return \"VAR_10\";\n if (n <= 13) return \"VAR_110\";\n if (n <= 15) return this.bytes.every((e)=>0xff === e) ? \"MAX\" : \"VAR_RESERVED\";\n else throw new Error(\"unreachable\");\n }\n getVersion() {\n return \"VAR_10\" === this.getVariant() ? this.bytes[6] >>> 4 : void 0;\n }\n clone() {\n return new UUID(this.bytes.slice(0));\n }\n equals(other) {\n return 0 === this.compareTo(other);\n }\n compareTo(other) {\n for(let i = 0; i < 16; i++){\n const diff = this.bytes[i] - other.bytes[i];\n if (0 !== diff) return Math.sign(diff);\n }\n return 0;\n }\n}\nclass V7Generator {\n constructor(randomNumberGenerator){\n this.timestamp = 0;\n this.counter = 0;\n this.random = randomNumberGenerator ?? getDefaultRandom();\n }\n generate() {\n return this.generateOrResetCore(Date.now(), 10000);\n }\n generateOrAbort() {\n return this.generateOrAbortCore(Date.now(), 10000);\n }\n generateOrResetCore(unixTsMs, rollbackAllowance) {\n let value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);\n if (void 0 === value) {\n this.timestamp = 0;\n value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);\n }\n return value;\n }\n generateOrAbortCore(unixTsMs, rollbackAllowance) {\n const MAX_COUNTER = 0x3ffffffffff;\n if (!Number.isInteger(unixTsMs) || unixTsMs < 1 || unixTsMs > 0xffffffffffff) throw new RangeError(\"`unixTsMs` must be a 48-bit positive integer\");\n if (rollbackAllowance < 0 || rollbackAllowance > 0xffffffffffff) throw new RangeError(\"`rollbackAllowance` out of reasonable range\");\n if (unixTsMs > this.timestamp) {\n this.timestamp = unixTsMs;\n this.resetCounter();\n } else {\n if (!(unixTsMs + rollbackAllowance >= this.timestamp)) return;\n this.counter++;\n if (this.counter > MAX_COUNTER) {\n this.timestamp++;\n this.resetCounter();\n }\n }\n return UUID.fromFieldsV7(this.timestamp, Math.trunc(this.counter / 2 ** 30), this.counter & 2 ** 30 - 1, this.random.nextUint32());\n }\n resetCounter() {\n this.counter = 0x400 * this.random.nextUint32() + (0x3ff & this.random.nextUint32());\n }\n generateV4() {\n const bytes = new Uint8Array(Uint32Array.of(this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32()).buffer);\n bytes[6] = 0x40 | bytes[6] >>> 4;\n bytes[8] = 0x80 | bytes[8] >>> 2;\n return UUID.ofInner(bytes);\n }\n}\nconst getDefaultRandom = ()=>({\n nextUint32: ()=>0x10000 * Math.trunc(0x10000 * Math.random()) + Math.trunc(0x10000 * Math.random())\n });\nlet defaultGenerator;\nconst uuidv7 = ()=>uuidv7obj().toString();\nconst uuidv7obj = ()=>(defaultGenerator || (defaultGenerator = new V7Generator())).generate();\nconst uuidv4 = ()=>uuidv4obj().toString();\nconst uuidv4obj = ()=>(defaultGenerator || (defaultGenerator = new V7Generator())).generateV4();\nexport { UUID, V7Generator, uuidv4, uuidv4obj, uuidv7, uuidv7obj };\n","import { uuidv7 } from \"../vendor/uuidv7.mjs\";\nclass PromiseQueue {\n add(promise) {\n const promiseUUID = uuidv7();\n const id = ++this.nextId;\n this.promiseByIds[promiseUUID] = {\n id,\n promise\n };\n promise.catch(()=>{}).finally(()=>{\n delete this.promiseByIds[promiseUUID];\n });\n return promise;\n }\n async join() {\n let promises = Object.values(this.promiseByIds).map((item)=>item.promise);\n let length = promises.length;\n while(length > 0){\n await Promise.all(promises);\n promises = Object.values(this.promiseByIds).map((item)=>item.promise);\n length = promises.length;\n }\n }\n getPromises(ignoredPromises = [], maxId = this.nextId) {\n const ignoredPromiseSet = new Set(ignoredPromises);\n return Object.values(this.promiseByIds).filter((item)=>item.id <= maxId && !ignoredPromiseSet.has(item.promise)).map((item)=>item.promise);\n }\n get maxId() {\n return this.nextId;\n }\n get length() {\n return Object.keys(this.promiseByIds).length;\n }\n constructor(){\n this.promiseByIds = {};\n this.nextId = 0;\n }\n}\nexport { PromiseQueue };\n","function createConsole(consoleLike = console) {\n const lockedMethods = {\n log: consoleLike.log.bind(consoleLike),\n warn: consoleLike.warn.bind(consoleLike),\n error: consoleLike.error.bind(consoleLike),\n debug: consoleLike.debug.bind(consoleLike)\n };\n return lockedMethods;\n}\nconst _createLogger = (prefix, maybeCall, consoleLike)=>{\n function _log(level, ...args) {\n maybeCall(()=>{\n const consoleMethod = consoleLike[level];\n consoleMethod(prefix, ...args);\n });\n }\n const logger = {\n debug: (...args)=>{\n _log('debug', ...args);\n },\n info: (...args)=>{\n _log('log', ...args);\n },\n warn: (...args)=>{\n _log('warn', ...args);\n },\n error: (...args)=>{\n _log('error', ...args);\n },\n critical: (...args)=>{\n consoleLike['error'](prefix, ...args);\n },\n createLogger: (additionalPrefix)=>_createLogger(`${prefix} ${additionalPrefix}`, maybeCall, consoleLike)\n };\n return logger;\n};\nconst passThrough = (fn)=>fn();\nfunction createLogger(prefix, maybeCall = passThrough) {\n return _createLogger(prefix, maybeCall, createConsole());\n}\nexport { _createLogger, createLogger };\n","import { includes } from \"./string-utils.mjs\";\nimport { isFunction, isUndefined } from \"./type-utils.mjs\";\nconst FACEBOOK = 'Facebook';\nconst MOBILE = 'Mobile';\nconst IOS = 'iOS';\nconst ANDROID = 'Android';\nconst TABLET = 'Tablet';\nconst ANDROID_TABLET = ANDROID + ' ' + TABLET;\nconst IPAD = 'iPad';\nconst APPLE = 'Apple';\nconst APPLE_WATCH = APPLE + ' Watch';\nconst SAFARI = 'Safari';\nconst BLACKBERRY = 'BlackBerry';\nconst SAMSUNG = 'Samsung';\nconst SAMSUNG_BROWSER = SAMSUNG + 'Browser';\nconst SAMSUNG_INTERNET = SAMSUNG + ' Internet';\nconst CHROME = 'Chrome';\nconst CHROME_OS = CHROME + ' OS';\nconst CHROME_IOS = CHROME + ' ' + IOS;\nconst INTERNET_EXPLORER = 'Internet Explorer';\nconst INTERNET_EXPLORER_MOBILE = INTERNET_EXPLORER + ' ' + MOBILE;\nconst OPERA = 'Opera';\nconst OPERA_MINI = OPERA + ' Mini';\nconst EDGE = 'Edge';\nconst MICROSOFT_EDGE = 'Microsoft ' + EDGE;\nconst FIREFOX = 'Firefox';\nconst FIREFOX_IOS = FIREFOX + ' ' + IOS;\nconst NINTENDO = 'Nintendo';\nconst PLAYSTATION = 'PlayStation';\nconst XBOX = 'Xbox';\nconst ANDROID_MOBILE = ANDROID + ' ' + MOBILE;\nconst MOBILE_SAFARI = MOBILE + ' ' + SAFARI;\nconst WINDOWS = 'Windows';\nconst WINDOWS_PHONE = WINDOWS + ' Phone';\nconst NOKIA = 'Nokia';\nconst OUYA = 'Ouya';\nconst GENERIC = 'Generic';\nconst GENERIC_MOBILE = GENERIC + ' ' + MOBILE.toLowerCase();\nconst GENERIC_TABLET = GENERIC + ' ' + TABLET.toLowerCase();\nconst KONQUEROR = 'Konqueror';\nconst OCULUS_BROWSER = 'Oculus Browser';\nconst VIVALDI = 'Vivaldi';\nconst YANDEX = 'Yandex';\nconst WHALE = 'Whale';\nconst DUCKDUCKGO = 'DuckDuckGo';\nconst PALE_MOON = 'Pale Moon';\nconst WATERFOX = 'Waterfox';\nconst BRAVE = 'Brave';\nconst GOOGLE_SEARCH_APP = 'Google Search App';\nconst BROWSER_VERSION_REGEX_SUFFIX = '(\\\\d+(\\\\.\\\\d+)?)';\nconst DEFAULT_BROWSER_VERSION_REGEX = new RegExp('Version/' + BROWSER_VERSION_REGEX_SUFFIX);\nfunction browserFromHints(hints) {\n if (hints?.brave) return BRAVE;\n return null;\n}\nconst XBOX_REGEX = new RegExp(XBOX, 'i');\nconst PLAYSTATION_REGEX = new RegExp(PLAYSTATION + ' \\\\w+', 'i');\nconst NINTENDO_REGEX = new RegExp(NINTENDO + ' \\\\w+', 'i');\nconst BLACKBERRY_REGEX = new RegExp(BLACKBERRY + '|PlayBook|BB10', 'i');\nconst windowsVersionMap = {\n 'NT3.51': 'NT 3.11',\n 'NT4.0': 'NT 4.0',\n '5.0': '2000',\n '5.1': 'XP',\n '5.2': 'XP',\n '6.0': 'Vista',\n '6.1': '7',\n '6.2': '8',\n '6.3': '8.1',\n '6.4': '10',\n '10.0': '10'\n};\nfunction isSafari(userAgent) {\n return includes(userAgent, SAFARI) && !includes(userAgent, CHROME) && !includes(userAgent, ANDROID);\n}\nconst safariCheck = (ua, vendor)=>vendor && includes(vendor, APPLE) || isSafari(ua);\nconst detectBrowser = function(user_agent, vendor, hints, options) {\n vendor = vendor || '';\n const fromHints = browserFromHints(hints);\n if (fromHints) return fromHints;\n if (options?.detectGoogleSearchApp && includes(user_agent, 'GSA/')) return GOOGLE_SEARCH_APP;\n if (includes(user_agent, ' OPR/') && includes(user_agent, 'Mini')) return OPERA_MINI;\n if (includes(user_agent, ' OPR/')) return OPERA;\n if (BLACKBERRY_REGEX.test(user_agent)) return BLACKBERRY;\n if (includes(user_agent, 'IE' + MOBILE) || includes(user_agent, 'WPDesktop')) return INTERNET_EXPLORER_MOBILE;\n if (includes(user_agent, 'OculusBrowser')) return OCULUS_BROWSER;\n else if (includes(user_agent, SAMSUNG_BROWSER)) return SAMSUNG_INTERNET;\n else if (includes(user_agent, EDGE) || includes(user_agent, 'Edg/')) return MICROSOFT_EDGE;\n else if (includes(user_agent, VIVALDI + '/')) return VIVALDI;\n else if (includes(user_agent, 'YaBrowser/')) return YANDEX;\n else if (includes(user_agent, WHALE + '/')) return WHALE;\n else if (includes(user_agent, DUCKDUCKGO + '/') || includes(user_agent, 'Ddg/')) return DUCKDUCKGO;\n else if (includes(user_agent, 'FBIOS')) return FACEBOOK + ' ' + MOBILE;\n else if (includes(user_agent, 'UCWEB') || includes(user_agent, 'UCBrowser')) return 'UC Browser';\n else if (includes(user_agent, 'CriOS')) return CHROME_IOS;\n else if (includes(user_agent, 'CrMo')) return CHROME;\n else if (includes(user_agent, CHROME)) return CHROME;\n else if (includes(user_agent, ANDROID) && includes(user_agent, SAFARI)) return ANDROID_MOBILE;\n else if (includes(user_agent, 'FxiOS')) return FIREFOX_IOS;\n else if (includes(user_agent.toLowerCase(), KONQUEROR.toLowerCase())) return KONQUEROR;\n else if (includes(user_agent, BRAVE + '/')) return BRAVE;\n else if (safariCheck(user_agent, vendor)) return includes(user_agent, MOBILE) ? MOBILE_SAFARI : SAFARI;\n else if (includes(user_agent, 'PaleMoon/')) return PALE_MOON;\n else if (includes(user_agent, WATERFOX + '/')) return WATERFOX;\n else if (includes(user_agent, FIREFOX)) return FIREFOX;\n else if (includes(user_agent, 'MSIE') || includes(user_agent, 'Trident/')) return INTERNET_EXPLORER;\n else if (includes(user_agent, 'Gecko')) return FIREFOX;\n return '';\n};\nconst versionRegexes = {\n [INTERNET_EXPLORER_MOBILE]: [\n new RegExp('rv:' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [MICROSOFT_EDGE]: [\n new RegExp(EDGE + '?\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [CHROME]: [\n new RegExp('(' + CHROME + '|CrMo)\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [CHROME_IOS]: [\n new RegExp('CriOS\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n 'UC Browser': [\n new RegExp('(UCBrowser|UCWEB)\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [SAFARI]: [\n DEFAULT_BROWSER_VERSION_REGEX\n ],\n [MOBILE_SAFARI]: [\n DEFAULT_BROWSER_VERSION_REGEX\n ],\n [OPERA]: [\n new RegExp('(' + OPERA + '|OPR)\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [FIREFOX]: [\n new RegExp(FIREFOX + '\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [FIREFOX_IOS]: [\n new RegExp('FxiOS\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [KONQUEROR]: [\n new RegExp('Konqueror[:/]?' + BROWSER_VERSION_REGEX_SUFFIX, 'i')\n ],\n [BLACKBERRY]: [\n new RegExp(BLACKBERRY + ' ' + BROWSER_VERSION_REGEX_SUFFIX),\n DEFAULT_BROWSER_VERSION_REGEX\n ],\n [ANDROID_MOBILE]: [\n new RegExp('android\\\\s' + BROWSER_VERSION_REGEX_SUFFIX, 'i')\n ],\n [SAMSUNG_INTERNET]: [\n new RegExp(SAMSUNG_BROWSER + '\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [OCULUS_BROWSER]: [\n new RegExp('OculusBrowser\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [VIVALDI]: [\n new RegExp(VIVALDI + '\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [YANDEX]: [\n new RegExp('YaBrowser\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [WHALE]: [\n new RegExp(WHALE + '\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [BRAVE]: [\n new RegExp(BRAVE + '\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [DUCKDUCKGO]: [\n new RegExp('(DuckDuckGo|Ddg)\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [PALE_MOON]: [\n new RegExp('PaleMoon\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [WATERFOX]: [\n new RegExp(WATERFOX + '\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [GOOGLE_SEARCH_APP]: [\n new RegExp('GSA\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [INTERNET_EXPLORER]: [\n new RegExp('(rv:|MSIE )' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n Mozilla: [\n new RegExp('rv:' + BROWSER_VERSION_REGEX_SUFFIX)\n ]\n};\nconst detectBrowserVersion = function(userAgent, vendor, hints, options) {\n const browser = detectBrowser(userAgent, vendor, hints, options);\n const regexes = versionRegexes[browser];\n if (isUndefined(regexes)) return null;\n for(let i = 0; i < regexes.length; i++){\n const regex = regexes[i];\n const matches = userAgent.match(regex);\n if (matches) return parseFloat(matches[matches.length - 2]);\n }\n return null;\n};\nconst osMatchers = [\n [\n new RegExp(XBOX + '; ' + XBOX + ' (.*?)[);]', 'i'),\n (match)=>[\n XBOX,\n match && match[1] || ''\n ]\n ],\n [\n new RegExp(NINTENDO, 'i'),\n [\n NINTENDO,\n ''\n ]\n ],\n [\n new RegExp(PLAYSTATION, 'i'),\n [\n PLAYSTATION,\n ''\n ]\n ],\n [\n BLACKBERRY_REGEX,\n [\n BLACKBERRY,\n ''\n ]\n ],\n [\n new RegExp(WINDOWS, 'i'),\n (_, user_agent)=>{\n if (/Phone/.test(user_agent) || /WPDesktop/.test(user_agent)) return [\n WINDOWS_PHONE,\n ''\n ];\n if (new RegExp(MOBILE).test(user_agent) && !/IEMobile\\b/.test(user_agent)) return [\n WINDOWS + ' ' + MOBILE,\n ''\n ];\n const match = /Windows NT ([0-9.]+)/i.exec(user_agent);\n if (match && match[1]) {\n const version = match[1];\n let osVersion = windowsVersionMap[version] || '';\n if (/arm/i.test(user_agent)) osVersion = 'RT';\n return [\n WINDOWS,\n osVersion\n ];\n }\n return [\n WINDOWS,\n ''\n ];\n }\n ],\n [\n /((iPhone|iPad|iPod).*?OS (\\d+)_(\\d+)_?(\\d+)?|iPhone)/,\n (match)=>{\n if (match && match[3]) {\n const versionParts = [\n match[3],\n match[4],\n match[5] || '0'\n ];\n return [\n IOS,\n versionParts.join('.')\n ];\n }\n return [\n IOS,\n ''\n ];\n }\n ],\n [\n /(watch.*\\/(\\d+\\.\\d+\\.\\d+)|watch os,(\\d+\\.\\d+),)/i,\n (match)=>{\n let version = '';\n if (match && match.length >= 3) version = isUndefined(match[2]) ? match[3] : match[2];\n return [\n 'watchOS',\n version\n ];\n }\n ],\n [\n new RegExp('(' + ANDROID + ' (\\\\d+)\\\\.(\\\\d+)\\\\.?(\\\\d+)?|' + ANDROID + ')', 'i'),\n (match)=>{\n if (match && match[2]) {\n const versionParts = [\n match[2],\n match[3],\n match[4] || '0'\n ];\n return [\n ANDROID,\n versionParts.join('.')\n ];\n }\n return [\n ANDROID,\n ''\n ];\n }\n ],\n [\n /Mac OS X (\\d+)[_.](\\d+)[_.]?(\\d+)?/i,\n (match)=>{\n const result = [\n 'Mac OS X',\n ''\n ];\n if (match && match[1]) {\n const versionParts = [\n match[1],\n match[2],\n match[3] || '0'\n ];\n result[1] = versionParts.join('.');\n }\n return result;\n }\n ],\n [\n /Mac/i,\n [\n 'Mac OS X',\n ''\n ]\n ],\n [\n /CrOS/,\n [\n CHROME_OS,\n ''\n ]\n ],\n [\n /Linux|debian/i,\n [\n 'Linux',\n ''\n ]\n ]\n];\nconst detectOS = function(user_agent) {\n for(let i = 0; i < osMatchers.length; i++){\n const [rgex, resultOrFn] = osMatchers[i];\n const match = rgex.exec(user_agent);\n const result = match && (isFunction(resultOrFn) ? resultOrFn(match, user_agent) : resultOrFn);\n if (result) return result;\n }\n return [\n '',\n ''\n ];\n};\nconst detectDevice = function(user_agent) {\n if (NINTENDO_REGEX.test(user_agent)) return NINTENDO;\n if (PLAYSTATION_REGEX.test(user_agent)) return PLAYSTATION;\n if (XBOX_REGEX.test(user_agent)) return XBOX;\n if (new RegExp(OUYA, 'i').test(user_agent)) return OUYA;\n if (new RegExp('(' + WINDOWS_PHONE + '|WPDesktop)', 'i').test(user_agent)) return WINDOWS_PHONE;\n else if (/iPad/.test(user_agent)) return IPAD;\n else if (/iPod/.test(user_agent)) return 'iPod Touch';\n else if (/iPhone/.test(user_agent)) return 'iPhone';\n else if (/(watch)(?: ?os[,/]|\\d,\\d\\/)[\\d.]+/i.test(user_agent)) return APPLE_WATCH;\n else if (BLACKBERRY_REGEX.test(user_agent)) return BLACKBERRY;\n else if (/(kobo)\\s(ereader|touch)/i.test(user_agent)) return 'Kobo';\n else if (new RegExp(NOKIA, 'i').test(user_agent)) return NOKIA;\n else if (/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\\))/i.test(user_agent) || /(kf[a-z]+)( bui|\\)).+silk\\//i.test(user_agent)) return 'Kindle Fire';\n else if (/(Android|ZTE)/i.test(user_agent)) if (!(!new RegExp(MOBILE).test(user_agent) || /(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(user_agent))) return ANDROID;\n else {\n if (/pixel[\\daxl ]{1,6}/i.test(user_agent) && !/pixel c/i.test(user_agent) || /(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(user_agent) || /lmy47v/i.test(user_agent) && !/QTAQZ3/i.test(user_agent)) return ANDROID;\n return ANDROID_TABLET;\n }\n else if (new RegExp('(pda|' + MOBILE + ')', 'i').test(user_agent)) return GENERIC_MOBILE;\n else if (new RegExp(TABLET, 'i').test(user_agent) && !new RegExp(TABLET + ' pc', 'i').test(user_agent)) return GENERIC_TABLET;\n else return '';\n};\nconst detectDeviceType = function(user_agent, options) {\n const device = detectDevice(user_agent);\n if (device === IPAD || device === ANDROID_TABLET || 'Kobo' === device || 'Kindle Fire' === device || device === GENERIC_TABLET) return TABLET;\n if (device === NINTENDO || device === XBOX || device === PLAYSTATION || device === OUYA) return 'Console';\n if (device === APPLE_WATCH) return 'Wearable';\n if (device) return MOBILE;\n if (options?.userAgentDataPlatform === 'Android' && (options?.maxTouchPoints ?? 0) > 0) {\n const shortSide = Math.min(options?.screenWidth ?? 0, options?.screenHeight ?? 0);\n const shortSideDp = shortSide / (options?.devicePixelRatio ?? 1);\n return shortSideDp >= 600 ? TABLET : MOBILE;\n }\n return 'Desktop';\n};\nexport { detectBrowser, detectBrowserVersion, detectDevice, detectDeviceType, detectOS };\n","export * from \"./bot-detection.mjs\";\nexport * from \"./bucketed-rate-limiter.mjs\";\nexport * from \"./number-utils.mjs\";\nexport * from \"./string-utils.mjs\";\nexport * from \"./type-utils.mjs\";\nexport * from \"./promise-queue.mjs\";\nexport * from \"./logger.mjs\";\nexport * from \"./user-agent-utils.mjs\";\nconst STRING_FORMAT = 'utf8';\nconst UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nfunction isValidUUID(value) {\n return 'string' == typeof value && UUID_REGEX.test(value);\n}\nfunction getEventUuid(uuid, generateUuid) {\n return isValidUUID(uuid) ? uuid : generateUuid();\n}\nfunction assert(truthyValue, message) {\n if (!truthyValue || 'string' != typeof truthyValue || isEmpty(truthyValue)) throw new Error(message);\n}\nfunction isEmpty(truthyValue) {\n if (0 === truthyValue.trim().length) return true;\n return false;\n}\nfunction removeTrailingSlash(url) {\n return url?.replace(/\\/+$/, '');\n}\nfunction stripUrlHash(url) {\n if (!url) return url;\n return url.split('#')[0];\n}\nasync function retriable(fn, props) {\n let lastError = null;\n for(let i = 0; i < props.retryCount + 1; i++){\n if (i > 0) await new Promise((r)=>setTimeout(r, props.retryDelay));\n try {\n const res = await fn();\n return res;\n } catch (e) {\n lastError = e;\n if (!props.retryCheck(e)) throw e;\n }\n }\n throw lastError;\n}\nfunction currentTimestamp() {\n return new Date().getTime();\n}\nfunction currentISOTime() {\n return new Date().toISOString();\n}\nfunction safeSetTimeout(fn, timeout) {\n const t = setTimeout(fn, timeout);\n t?.unref && t?.unref();\n return t;\n}\nconst isPromise = (obj)=>obj && 'function' == typeof obj.then;\nconst isError = (x)=>x instanceof Error;\nfunction getFetch() {\n return 'undefined' != typeof fetch ? fetch : void 0 !== globalThis.fetch ? globalThis.fetch : void 0;\n}\nfunction allSettled(promises) {\n return Promise.all(promises.map((p)=>(p ?? Promise.resolve()).then((value)=>({\n status: 'fulfilled',\n value\n }), (reason)=>({\n status: 'rejected',\n reason\n }))));\n}\nexport { STRING_FORMAT, UUID_REGEX, allSettled, assert, currentISOTime, currentTimestamp, getEventUuid, getFetch, isError, isPromise, isValidUUID, removeTrailingSlash, retriable, safeSetTimeout, stripUrlHash };\n","import { isArray, isBoolean, isNull, isNullish, isUndefined } from \"../utils/index.mjs\";\nconst OTLP_SEVERITY_MAP = {\n trace: {\n text: 'TRACE',\n number: 1\n },\n debug: {\n text: 'DEBUG',\n number: 5\n },\n info: {\n text: 'INFO',\n number: 9\n },\n warn: {\n text: 'WARN',\n number: 13\n },\n error: {\n text: 'ERROR',\n number: 17\n },\n fatal: {\n text: 'FATAL',\n number: 21\n }\n};\nconst DEFAULT_OTLP_SEVERITY = OTLP_SEVERITY_MAP.info;\nfunction getOtlpSeverityText(level) {\n return (OTLP_SEVERITY_MAP[level] || DEFAULT_OTLP_SEVERITY).text;\n}\nfunction getOtlpSeverityNumber(level) {\n return (OTLP_SEVERITY_MAP[level] || DEFAULT_OTLP_SEVERITY).number;\n}\nfunction toOtlpAnyValue(value) {\n if (isBoolean(value)) return {\n boolValue: value\n };\n if ('number' == typeof value) {\n if (!Number.isFinite(value)) return {\n stringValue: String(value)\n };\n if (Number.isInteger(value)) return {\n intValue: value\n };\n return {\n doubleValue: value\n };\n }\n if ('string' == typeof value) return {\n stringValue: value\n };\n if (isArray(value)) return {\n arrayValue: {\n values: value.map((v)=>toOtlpAnyValue(v))\n }\n };\n try {\n return {\n stringValue: JSON.stringify(value)\n };\n } catch {\n return {\n stringValue: String(value)\n };\n }\n}\nfunction toOtlpKeyValueList(attrs) {\n const result = [];\n for(const key in attrs){\n const value = attrs[key];\n if (!(isNull(value) || isUndefined(value))) result.push({\n key,\n value: toOtlpAnyValue(value)\n });\n }\n return result;\n}\nfunction timestampToUnixNano() {\n return String(Date.now()) + '000000';\n}\nfunction buildOtlpLogRecord(options, sdkContext) {\n const level = options.level || 'info';\n const { text: severityText, number: severityNumber } = OTLP_SEVERITY_MAP[level] || DEFAULT_OTLP_SEVERITY;\n const now = timestampToUnixNano();\n const autoAttributes = {};\n if (sdkContext.distinctId) autoAttributes.posthogDistinctId = sdkContext.distinctId;\n if (sdkContext.sessionId) autoAttributes.sessionId = sdkContext.sessionId;\n if (sdkContext.windowId) autoAttributes['window.id'] = sdkContext.windowId;\n if (!isNullish(sdkContext.sessionStartTimestamp)) autoAttributes.sessionStartTimestamp = String(sdkContext.sessionStartTimestamp);\n if (!isNullish(sdkContext.lastActivityTimestamp)) autoAttributes.lastActivityTimestamp = String(sdkContext.lastActivityTimestamp);\n if (sdkContext.currentUrl) autoAttributes['url.full'] = sdkContext.currentUrl;\n if (sdkContext.screenName) autoAttributes['screen.name'] = sdkContext.screenName;\n if (sdkContext.appState) autoAttributes['app.state'] = sdkContext.appState;\n if (sdkContext.activeFeatureFlags && sdkContext.activeFeatureFlags.length > 0) autoAttributes.feature_flags = sdkContext.activeFeatureFlags;\n const mergedAttributes = {\n ...autoAttributes,\n ...options.attributes || {}\n };\n const record = {\n timeUnixNano: now,\n observedTimeUnixNano: now,\n severityNumber,\n severityText,\n body: {\n stringValue: options.body\n },\n attributes: toOtlpKeyValueList(mergedAttributes)\n };\n if (options.trace_id) record.traceId = options.trace_id;\n if (options.span_id) record.spanId = options.span_id;\n if (!isUndefined(options.trace_flags)) record.flags = options.trace_flags;\n return record;\n}\nfunction buildResourceAttributes(config, sdkName, sdkVersion) {\n return {\n ...config.resourceAttributes,\n 'service.name': config.serviceName || 'unknown_service',\n ...config.environment && {\n 'deployment.environment': config.environment\n },\n ...config.serviceVersion && {\n 'service.version': config.serviceVersion\n },\n 'telemetry.sdk.name': sdkName,\n 'telemetry.sdk.version': sdkVersion\n };\n}\nfunction buildOtlpLogsPayload(logRecords, resourceAttributes, scopeName, scopeVersion) {\n return {\n resourceLogs: [\n {\n resource: {\n attributes: toOtlpKeyValueList(resourceAttributes)\n },\n scopeLogs: [\n {\n scope: {\n name: scopeName,\n version: scopeVersion\n },\n logRecords\n }\n ]\n }\n ]\n };\n}\nexport { buildOtlpLogRecord, buildOtlpLogsPayload, buildResourceAttributes, getOtlpSeverityNumber, getOtlpSeverityText, toOtlpAnyValue, toOtlpKeyValueList };\n","import { buildOtlpLogRecord, buildOtlpLogsPayload, buildResourceAttributes } from \"./logs-utils.mjs\";\nimport { PostHogPersistedProperty } from \"../types.mjs\";\nimport { isArray, safeSetTimeout } from \"../utils/index.mjs\";\nconst MAX_FLUSH_BACKOFF_EXPONENT = 6;\nclass PostHogLogs {\n constructor(_instance, _config, _logger, _getContext, _onReady, _waitForStoragePersist = ()=>Promise.resolve(), _scopeName){\n this._instance = _instance;\n this._config = _config;\n this._logger = _logger;\n this._getContext = _getContext;\n this._onReady = _onReady;\n this._waitForStoragePersist = _waitForStoragePersist;\n this._scopeName = _scopeName;\n this._flushPromise = null;\n this._evictedSinceAdvance = 0;\n this._consecutiveFlushFailures = 0;\n this._intervalWindowStart = 0;\n this._intervalLogCount = 0;\n this._droppedWarned = false;\n this._maxBufferSize = _config.maxBufferSize;\n this._maxQueueSize = Math.max(_config.maxQueueSize ?? _config.maxBufferSize, _config.maxBufferSize);\n this._flushIntervalMs = _config.flushIntervalMs;\n this._maxBatchRecordsPerPost = _config.maxBatchRecordsPerPost;\n this._rateCapWindowMs = _config.rateCapWindowMs;\n this._maxLogsPerInterval = _config.maxLogsPerInterval;\n }\n reset() {\n this._clearFlushTimer();\n this._flushPromise = null;\n this._intervalWindowStart = 0;\n this._intervalLogCount = 0;\n this._droppedWarned = false;\n this._evictedSinceAdvance = 0;\n this._consecutiveFlushFailures = 0;\n this._maxBatchRecordsPerPost = this._config.maxBatchRecordsPerPost;\n }\n onReconnect() {\n this._consecutiveFlushFailures = 0;\n this._flushInBackground();\n }\n captureLog(options) {\n if (this._instance.isDisabled) return;\n if (this._instance.optedOut) return;\n if (!options?.body) return;\n const filtered = this._runBeforeSend(options);\n if (null === filtered) return;\n if (!filtered.body) return void this._logger.info(\"Log was rejected in beforeSend function\");\n if (!this._checkRateLimit()) return;\n const record = buildOtlpLogRecord(filtered, this._getContext());\n const entry = {\n record\n };\n this._onReady(()=>this._enqueue(entry));\n }\n _runBeforeSend(options) {\n const beforeSend = this._config.beforeSend;\n if (!beforeSend) return options;\n const fns = isArray(beforeSend) ? beforeSend : [\n beforeSend\n ];\n let result = options;\n for (const fn of fns)try {\n const next = fn(result);\n if (!next) {\n this._logger.info(\"Log was rejected in beforeSend function\");\n return null;\n }\n result = next;\n } catch (e) {\n this._logger.error(\"Error in beforeSend function for log:\", e);\n return null;\n }\n return result;\n }\n _checkRateLimit() {\n if (void 0 === this._maxLogsPerInterval) return true;\n const now = Date.now();\n const elapsed = now - this._intervalWindowStart;\n if (elapsed >= this._rateCapWindowMs || elapsed < 0) {\n this._intervalWindowStart = now;\n this._intervalLogCount = 0;\n this._droppedWarned = false;\n }\n if (this._intervalLogCount >= this._maxLogsPerInterval) {\n if (!this._droppedWarned) {\n this._logger.warn(`captureLog dropping logs: exceeded ${this._maxLogsPerInterval} logs per ${this._rateCapWindowMs}ms`);\n this._droppedWarned = true;\n }\n return false;\n }\n this._intervalLogCount++;\n return true;\n }\n async flush() {\n if (this._instance.isDisabled) return;\n if (this._flushPromise) return this._flushPromise;\n this._flushPromise = this._flushInner().finally(()=>{\n this._flushPromise = null;\n });\n return this._flushPromise;\n }\n async _flushInner() {\n this._clearFlushTimer();\n let queue = this._instance.getPersistedProperty(PostHogPersistedProperty.LogsQueue) ?? [];\n if (0 === queue.length) return;\n const originalQueueLength = queue.length;\n let sentCount = 0;\n while(queue.length > 0 && sentCount < originalQueueLength){\n this._evictedSinceAdvance = 0;\n const batchSize = Math.min(queue.length, this._maxBatchRecordsPerPost);\n const batch = queue.slice(0, batchSize);\n const records = batch.map((e)=>e.record);\n const payload = buildOtlpLogsPayload(records, this._buildResourceAttributes(), this._scopeName ?? this._instance.getLibraryId(), this._instance.getLibraryVersion());\n const outcome = await this._instance._sendLogsBatch(payload);\n if ('too-large' === outcome.kind && batch.length > 1) {\n this._maxBatchRecordsPerPost = Math.max(1, Math.floor(batch.length / 2));\n this._logger.warn(`Received 413 when sending logs batch of size ${batch.length}, reducing batch size to ${this._maxBatchRecordsPerPost}`);\n continue;\n }\n if ('retry-later' === outcome.kind) throw outcome.error;\n if ('too-large' === outcome.kind) this._logger.warn(\"Dropping a single log record after 413 with batch size 1 \\u2014 the record is larger than the server cap and cannot be split further.\");\n else if ('ok' === outcome.kind && this._maxBatchRecordsPerPost < this._config.maxBatchRecordsPerPost) this._maxBatchRecordsPerPost = Math.min(this._config.maxBatchRecordsPerPost, this._maxBatchRecordsPerPost + 1);\n await this._persistQueueAdvance(batch.length);\n queue = this._instance.getPersistedProperty(PostHogPersistedProperty.LogsQueue) ?? [];\n sentCount += batch.length;\n if ('fatal' === outcome.kind) throw outcome.error;\n }\n }\n async _persistQueueAdvance(consumed) {\n const evicted = this._evictedSinceAdvance;\n const drop = Math.max(0, consumed - evicted);\n const refreshed = this._instance.getPersistedProperty(PostHogPersistedProperty.LogsQueue) ?? [];\n this._instance.setPersistedProperty(PostHogPersistedProperty.LogsQueue, refreshed.slice(drop));\n await this._waitForStoragePersist();\n }\n _buildResourceAttributes() {\n return buildResourceAttributes(this._config, this._instance.getLibraryId(), this._instance.getLibraryVersion());\n }\n _enqueue(entry) {\n if (this._instance.optedOut) return;\n const queue = this._instance.getPersistedProperty(PostHogPersistedProperty.LogsQueue) ?? [];\n if (queue.length >= this._maxQueueSize) {\n queue.shift();\n this._evictedSinceAdvance++;\n this._logger.info('Logs queue is full, dropping oldest record.');\n }\n queue.push(entry);\n this._instance.setPersistedProperty(PostHogPersistedProperty.LogsQueue, queue);\n if (queue.length >= this._maxBufferSize) return void this._flushInBackground();\n this._armFlushTimer();\n }\n _armFlushTimer(delayMs = this._flushIntervalMs) {\n if (this._flushTimer) return;\n this._flushTimer = safeSetTimeout(()=>{\n this._flushTimer = void 0;\n this._flushInBackground();\n }, delayMs);\n }\n _nextFlushDelay() {\n const exponent = Math.min(Math.max(0, this._consecutiveFlushFailures - 1), MAX_FLUSH_BACKOFF_EXPONENT);\n return this._flushIntervalMs * 2 ** exponent;\n }\n _hasQueuedRecords() {\n const queue = this._instance.getPersistedProperty(PostHogPersistedProperty.LogsQueue);\n return !!queue && queue.length > 0;\n }\n async shutdown(timeoutMs) {\n this._clearFlushTimer();\n const flushPromise = this.flush().catch(()=>{});\n if (void 0 === timeoutMs) return void await flushPromise;\n await Promise.race([\n flushPromise,\n new Promise((resolve)=>safeSetTimeout(resolve, timeoutMs))\n ]);\n }\n async flushWithTimeout(timeoutMs) {\n let timedOut = false;\n const flushPromise = this.flush();\n const timerPromise = new Promise((resolve)=>safeSetTimeout(()=>{\n timedOut = true;\n resolve();\n }, timeoutMs));\n try {\n await Promise.race([\n flushPromise,\n timerPromise\n ]);\n } finally{\n if (timedOut) flushPromise.catch(()=>{});\n }\n }\n _flushInBackground() {\n this.flush().then(()=>{\n this._consecutiveFlushFailures = 0;\n }, (err)=>{\n this._consecutiveFlushFailures++;\n this._logger.error('PostHog logs flush failed:', err);\n }).finally(()=>{\n if (!this._instance.isDisabled && this._hasQueuedRecords()) this._armFlushTimer(this._nextFlushDelay());\n });\n }\n _clearFlushTimer() {\n if (this._flushTimer) {\n clearTimeout(this._flushTimer);\n this._flushTimer = void 0;\n }\n }\n}\nexport { PostHogLogs };\n","import { toOtlpKeyValueList } from \"../logs/logs-utils.mjs\";\nconst DEFAULT_HISTOGRAM_BOUNDS = [\n 0,\n 5,\n 10,\n 25,\n 50,\n 75,\n 100,\n 250,\n 500,\n 750,\n 1000,\n 2500,\n 5000,\n 7500,\n 10000\n];\nfunction msToUnixNano(ms) {\n return String(ms) + '000000';\n}\nfunction seriesKey(type, name, unit, attributes) {\n let attrsKey = '';\n if (attributes) {\n const keys = Object.keys(attributes).sort();\n attrsKey = keys.map((k)=>`${JSON.stringify(k)}:${JSON.stringify(attributes[k])}`).join(',');\n }\n return `${type}\\u0000${name}\\u0000${unit ?? ''}\\u0000${attrsKey}`;\n}\nfunction bucketIndexFor(value, bounds) {\n for(let i = 0; i < bounds.length; i++)if (value <= bounds[i]) return i;\n return bounds.length;\n}\nfunction buildMetricsResourceAttributes(config, scopeName, scopeVersion) {\n return {\n ...config.resourceAttributes,\n 'service.name': config.serviceName || 'unknown_service',\n ...config.environment && {\n 'deployment.environment': config.environment\n },\n ...config.serviceVersion && {\n 'service.version': config.serviceVersion\n },\n 'telemetry.sdk.name': scopeName,\n 'telemetry.sdk.version': scopeVersion\n };\n}\nfunction buildOtlpMetricsPayload(metrics, resourceAttributes, scopeName, scopeVersion) {\n return {\n resourceMetrics: [\n {\n resource: {\n attributes: toOtlpKeyValueList(resourceAttributes)\n },\n scopeMetrics: [\n {\n scope: {\n name: scopeName,\n version: scopeVersion\n },\n metrics\n }\n ]\n }\n ]\n };\n}\nexport { DEFAULT_HISTOGRAM_BOUNDS, bucketIndexFor, buildMetricsResourceAttributes, buildOtlpMetricsPayload, msToUnixNano, seriesKey };\n","const DEFAULT_FLUSH_INTERVAL_MS = 10000;\nconst DEFAULT_MAX_SERIES_PER_FLUSH = 1000;\nfunction resolveMetricsConfig(config) {\n const resourceAttributes = config?.resourceAttributes;\n return {\n serviceName: resourceAttributes?.['service.name'] ?? config?.serviceName,\n serviceVersion: resourceAttributes?.['service.version'] ?? config?.serviceVersion,\n environment: resourceAttributes?.['deployment.environment'] ?? config?.environment,\n resourceAttributes,\n beforeSend: config?.beforeSend,\n flushIntervalMs: config?.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,\n maxSeriesPerFlush: config?.maxSeriesPerFlush ?? DEFAULT_MAX_SERIES_PER_FLUSH\n };\n}\nexport { resolveMetricsConfig };\n","import { isArray, safeSetTimeout } from \"../utils/index.mjs\";\nimport { toOtlpKeyValueList } from \"../logs/logs-utils.mjs\";\nimport { DEFAULT_HISTOGRAM_BOUNDS, bucketIndexFor, buildMetricsResourceAttributes, buildOtlpMetricsPayload, msToUnixNano, seriesKey } from \"./metrics-utils.mjs\";\nimport { resolveMetricsConfig } from \"./config.mjs\";\nconst OTLP_TEMPORALITY_DELTA = 1;\nclass PostHogMetrics {\n constructor(_instance, _config, _logger){\n this._instance = _instance;\n this._config = _config;\n this._logger = _logger;\n this._series = new Map();\n this._flushPromise = null;\n this._seriesCapWarned = false;\n this._typeByName = new Map();\n this._typeCollisionWarned = new Set();\n this._generation = 0;\n }\n count(name, value = 1, options) {\n this._capture({\n name,\n type: 'count',\n value,\n unit: options?.unit,\n attributes: options?.attributes\n });\n }\n gauge(name, value, options) {\n this._capture({\n name,\n type: 'gauge',\n value,\n unit: options?.unit,\n attributes: options?.attributes\n });\n }\n histogram(name, value, options) {\n this._capture({\n name,\n type: 'histogram',\n value,\n unit: options?.unit,\n attributes: options?.attributes\n });\n }\n flush() {\n const prev = this._flushPromise;\n const run = async ()=>{\n if (prev) await prev.catch(()=>{});\n await this._doFlush();\n };\n const p = run().finally(()=>{\n if (this._flushPromise === p) this._flushPromise = null;\n });\n this._flushPromise = p;\n return p;\n }\n drainWindow() {\n if (0 === this._series.size) return null;\n const window = this._series;\n this._series = new Map();\n this._seriesCapWarned = false;\n this._typeByName = new Map();\n this._typeCollisionWarned = new Set();\n return this._buildPayload(window);\n }\n reset() {\n this._generation++;\n this._clearFlushTimer();\n this._series = new Map();\n this._flushPromise = null;\n this._seriesCapWarned = false;\n this._typeByName = new Map();\n this._typeCollisionWarned = new Set();\n }\n _capture(sample) {\n if (this._instance.isDisabled || this._instance.optedOut) return;\n const filtered = this._runBeforeSend(sample);\n if (null === filtered) return;\n if (!filtered.name || 'string' != typeof filtered.name) return void this._logger.warn('Dropping metric with empty name');\n if ('number' != typeof filtered.value || !Number.isFinite(filtered.value)) return void this._logger.warn(`Dropping metric '${filtered.name}': value must be a finite number`);\n if ('count' === filtered.type && filtered.value < 0) return void this._logger.warn(`Dropping count '${filtered.name}': counters are monotonic, value must be >= 0`);\n let attributes;\n let key;\n try {\n attributes = filtered.attributes ? {\n ...filtered.attributes\n } : void 0;\n key = seriesKey(filtered.type, filtered.name, filtered.unit, attributes);\n } catch (e) {\n this._logger.warn(`Dropping metric '${filtered.name}': attributes could not be serialized`, e);\n return;\n }\n let state = this._series.get(key);\n if (!state) {\n if (!this._admitNewSeries()) return;\n state = {\n name: filtered.name,\n type: filtered.type,\n unit: filtered.unit,\n attributes,\n windowStartMs: Date.now()\n };\n this._series.set(key, state);\n }\n const seenType = this._typeByName.get(filtered.name);\n if (void 0 === seenType) this._typeByName.set(filtered.name, filtered.type);\n else if (seenType !== filtered.type && !this._typeCollisionWarned.has(filtered.name)) {\n this._typeCollisionWarned.add(filtered.name);\n this._logger.warn(`Metric name '${filtered.name}' is already used as a ${seenType}; recording it as a ${filtered.type} too will blend both series in charts. Use a distinct name.`);\n }\n this._fold(state, filtered.value);\n this._armFlushTimer();\n }\n _admitNewSeries() {\n if (this._series.size < this._config.maxSeriesPerFlush) return true;\n if (!this._seriesCapWarned) {\n this._seriesCapWarned = true;\n this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`);\n }\n return false;\n }\n _fold(state, value) {\n switch(state.type){\n case 'count':\n state.total = (state.total ?? 0) + value;\n break;\n case 'gauge':\n state.last = value;\n break;\n case 'histogram':\n {\n if (!state.hist) state.hist = {\n count: 0,\n sum: 0,\n min: value,\n max: value,\n bucketCounts: new Array(DEFAULT_HISTOGRAM_BOUNDS.length + 1).fill(0)\n };\n const hist = state.hist;\n hist.count += 1;\n hist.sum += value;\n hist.min = Math.min(hist.min, value);\n hist.max = Math.max(hist.max, value);\n hist.bucketCounts[bucketIndexFor(value, DEFAULT_HISTOGRAM_BOUNDS)] += 1;\n break;\n }\n }\n }\n _runBeforeSend(sample) {\n const beforeSend = this._config.beforeSend;\n if (!beforeSend) return sample;\n const fns = isArray(beforeSend) ? beforeSend : [\n beforeSend\n ];\n let result = sample;\n for (const fn of fns)try {\n const next = fn(result);\n if (!next) {\n this._logger.info(\"Metric was rejected in beforeSend function\");\n return null;\n }\n result = next;\n } catch (e) {\n this._logger.error(\"Error in beforeSend function for metric:\", e);\n return null;\n }\n return result;\n }\n _armFlushTimer() {\n if (this._flushTimer) return;\n this._flushTimer = safeSetTimeout(()=>{\n this._flushTimer = void 0;\n this.flush().catch((e)=>{\n this._logger.error('Metrics flush failed:', e);\n });\n }, this._config.flushIntervalMs);\n }\n _clearFlushTimer() {\n if (this._flushTimer) {\n clearTimeout(this._flushTimer);\n this._flushTimer = void 0;\n }\n }\n async _doFlush() {\n if (0 === this._series.size) return;\n const window = this._series;\n this._series = new Map();\n this._seriesCapWarned = false;\n this._typeByName = new Map();\n this._typeCollisionWarned = new Set();\n const generation = this._generation;\n const outcome = await this._instance._sendMetricsBatch(this._buildPayload(window));\n if (generation !== this._generation) return;\n switch(outcome.kind){\n case 'ok':\n return;\n case 'retry-later':\n this._mergeWindowBack(window);\n this._armFlushTimer();\n return;\n case 'too-large':\n this._logger.warn('Metrics batch exceeded the server size limit and was dropped');\n return;\n case 'fatal':\n this._logger.error('Failed to send metrics batch:', outcome.error);\n return;\n }\n }\n _buildPayload(window) {\n return buildOtlpMetricsPayload(this._buildMetrics(window), buildMetricsResourceAttributes(this._config, this._instance.getLibraryId(), this._instance.getLibraryVersion()), this._instance.getLibraryId(), this._instance.getLibraryVersion());\n }\n _buildMetrics(window) {\n const nowNano = msToUnixNano(Date.now());\n const byMetric = new Map();\n for (const state of window.values()){\n const metricKey = seriesKey(state.type, state.name, state.unit, void 0);\n let metric = byMetric.get(metricKey);\n if (!metric) {\n metric = {\n name: state.name,\n ...state.unit && {\n unit: state.unit\n }\n };\n if ('count' === state.type) metric.sum = {\n aggregationTemporality: OTLP_TEMPORALITY_DELTA,\n isMonotonic: true,\n dataPoints: []\n };\n else if ('gauge' === state.type) metric.gauge = {\n dataPoints: []\n };\n else metric.histogram = {\n aggregationTemporality: OTLP_TEMPORALITY_DELTA,\n dataPoints: []\n };\n byMetric.set(metricKey, metric);\n }\n const attributes = toOtlpKeyValueList(state.attributes ?? {});\n const startNano = msToUnixNano(state.windowStartMs);\n if ('count' === state.type) {\n const dp = {\n attributes,\n startTimeUnixNano: startNano,\n timeUnixNano: nowNano,\n asDouble: state.total ?? 0\n };\n metric.sum.dataPoints.push(dp);\n } else if ('gauge' === state.type) {\n const dp = {\n attributes,\n timeUnixNano: nowNano,\n asDouble: state.last ?? 0\n };\n metric.gauge.dataPoints.push(dp);\n } else if (state.hist) {\n const dp = {\n attributes,\n startTimeUnixNano: startNano,\n timeUnixNano: nowNano,\n count: state.hist.count,\n sum: state.hist.sum,\n min: state.hist.min,\n max: state.hist.max,\n bucketCounts: state.hist.bucketCounts,\n explicitBounds: DEFAULT_HISTOGRAM_BOUNDS\n };\n metric.histogram.dataPoints.push(dp);\n }\n }\n return Array.from(byMetric.values());\n }\n _mergeWindowBack(window) {\n for (const [key, old] of window){\n const current = this._series.get(key);\n if (!current) {\n if (this._admitNewSeries()) this._series.set(key, old);\n continue;\n }\n current.windowStartMs = Math.min(current.windowStartMs, old.windowStartMs);\n switch(current.type){\n case 'count':\n current.total = (current.total ?? 0) + (old.total ?? 0);\n break;\n case 'gauge':\n break;\n case 'histogram':\n if (old.hist) if (current.hist) {\n current.hist.count += old.hist.count;\n current.hist.sum += old.hist.sum;\n current.hist.min = Math.min(current.hist.min, old.hist.min);\n current.hist.max = Math.max(current.hist.max, old.hist.max);\n for(let i = 0; i < current.hist.bucketCounts.length; i++)current.hist.bucketCounts[i] += old.hist.bucketCounts[i];\n } else current.hist = old.hist;\n break;\n }\n }\n }\n}\nexport { DEFAULT_HISTOGRAM_BOUNDS, PostHogMetrics, buildMetricsResourceAttributes, buildOtlpMetricsPayload, resolveMetricsConfig };\n","import { isArray, isNoLike } from \"./utils/index.mjs\";\nimport { uuidv7 } from \"./vendor/uuidv7.mjs\";\nconst COOKIE_PREFIX = 'ph_';\nconst COOKIE_SUFFIX = '_posthog';\nfunction cookieStoreFromHeader(cookieHeader) {\n const cookies = {};\n if (cookieHeader) for (const pair of cookieHeader.split(';')){\n const [key, ...valueParts] = pair.trim().split('=');\n if (key) {\n const raw = valueParts.join('=').trim();\n try {\n cookies[key.trim()] = decodeURIComponent(raw);\n } catch {\n cookies[key.trim()] = raw;\n }\n }\n }\n return {\n get: (name)=>name in cookies ? {\n value: cookies[name]\n } : void 0\n };\n}\nfunction getPostHogCookieName(apiKey) {\n const sanitized = apiKey.replace(/\\+/g, 'PL').replace(/\\//g, 'SL').replace(/=/g, 'EQ');\n return `${COOKIE_PREFIX}${sanitized}${COOKIE_SUFFIX}`;\n}\nfunction serializePostHogCookie(anonymousId) {\n const now = Date.now();\n const sessionId = uuidv7();\n return JSON.stringify({\n distinct_id: anonymousId,\n $device_id: anonymousId,\n $user_state: 'anonymous',\n $sesid: [\n now,\n sessionId,\n now\n ]\n });\n}\nfunction readPostHogCookie(cookies, apiKey) {\n const cookieName = getPostHogCookieName(apiKey);\n const cookie = cookies.get(cookieName);\n return cookie ? parsePostHogCookie(cookie.value) : null;\n}\nfunction cookieStateToProperties(state) {\n if (!state) return;\n const props = {};\n if (state.sessionId) props.$session_id = state.sessionId;\n if (state.deviceId) props.$device_id = state.deviceId;\n return Object.keys(props).length > 0 ? props : void 0;\n}\nfunction parsePostHogCookie(cookieValue) {\n if (!cookieValue) return null;\n try {\n const parsed = JSON.parse(cookieValue);\n if (!parsed || 'object' != typeof parsed || !parsed.distinct_id) return null;\n const sesid = isArray(parsed.$sesid) ? parsed.$sesid[1] : void 0;\n return {\n distinctId: String(parsed.distinct_id),\n isIdentified: 'identified' === parsed.$user_state,\n sessionId: 'string' == typeof sesid ? sesid : void 0,\n deviceId: 'string' == typeof parsed.$device_id ? parsed.$device_id : void 0\n };\n } catch {\n return null;\n }\n}\nconst CONSENT_PREFIX = '__ph_opt_in_out_';\nfunction getConsentCookieName(apiKey, config) {\n if (config?.consent_persistence_name) return config.consent_persistence_name;\n if (config?.opt_out_capturing_cookie_prefix) return config.opt_out_capturing_cookie_prefix + apiKey;\n return CONSENT_PREFIX + apiKey;\n}\nfunction isOptedOut(cookies, apiKey, config) {\n const cookieName = getConsentCookieName(apiKey, config);\n const cookie = cookies.get(cookieName);\n if (cookie) return isNoLike(cookie.value);\n return config?.opt_out_capturing_by_default ?? false;\n}\nexport { cookieStateToProperties, cookieStoreFromHeader, getConsentCookieName, getPostHogCookieName, isOptedOut, parsePostHogCookie, readPostHogCookie, serializePostHogCookie };\n","class SimpleEventEmitter {\n constructor(){\n this.events = {};\n this.events = {};\n }\n on(event, listener) {\n if (!this.events[event]) this.events[event] = [];\n this.events[event].push(listener);\n return ()=>{\n this.events[event] = this.events[event].filter((x)=>x !== listener);\n };\n }\n emit(event, payload) {\n for (const listener of this.events[event] || [])listener(payload);\n for (const listener of this.events['*'] || [])listener(event, payload);\n }\n}\nexport { SimpleEventEmitter };\n","let parsedStackResults;\nlet lastKeysCount;\nlet cachedFilenameChunkIds;\nfunction getFilenameToChunkIdMap(stackParser) {\n const chunkIdMap = globalThis._posthogChunkIds;\n if (!chunkIdMap) return;\n const chunkIdKeys = Object.keys(chunkIdMap);\n if (cachedFilenameChunkIds && chunkIdKeys.length === lastKeysCount) return cachedFilenameChunkIds;\n lastKeysCount = chunkIdKeys.length;\n cachedFilenameChunkIds = chunkIdKeys.reduce((acc, stackKey)=>{\n if (!parsedStackResults) parsedStackResults = {};\n const result = parsedStackResults[stackKey];\n if (result) acc[result[0]] = result[1];\n else {\n const parsedStack = stackParser(stackKey);\n for(let i = parsedStack.length - 1; i >= 0; i--){\n const stackFrame = parsedStack[i];\n const filename = stackFrame?.filename;\n const chunkId = chunkIdMap[stackKey];\n if (filename && chunkId) {\n acc[filename] = chunkId;\n parsedStackResults[stackKey] = [\n filename,\n chunkId\n ];\n break;\n }\n }\n }\n return acc;\n }, {});\n return cachedFilenameChunkIds;\n}\nexport { getFilenameToChunkIdMap };\n","import { isArray } from \"../utils/index.mjs\";\nimport { getFilenameToChunkIdMap } from \"./chunk-ids.mjs\";\nconst MAX_CAUSE_RECURSION = 4;\nclass ErrorPropertiesBuilder {\n constructor(coercers, stackParser, modifiers = []){\n this.coercers = coercers;\n this.stackParser = stackParser;\n this.modifiers = modifiers;\n }\n buildFromUnknown(input, hint = {}) {\n const providedMechanism = hint && hint.mechanism;\n const mechanism = providedMechanism || {\n handled: true,\n type: 'generic'\n };\n const coercingContext = this.buildCoercingContext(mechanism, hint, 0);\n const exceptionWithCause = coercingContext.apply(input);\n const parsingContext = this.buildParsingContext(hint);\n const exceptionWithStack = this.parseStacktrace(exceptionWithCause, parsingContext);\n const exceptionList = this.convertToExceptionList(exceptionWithStack, mechanism);\n return {\n $exception_list: exceptionList,\n $exception_level: 'error'\n };\n }\n async modifyFrames(exceptionList) {\n for (const exc of exceptionList)if (exc.stacktrace && exc.stacktrace.frames && isArray(exc.stacktrace.frames)) exc.stacktrace.frames = await this.applyModifiers(exc.stacktrace.frames);\n return exceptionList;\n }\n coerceFallback(ctx) {\n return {\n type: 'Error',\n value: 'Unknown error',\n stack: ctx.syntheticException?.stack,\n synthetic: true\n };\n }\n parseStacktrace(err, ctx) {\n let cause;\n if (null != err.cause) cause = this.parseStacktrace(err.cause, ctx);\n let stack;\n if ('' != err.stack && null != err.stack) stack = this.applyChunkIds(this.stackParser(err.stack, err.synthetic ? ctx.skipFirstLines : 0), ctx.chunkIdMap);\n return {\n ...err,\n cause,\n stack\n };\n }\n applyChunkIds(frames, chunkIdMap) {\n return frames.map((frame)=>{\n if (frame.filename && chunkIdMap) frame.chunk_id = chunkIdMap[frame.filename];\n return frame;\n });\n }\n applyCoercers(input, ctx) {\n for (const adapter of this.coercers)if (adapter.match(input)) return adapter.coerce(input, ctx);\n return this.coerceFallback(ctx);\n }\n async applyModifiers(frames) {\n let newFrames = frames;\n for (const modifier of this.modifiers)newFrames = await modifier(newFrames);\n return newFrames;\n }\n convertToExceptionList(exceptionWithStack, mechanism) {\n const currentException = {\n type: exceptionWithStack.type,\n value: exceptionWithStack.value,\n mechanism: {\n type: mechanism.type ?? 'generic',\n handled: mechanism.handled ?? true,\n synthetic: exceptionWithStack.synthetic ?? false\n }\n };\n if (exceptionWithStack.stack) currentException.stacktrace = {\n type: 'raw',\n frames: exceptionWithStack.stack\n };\n const exceptionList = [\n currentException\n ];\n if (null != exceptionWithStack.cause) exceptionList.push(...this.convertToExceptionList(exceptionWithStack.cause, {\n ...mechanism,\n handled: true\n }));\n return exceptionList;\n }\n buildParsingContext(hint) {\n const context = {\n chunkIdMap: getFilenameToChunkIdMap(this.stackParser),\n skipFirstLines: hint.skipFirstLines ?? 1\n };\n return context;\n }\n buildCoercingContext(mechanism, hint, depth = 0) {\n const coerce = (input, depth)=>{\n if (!(depth <= MAX_CAUSE_RECURSION)) return;\n {\n const ctx = this.buildCoercingContext(mechanism, hint, depth);\n return this.applyCoercers(input, ctx);\n }\n };\n const context = {\n ...hint,\n syntheticException: 0 == depth ? hint.syntheticException : void 0,\n mechanism,\n apply: (input)=>coerce(input, depth),\n next: (input)=>coerce(input, depth + 1)\n };\n return context;\n }\n}\nexport { ErrorPropertiesBuilder };\n","import { isUndefined } from \"../../utils/index.mjs\";\nconst UNKNOWN_FUNCTION = '?';\nfunction createFrame(platform, filename, func, lineno, colno) {\n const frame = {\n platform,\n filename,\n function: '<anonymous>' === func ? UNKNOWN_FUNCTION : func,\n in_app: true\n };\n if (!isUndefined(lineno)) frame.lineno = lineno;\n if (!isUndefined(colno)) frame.colno = colno;\n return frame;\n}\nexport { UNKNOWN_FUNCTION, createFrame };\n","import { UNKNOWN_FUNCTION } from \"./base.mjs\";\nconst extractSafariExtensionDetails = (func, filename)=>{\n const isSafariExtension = -1 !== func.indexOf('safari-extension');\n const isSafariWebExtension = -1 !== func.indexOf('safari-web-extension');\n return isSafariExtension || isSafariWebExtension ? [\n -1 !== func.indexOf('@') ? func.split('@')[0] : UNKNOWN_FUNCTION,\n isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`\n ] : [\n func,\n filename\n ];\n};\nexport { extractSafariExtensionDetails };\n","import { UNKNOWN_FUNCTION, createFrame } from \"./base.mjs\";\nimport { extractSafariExtensionDetails } from \"./safari.mjs\";\nconst chromeRegexNoFnName = /^\\s*at (\\S+?)(?::(\\d+))(?::(\\d+))\\s*$/i;\nconst chromeRegex = /^\\s*at (?:(.+?\\)(?: \\[.+\\])?|.*?) ?\\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\\/)?.*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\nconst chromeEvalRegex = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\nconst chromeStackLineParser = (line, platform)=>{\n const noFnParts = chromeRegexNoFnName.exec(line);\n if (noFnParts) {\n const [, filename, line, col] = noFnParts;\n return createFrame(platform, filename, UNKNOWN_FUNCTION, +line, +col);\n }\n const parts = chromeRegex.exec(line);\n if (parts) {\n const isEval = parts[2] && 0 === parts[2].indexOf('eval');\n if (isEval) {\n const subMatch = chromeEvalRegex.exec(parts[2]);\n if (subMatch) {\n parts[2] = subMatch[1];\n parts[3] = subMatch[2];\n parts[4] = subMatch[3];\n }\n }\n const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);\n return createFrame(platform, filename, func, parts[3] ? +parts[3] : void 0, parts[4] ? +parts[4] : void 0);\n }\n};\nexport { chromeStackLineParser };\n","import { UNKNOWN_FUNCTION, createFrame } from \"./base.mjs\";\nimport { extractSafariExtensionDetails } from \"./safari.mjs\";\nconst geckoREgex = /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)?((?:[-a-z]+)?:\\/.*?|\\[native code\\]|[^@]*(?:bundle|\\d+\\.js)|\\/[\\w\\-. /=]+)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nconst geckoEvalRegex = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\nconst geckoStackLineParser = (line, platform)=>{\n const parts = geckoREgex.exec(line);\n if (parts) {\n const isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n if (isEval) {\n const subMatch = geckoEvalRegex.exec(parts[3]);\n if (subMatch) {\n parts[1] = parts[1] || 'eval';\n parts[3] = subMatch[1];\n parts[4] = subMatch[2];\n parts[5] = '';\n }\n }\n let filename = parts[3];\n let func = parts[1] || UNKNOWN_FUNCTION;\n [func, filename] = extractSafariExtensionDetails(func, filename);\n return createFrame(platform, filename, func, parts[4] ? +parts[4] : void 0, parts[5] ? +parts[5] : void 0);\n }\n};\nexport { geckoStackLineParser };\n","import { UNKNOWN_FUNCTION, createFrame } from \"./base.mjs\";\nconst winjsRegex = /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:[-a-z]+):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\nconst winjsStackLineParser = (line, platform)=>{\n const parts = winjsRegex.exec(line);\n return parts ? createFrame(platform, parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : void 0) : void 0;\n};\nexport { winjsStackLineParser };\n","import { UNKNOWN_FUNCTION, createFrame } from \"./base.mjs\";\nconst opera10Regex = / line (\\d+).*script (?:in )?(\\S+)(?:: in function (\\S+))?$/i;\nconst opera10StackLineParser = (line, platform)=>{\n const parts = opera10Regex.exec(line);\n return parts ? createFrame(platform, parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : void 0;\n};\nconst opera11Regex = / line (\\d+), column (\\d+)\\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\\(.*\\))? in (.*):\\s*$/i;\nconst opera11StackLineParser = (line, platform)=>{\n const parts = opera11Regex.exec(line);\n return parts ? createFrame(platform, parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : void 0;\n};\nexport { opera10StackLineParser, opera11StackLineParser };\n","import { UNKNOWN_FUNCTION } from \"./base.mjs\";\nconst FILENAME_MATCH = /^\\s*[-]{4,}$/;\nconst FULL_MATCH = /at (?:async )?(?:(.+?)\\s+\\()?(?:(.+):(\\d+):(\\d+)?|([^)]+))\\)?/;\nconst nodeStackLineParser = (line, platform)=>{\n const lineMatch = line.match(FULL_MATCH);\n if (lineMatch) {\n let object;\n let method;\n let functionName;\n let typeName;\n let methodName;\n if (lineMatch[1]) {\n functionName = lineMatch[1];\n let methodStart = functionName.lastIndexOf('.');\n if ('.' === functionName[methodStart - 1]) methodStart--;\n if (methodStart > 0) {\n object = functionName.slice(0, methodStart);\n method = functionName.slice(methodStart + 1);\n const objectEnd = object.indexOf('.Module');\n if (objectEnd > 0) {\n functionName = functionName.slice(objectEnd + 1);\n object = object.slice(0, objectEnd);\n }\n }\n typeName = void 0;\n }\n if (method) {\n typeName = object;\n methodName = method;\n }\n if ('<anonymous>' === method) {\n methodName = void 0;\n functionName = void 0;\n }\n if (void 0 === functionName) {\n methodName = methodName || UNKNOWN_FUNCTION;\n functionName = typeName ? `${typeName}.${methodName}` : methodName;\n }\n let filename = lineMatch[2]?.startsWith('file://') ? lineMatch[2].slice(7) : lineMatch[2];\n const isNative = 'native' === lineMatch[5];\n if (filename?.match(/\\/[A-Z]:/)) filename = filename.slice(1);\n if (!filename && lineMatch[5] && !isNative) filename = lineMatch[5];\n return {\n filename: filename ? decodeURI(filename) : void 0,\n module: void 0,\n function: functionName,\n lineno: _parseIntOrUndefined(lineMatch[3]),\n colno: _parseIntOrUndefined(lineMatch[4]),\n in_app: filenameIsInApp(filename || '', isNative),\n platform: platform\n };\n }\n if (line.match(FILENAME_MATCH)) return {\n filename: line,\n platform: platform\n };\n};\nfunction filenameIsInApp(filename, isNative = false) {\n const isInternal = isNative || filename && !filename.startsWith('/') && !filename.match(/^[A-Z]:/) && !filename.startsWith('.') && !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\\-+])*:\\/\\//);\n return !isInternal && void 0 !== filename && !filename.includes('node_modules/');\n}\nfunction _parseIntOrUndefined(input) {\n return parseInt(input || '', 10) || void 0;\n}\nexport { nodeStackLineParser };\n","import { UNKNOWN_FUNCTION } from \"./base.mjs\";\nimport { chromeStackLineParser } from \"./chrome.mjs\";\nimport { geckoStackLineParser } from \"./gecko.mjs\";\nimport { winjsStackLineParser } from \"./winjs.mjs\";\nimport { opera10StackLineParser, opera11StackLineParser } from \"./opera.mjs\";\nimport { nodeStackLineParser } from \"./node.mjs\";\nconst WEBPACK_ERROR_REGEXP = /\\(error: (.*)\\)/;\nconst STACKTRACE_FRAME_LIMIT = 50;\nfunction reverseAndStripFrames(stack) {\n if (!stack.length) return [];\n const localStack = Array.from(stack);\n localStack.reverse();\n return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame)=>({\n ...frame,\n filename: frame.filename || getLastStackFrame(localStack).filename,\n function: frame.function || UNKNOWN_FUNCTION\n }));\n}\nfunction getLastStackFrame(arr) {\n return arr[arr.length - 1] || {};\n}\nfunction createDefaultStackParser() {\n return createStackParser(\"web:javascript\", chromeStackLineParser, geckoStackLineParser);\n}\nfunction createStackParser(platform, ...parsers) {\n return (stack, skipFirstLines = 0)=>{\n const frames = [];\n const lines = stack.split('\\n');\n for(let i = skipFirstLines; i < lines.length; i++){\n const line = lines[i];\n if (line.length > 1024) continue;\n const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;\n if (!cleanedLine.match(/\\S*Error: /)) {\n for (const parser of parsers){\n const frame = parser(cleanedLine, platform);\n if (frame) {\n frames.push(frame);\n break;\n }\n }\n if (frames.length >= STACKTRACE_FRAME_LIMIT) break;\n }\n }\n return reverseAndStripFrames(frames);\n };\n}\nexport { chromeStackLineParser, createDefaultStackParser, createStackParser, geckoStackLineParser, nodeStackLineParser, opera10StackLineParser, opera11StackLineParser, reverseAndStripFrames, winjsStackLineParser };\n","import { isBuiltin, isString } from \"../../utils/index.mjs\";\nclass DOMExceptionCoercer {\n match(err) {\n return this.isDOMException(err) || this.isDOMError(err);\n }\n coerce(err, ctx) {\n const hasStack = isString(err.stack);\n return {\n type: this.getType(err),\n value: this.getValue(err),\n stack: hasStack ? err.stack : void 0,\n cause: err.cause ? ctx.next(err.cause) : void 0,\n synthetic: false\n };\n }\n getType(candidate) {\n return this.isDOMError(candidate) ? 'DOMError' : 'DOMException';\n }\n getValue(err) {\n const name = err.name || (this.isDOMError(err) ? 'DOMError' : 'DOMException');\n const message = err.message ? `${name}: ${err.message}` : name;\n return message;\n }\n isDOMException(err) {\n return isBuiltin(err, 'DOMException');\n }\n isDOMError(err) {\n return isBuiltin(err, 'DOMError');\n }\n}\nexport { DOMExceptionCoercer };\n","import { isPlainError } from \"../../utils/index.mjs\";\nclass ErrorCoercer {\n match(err) {\n return isPlainError(err);\n }\n coerce(err, ctx) {\n return {\n type: this.getType(err),\n value: this.getMessage(err, ctx),\n stack: this.getStack(err),\n cause: err.cause ? ctx.next(err.cause) : void 0,\n synthetic: false\n };\n }\n getType(err) {\n return err.name || err.constructor.name;\n }\n getMessage(err, _ctx) {\n const message = err.message;\n if (message.error && 'string' == typeof message.error.message) return String(message.error.message);\n return String(message);\n }\n getStack(err) {\n return err.stacktrace || err.stack || void 0;\n }\n}\nexport { ErrorCoercer };\n","import { isErrorEvent } from \"../../utils/index.mjs\";\nclass ErrorEventCoercer {\n constructor(){}\n match(err) {\n return isErrorEvent(err) && void 0 != err.error;\n }\n coerce(err, ctx) {\n const exceptionLike = ctx.apply(err.error);\n if (!exceptionLike) return {\n type: 'ErrorEvent',\n value: err.message,\n stack: ctx.syntheticException?.stack,\n synthetic: true\n };\n return exceptionLike;\n }\n}\nexport { ErrorEventCoercer };\n","const ERROR_TYPES_PATTERN = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;\nclass StringCoercer {\n match(input) {\n return 'string' == typeof input;\n }\n coerce(input, ctx) {\n const [type, value] = this.getInfos(input);\n return {\n type: type ?? 'Error',\n value: value ?? input,\n stack: ctx.syntheticException?.stack,\n synthetic: true\n };\n }\n getInfos(candidate) {\n let type = 'Error';\n let value = candidate;\n const groups = candidate.match(ERROR_TYPES_PATTERN);\n if (groups) {\n type = groups[1];\n value = groups[2];\n }\n return [\n type,\n value\n ];\n }\n}\nexport { StringCoercer };\n","const severityLevels = [\n 'fatal',\n 'error',\n 'warning',\n 'log',\n 'info',\n 'debug'\n];\nexport { severityLevels };\n","function truncate(str, max = 0) {\n if ('string' != typeof str || 0 === max) return str;\n return str.length <= max ? str : `${str.slice(0, max)}...`;\n}\nfunction extractExceptionKeysForMessage(err, maxLength = 40) {\n const keys = Object.keys(err);\n keys.sort();\n if (!keys.length) return '[object has no keys]';\n for(let i = keys.length; i > 0; i--){\n const serialized = keys.slice(0, i).join(', ');\n if (!(serialized.length > maxLength)) {\n if (i === keys.length) return serialized;\n return serialized.length <= maxLength ? serialized : `${serialized.slice(0, maxLength)}...`;\n }\n }\n return '';\n}\nexport { extractExceptionKeysForMessage, truncate };\n","import { isEmptyString, isError, isEvent, isString } from \"../../utils/index.mjs\";\nimport { severityLevels } from \"../types.mjs\";\nimport { extractExceptionKeysForMessage } from \"./utils.mjs\";\nclass ObjectCoercer {\n match(candidate) {\n return 'object' == typeof candidate && null !== candidate;\n }\n coerce(candidate, ctx) {\n const errorProperty = this.getErrorPropertyFromObject(candidate);\n if (errorProperty) return ctx.apply(errorProperty);\n return {\n type: this.getType(candidate),\n value: this.getValue(candidate),\n stack: ctx.syntheticException?.stack,\n level: this.isSeverityLevel(candidate.level) ? candidate.level : 'error',\n synthetic: true\n };\n }\n getType(err) {\n return isEvent(err) ? err.constructor.name : 'Error';\n }\n getValue(err) {\n if ('name' in err && 'string' == typeof err.name) {\n let message = `'${err.name}' captured as exception`;\n if ('message' in err && 'string' == typeof err.message) message += ` with message: '${err.message}'`;\n return message;\n }\n if ('message' in err && 'string' == typeof err.message) return err.message;\n const className = this.getObjectClassName(err);\n const keys = extractExceptionKeysForMessage(err);\n return `${className && 'Object' !== className ? `'${className}'` : 'Object'} captured as exception with keys: ${keys}`;\n }\n isSeverityLevel(x) {\n return isString(x) && !isEmptyString(x) && severityLevels.indexOf(x) >= 0;\n }\n getErrorPropertyFromObject(obj) {\n for(const prop in obj)if (Object.prototype.hasOwnProperty.call(obj, prop)) {\n const value = obj[prop];\n if (isError(value)) return value;\n }\n }\n getObjectClassName(obj) {\n try {\n const prototype = Object.getPrototypeOf(obj);\n return prototype ? prototype.constructor.name : void 0;\n } catch (e) {\n return;\n }\n }\n}\nexport { ObjectCoercer };\n","import { isEvent } from \"../../utils/index.mjs\";\nimport { extractExceptionKeysForMessage } from \"./utils.mjs\";\nclass EventCoercer {\n match(err) {\n return isEvent(err);\n }\n coerce(evt, ctx) {\n const constructorName = evt.constructor.name;\n return {\n type: constructorName,\n value: `${constructorName} captured as exception with keys: ${extractExceptionKeysForMessage(evt)}`,\n stack: ctx.syntheticException?.stack,\n synthetic: true\n };\n }\n}\nexport { EventCoercer };\n","import { isPrimitive } from \"../../utils/index.mjs\";\nclass PrimitiveCoercer {\n match(candidate) {\n return isPrimitive(candidate);\n }\n coerce(value, ctx) {\n return {\n type: 'Error',\n value: `Primitive value captured as exception: ${String(value)}`,\n stack: ctx.syntheticException?.stack,\n synthetic: true\n };\n }\n}\nexport { PrimitiveCoercer };\n","import { isBuiltin, isEvent, isPrimitive } from \"../../utils/index.mjs\";\nclass PromiseRejectionEventCoercer {\n match(err) {\n return isBuiltin(err, 'PromiseRejectionEvent') || this.isCustomEventWrappingRejection(err);\n }\n isCustomEventWrappingRejection(err) {\n if (!isEvent(err)) return false;\n try {\n const detail = err.detail;\n return null != detail && 'object' == typeof detail && 'reason' in detail;\n } catch {\n return false;\n }\n }\n coerce(err, ctx) {\n const reason = this.getUnhandledRejectionReason(err);\n if (isPrimitive(reason)) return {\n type: 'UnhandledRejection',\n value: `Non-Error promise rejection captured with value: ${String(reason)}`,\n stack: ctx.syntheticException?.stack,\n synthetic: true\n };\n return ctx.apply(reason);\n }\n getUnhandledRejectionReason(error) {\n try {\n if ('reason' in error) return error.reason;\n if ('detail' in error && null != error.detail && 'object' == typeof error.detail && 'reason' in error.detail) return error.detail.reason;\n } catch {}\n return error;\n }\n}\nexport { PromiseRejectionEventCoercer };\n","export * from \"./dom-exception-coercer.mjs\";\nexport * from \"./error-coercer.mjs\";\nexport * from \"./error-event-coercer.mjs\";\nexport * from \"./string-coercer.mjs\";\nexport * from \"./object-coercer.mjs\";\nexport * from \"./event-coercer.mjs\";\nexport * from \"./primitive-coercer.mjs\";\nexport * from \"./promise-rejection-event.mjs\";\n","class ReduceableCache {\n constructor(_maxSize){\n this._maxSize = _maxSize;\n this._cache = new Map();\n }\n get(key) {\n const value = this._cache.get(key);\n if (void 0 === value) return;\n this._cache.delete(key);\n this._cache.set(key, value);\n return value;\n }\n set(key, value) {\n this._cache.set(key, value);\n }\n reduce() {\n while(this._cache.size >= this._maxSize){\n const value = this._cache.keys().next().value;\n if (value) this._cache.delete(value);\n }\n }\n}\nexport { ReduceableCache };\n","import { isNumber, isObject, isString, safeJsonStringify } from \"../utils/index.mjs\";\nconst EXCEPTION_STEP_INTERNAL_FIELDS = {\n MESSAGE: '$message',\n TIMESTAMP: '$timestamp'\n};\nconst RESERVED_EXCEPTION_STEP_KEYS = new Set([\n EXCEPTION_STEP_INTERNAL_FIELDS.MESSAGE,\n EXCEPTION_STEP_INTERNAL_FIELDS.TIMESTAMP\n]);\nconst DEFAULT_EXCEPTION_STEPS_CONFIG = {\n enabled: true,\n max_bytes: 32768\n};\nfunction resolveExceptionStepsConfig(config) {\n if (!config) return {\n ...DEFAULT_EXCEPTION_STEPS_CONFIG\n };\n return {\n enabled: config.enabled ?? DEFAULT_EXCEPTION_STEPS_CONFIG.enabled,\n max_bytes: normalizePositiveInteger(config.max_bytes, DEFAULT_EXCEPTION_STEPS_CONFIG.max_bytes)\n };\n}\nfunction stripReservedExceptionStepFields(properties) {\n if (!properties) return {\n sanitizedProperties: {},\n droppedKeys: []\n };\n const droppedKeys = [];\n const sanitizedProperties = Object.keys(properties).reduce((acc, key)=>{\n if (RESERVED_EXCEPTION_STEP_KEYS.has(key)) {\n droppedKeys.push(key);\n return acc;\n }\n acc[key] = properties[key];\n return acc;\n }, {});\n return {\n sanitizedProperties,\n droppedKeys\n };\n}\nclass ExceptionStepsBuffer {\n constructor(config){\n this._entries = [];\n this._totalBytes = 0;\n this._config = resolveExceptionStepsConfig(config);\n }\n setConfig(config) {\n this._config = resolveExceptionStepsConfig(config);\n this._trimToMaxBytes();\n }\n add(step) {\n const serialized = normalizeAndSerializeStep(step);\n if (!serialized) return;\n const bytes = getUtf8ByteLength(serialized.json);\n if (bytes > this._config.max_bytes) return;\n this._entries.push({\n step: serialized.step,\n bytes\n });\n this._totalBytes += bytes;\n this._trimToMaxBytes();\n }\n getAttachable() {\n return this._entries.map((e)=>e.step);\n }\n clear() {\n this._entries = [];\n this._totalBytes = 0;\n }\n size() {\n return this._entries.length;\n }\n _trimToMaxBytes() {\n while(this._totalBytes > this._config.max_bytes && this._entries.length > 0){\n const evicted = this._entries.shift();\n if (evicted) this._totalBytes -= evicted.bytes;\n }\n }\n}\nfunction normalizePositiveInteger(input, fallback) {\n if (!isNumber(input) || input === 1 / 0 || input === -1 / 0) return fallback;\n const normalized = Math.floor(input);\n if (normalized < 0) return fallback;\n return normalized;\n}\nfunction normalizeAndSerializeStep(step) {\n let json;\n try {\n json = safeJsonStringify(step);\n } catch {\n return;\n }\n try {\n const parsed = JSON.parse(json);\n if (!isObject(parsed)) return;\n const parsedStep = parsed;\n const message = parsedStep[EXCEPTION_STEP_INTERNAL_FIELDS.MESSAGE];\n const timestamp = parsedStep[EXCEPTION_STEP_INTERNAL_FIELDS.TIMESTAMP];\n if (!isString(message) || 0 === message.trim().length) return;\n if (!isString(timestamp) && !isNumber(timestamp)) return;\n return {\n step: parsedStep,\n json\n };\n } catch {\n return;\n }\n}\nfunction getUtf8ByteLength(value) {\n if ('undefined' != typeof TextEncoder) return new TextEncoder().encode(value).length;\n const encoded = encodeURIComponent(value);\n let byteLength = 0;\n for(let i = 0; i < encoded.length; i++)if ('%' === encoded[i]) {\n byteLength += 1;\n i += 2;\n } else byteLength += 1;\n return byteLength;\n}\nexport { DEFAULT_EXCEPTION_STEPS_CONFIG, EXCEPTION_STEP_INTERNAL_FIELDS, ExceptionStepsBuffer, getUtf8ByteLength, resolveExceptionStepsConfig, stripReservedExceptionStepFields };\n","export * from \"./error-properties-builder.mjs\";\nexport * from \"./parsers/index.mjs\";\nexport * from \"./coercers/index.mjs\";\nexport * from \"./utils.mjs\";\nexport * from \"./exception-steps.mjs\";\n","import { SimpleEventEmitter } from \"./eventemitter.mjs\";\nimport { getFeatureFlagValue, minimizeFlagCalledEventProperties, normalizeFlagsResponse } from \"./featureFlagUtils.mjs\";\nimport { gzipCompress, isGzipSupported } from \"./gzip.mjs\";\nimport { PostHogPersistedProperty } from \"./types.mjs\";\nimport { PromiseQueue, STRING_FORMAT, allSettled, createLogger, currentISOTime, getEventUuid, removeTrailingSlash, retriable, safeJsonStringify, safeSetTimeout } from \"./utils/index.mjs\";\nimport { uuidv7 } from \"./vendor/uuidv7.mjs\";\nimport { ErrorCoercer, ErrorPropertiesBuilder, ObjectCoercer, PrimitiveCoercer, StringCoercer, createDefaultStackParser } from \"./error-tracking/index.mjs\";\nclass PostHogFetchHttpError extends Error {\n constructor(response, reqByteLength){\n super('HTTP error while fetching PostHog: status=' + response.status + ', reqByteLength=' + reqByteLength), this.response = response, this.reqByteLength = reqByteLength, this.name = 'PostHogFetchHttpError';\n }\n get status() {\n return this.response.status;\n }\n get text() {\n return this.response.text();\n }\n get json() {\n return this.response.json();\n }\n}\nclass PostHogFetchNetworkError extends Error {\n constructor(error){\n super('Network error while fetching PostHog', error instanceof Error ? {\n cause: error\n } : {}), this.error = error, this.name = 'PostHogFetchNetworkError';\n }\n}\nconst maybeAdd = (key, value)=>void 0 !== value ? {\n [key]: value\n } : {};\nconst applyCallerFeatureFlagOverrides = (target, callerProperties)=>{\n for (const key of Object.keys(callerProperties))if (key.startsWith('$feature/') || '$active_feature_flags' === key) target[key] = callerProperties[key];\n};\nasync function logFlushError(err) {\n if (err instanceof PostHogFetchHttpError) {\n let text = '';\n try {\n text = await err.text;\n } catch {}\n console.error(`Error while flushing PostHog: message=${err.message}, response body=${text}`, err);\n } else console.error('Error while flushing PostHog', err);\n return Promise.resolve();\n}\nfunction isPostHogFetchError(err) {\n return 'object' == typeof err && (err instanceof PostHogFetchHttpError || isPostHogFetchNetworkError(err));\n}\nfunction isPostHogFetchNetworkError(err) {\n return err instanceof PostHogFetchNetworkError;\n}\nfunction isRetryableFlagsFetchError(err) {\n if (err instanceof PostHogFetchHttpError) return 502 === err.status || 504 === err.status;\n if (!(err instanceof PostHogFetchNetworkError)) return false;\n const cause = err.error;\n const code = cause?.code ?? cause?.cause?.code;\n return 'ECONNREFUSED' !== code;\n}\nfunction isPostHogFetchContentTooLargeError(err) {\n return 'object' == typeof err && err instanceof PostHogFetchHttpError && 413 === err.status;\n}\nfunction isPostHogFetchRetryableError(err) {\n if (err instanceof PostHogFetchHttpError) return 408 === err.status || 429 === err.status || err.status >= 500;\n return isPostHogFetchNetworkError(err);\n}\nfunction isPostHogEventProperties(value) {\n return null !== value && 'object' == typeof value && !Array.isArray(value);\n}\nvar posthog_core_stateless_QuotaLimitedFeature = /*#__PURE__*/ function(QuotaLimitedFeature) {\n QuotaLimitedFeature[\"FeatureFlags\"] = \"feature_flags\";\n QuotaLimitedFeature[\"Recordings\"] = \"recordings\";\n return QuotaLimitedFeature;\n}({});\nconst DEFAULT_QUEUE_ROUTE = 'default';\nclass PostHogCoreStateless {\n getErrorPropertiesBuilder() {\n if (!this._errorPropertiesBuilder) this._errorPropertiesBuilder = this.createErrorPropertiesBuilder();\n return this._errorPropertiesBuilder;\n }\n createErrorPropertiesBuilder() {\n return new ErrorPropertiesBuilder([\n new ErrorCoercer(),\n new ObjectCoercer(),\n new StringCoercer(),\n new PrimitiveCoercer()\n ], createDefaultStackParser());\n }\n constructor(apiKey, options = {}){\n this.flushPromise = null;\n this.pendingFlushPromise = null;\n this.flushPromises = new Set();\n this._dequeuedMessagesCount = 0;\n this.shutdownPromise = null;\n this.promiseQueue = new PromiseQueue();\n this._events = new SimpleEventEmitter();\n this._isInitialized = false;\n const normalizedApiKey = 'string' == typeof apiKey ? apiKey.trim() : '';\n const normalizedHost = 'string' == typeof options.host ? options.host.trim() : '';\n const missingApiKey = !normalizedApiKey;\n this._logger = createLogger('[PostHog]', this.logMsgIfDebug.bind(this));\n if (missingApiKey) this._logger.error(\"You must pass your PostHog project's api key. The client will be disabled.\");\n this.apiKey = normalizedApiKey;\n this.host = removeTrailingSlash(normalizedHost || 'https://us.i.posthog.com');\n this.flushAt = options.flushAt ? Math.max(options.flushAt, 1) : 20;\n this.maxBatchSize = Math.max(this.flushAt, options.maxBatchSize ?? 100);\n this.maxQueueSize = Math.max(this.flushAt, options.maxQueueSize ?? 1000);\n this.flushInterval = options.flushInterval ?? 10000;\n this.preloadFeatureFlags = options.preloadFeatureFlags ?? true;\n this.defaultOptIn = options.defaultOptIn ?? true;\n this.disableSurveys = options.disableSurveys ?? false;\n this._retryOptions = {\n retryCount: options.fetchRetryCount ?? 3,\n retryDelay: options.fetchRetryDelay ?? 3000,\n retryCheck: isPostHogFetchRetryableError\n };\n this.requestTimeout = options.requestTimeout ?? 10000;\n this.featureFlagsRequestTimeoutMs = options.featureFlagsRequestTimeoutMs ?? 3000;\n this.featureFlagsRequestMaxRetries = options.featureFlagsRequestMaxRetries ?? 1;\n this.remoteConfigRequestTimeoutMs = options.remoteConfigRequestTimeoutMs ?? 3000;\n this.disableGeoip = options.disableGeoip ?? true;\n this.disabled = (options.disabled ?? false) || missingApiKey;\n this.historicalMigration = options?.historicalMigration ?? false;\n this._initPromise = Promise.resolve();\n this._isInitialized = true;\n this.evaluationContexts = options?.evaluationContexts ?? options?.evaluationEnvironments;\n if (options?.evaluationEnvironments && !options?.evaluationContexts) this._logger.warn('evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.');\n this.disableCompression = !isGzipSupported() || (options?.disableCompression ?? false);\n }\n logMsgIfDebug(fn) {\n if (this.isDebug) fn();\n }\n wrap(fn) {\n if (this.disabled) return void this._logger.warn('The client is disabled');\n if (this._isInitialized) return fn();\n this._initPromise.then(()=>fn());\n }\n getCommonEventProperties() {\n return {\n $lib: this.getLibraryId(),\n $lib_version: this.getLibraryVersion()\n };\n }\n get optedOut() {\n return this.getPersistedProperty(PostHogPersistedProperty.OptedOut) ?? !this.defaultOptIn;\n }\n async optIn() {\n this.wrap(()=>{\n this.setPersistedProperty(PostHogPersistedProperty.OptedOut, false);\n });\n }\n async optOut() {\n this.wrap(()=>{\n this.setPersistedProperty(PostHogPersistedProperty.OptedOut, true);\n });\n }\n on(event, cb) {\n return this._events.on(event, cb);\n }\n debug(enabled = true) {\n this.removeDebugCallback?.();\n if (enabled) {\n const removeDebugCallback = this.on('*', (event, payload)=>this._logger.info(event, payload));\n this.removeDebugCallback = ()=>{\n removeDebugCallback();\n this.removeDebugCallback = void 0;\n };\n }\n }\n get isDebug() {\n return !!this.removeDebugCallback;\n }\n get isDisabled() {\n return this.disabled;\n }\n buildPayload(payload) {\n const userProperties = payload.properties || {};\n let properties = {\n ...userProperties,\n ...this.getCommonEventProperties()\n };\n applyCallerFeatureFlagOverrides(properties, userProperties);\n if ('$feature_flag_called' === payload.event && false === properties.$feature_flag_has_experiment && this.isMinimalFlagCalledEventsEnabled()) properties = minimizeFlagCalledEventProperties(properties);\n return {\n distinct_id: payload.distinct_id,\n event: payload.event,\n properties\n };\n }\n isMinimalFlagCalledEventsEnabled() {\n return false;\n }\n addPendingPromise(promise) {\n return this.promiseQueue.add(promise);\n }\n identifyStateless(distinctId, properties, options) {\n this.wrap(()=>{\n const payload = {\n ...this.buildPayload({\n distinct_id: distinctId,\n event: '$identify',\n properties\n })\n };\n this.enqueue('identify', payload, options);\n });\n }\n async identifyStatelessImmediate(distinctId, properties, options) {\n const payload = {\n ...this.buildPayload({\n distinct_id: distinctId,\n event: '$identify',\n properties\n })\n };\n await this.sendImmediate('identify', payload, options);\n }\n captureStateless(distinctId, event, properties, options) {\n this.wrap(()=>{\n const payload = this.buildPayload({\n distinct_id: distinctId,\n event,\n properties\n });\n this.enqueue('capture', payload, options);\n });\n }\n async captureStatelessImmediate(distinctId, event, properties, options) {\n const payload = this.buildPayload({\n distinct_id: distinctId,\n event,\n properties\n });\n await this.sendImmediate('capture', payload, options);\n }\n aliasStateless(alias, distinctId, properties, options) {\n this.wrap(()=>{\n const payload = this.buildPayload({\n event: '$create_alias',\n distinct_id: distinctId,\n properties: {\n ...properties || {},\n distinct_id: distinctId,\n alias\n }\n });\n this.enqueue('alias', payload, options);\n });\n }\n async aliasStatelessImmediate(alias, distinctId, properties, options) {\n const payload = this.buildPayload({\n event: '$create_alias',\n distinct_id: distinctId,\n properties: {\n ...properties || {},\n distinct_id: distinctId,\n alias\n }\n });\n await this.sendImmediate('alias', payload, options);\n }\n groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {\n this.wrap(()=>{\n const payload = this.buildPayload({\n distinct_id: distinctId || `$${groupType}_${groupKey}`,\n event: '$groupidentify',\n properties: {\n $group_type: groupType,\n $group_key: groupKey,\n $group_set: groupProperties || {},\n ...eventProperties || {}\n }\n });\n this.enqueue('capture', payload, options);\n });\n }\n async groupIdentifyStatelessImmediate(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {\n const payload = this.buildPayload({\n distinct_id: distinctId || `$${groupType}_${groupKey}`,\n event: '$groupidentify',\n properties: {\n $group_type: groupType,\n $group_key: groupKey,\n $group_set: groupProperties || {},\n ...eventProperties || {}\n }\n });\n await this.sendImmediate('capture', payload, options);\n }\n async getRemoteConfig() {\n await this._initPromise;\n let host = this.host;\n if ('https://us.i.posthog.com' === host) host = 'https://us-assets.i.posthog.com';\n else if ('https://eu.i.posthog.com' === host) host = 'https://eu-assets.i.posthog.com';\n const url = `${host}/array/${this.apiKey}/config`;\n const fetchOptions = {\n method: 'GET',\n headers: {\n ...this.getCustomHeaders(),\n 'Content-Type': 'application/json'\n }\n };\n return this.fetchWithRetry(url, fetchOptions, {\n retryCount: 0\n }, this.remoteConfigRequestTimeoutMs).then((response)=>response.json()).catch((error)=>{\n this._logger.error('Remote config could not be loaded', error);\n this._events.emit('error', error);\n });\n }\n async getFlags(distinctId, groups = {}, personProperties = {}, groupProperties = {}, extraPayload = {}, fetchConfig = false) {\n await this._initPromise;\n const configParam = fetchConfig ? '&config=true' : '';\n const url = `${this.host}/flags/?v=2${configParam}`;\n const requestData = {\n token: this.apiKey,\n distinct_id: distinctId,\n groups,\n person_properties: personProperties,\n group_properties: groupProperties,\n ...extraPayload\n };\n if (personProperties.$device_id) requestData.$device_id = personProperties.$device_id;\n if (this.evaluationContexts && this.evaluationContexts.length > 0) requestData.evaluation_contexts = this.evaluationContexts;\n const fetchOptions = {\n method: 'POST',\n headers: {\n ...this.getCustomHeaders(),\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(requestData)\n };\n this._logger.info('Flags URL', url);\n return this.fetchWithRetry(url, fetchOptions, {\n retryCount: this.featureFlagsRequestMaxRetries,\n retryCheck: isRetryableFlagsFetchError\n }, this.featureFlagsRequestTimeoutMs).then((response)=>response.json()).then((response)=>({\n success: true,\n response: normalizeFlagsResponse(response)\n })).catch((error)=>{\n this._events.emit('error', error);\n return {\n success: false,\n error: this.categorizeRequestError(error)\n };\n });\n }\n categorizeRequestError(error) {\n if (error instanceof PostHogFetchHttpError) return {\n type: 'api_error',\n statusCode: error.status\n };\n if (error instanceof PostHogFetchNetworkError) {\n const cause = error.error;\n if (cause instanceof Error && ('AbortError' === cause.name || 'TimeoutError' === cause.name)) return {\n type: 'timeout'\n };\n return {\n type: 'connection_error'\n };\n }\n return {\n type: 'unknown_error'\n };\n }\n async getFeatureFlagStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {\n await this._initPromise;\n const flagDetailResponse = await this.getFeatureFlagDetailStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);\n if (void 0 === flagDetailResponse) return {\n response: void 0,\n requestId: void 0\n };\n let response = getFeatureFlagValue(flagDetailResponse.response);\n if (void 0 === response) response = false;\n return {\n response,\n requestId: flagDetailResponse.requestId\n };\n }\n async getFeatureFlagDetailStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {\n await this._initPromise;\n const flagsResponse = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [\n key\n ]);\n if (void 0 === flagsResponse) return;\n const featureFlags = flagsResponse.flags;\n const flagDetail = featureFlags[key];\n return {\n response: flagDetail,\n requestId: flagsResponse.requestId,\n evaluatedAt: flagsResponse.evaluatedAt\n };\n }\n async getFeatureFlagPayloadStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {\n await this._initPromise;\n const payloads = await this.getFeatureFlagPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [\n key\n ]);\n if (!payloads) return;\n const response = payloads[key];\n if (void 0 === response) return null;\n return response;\n }\n async getFeatureFlagPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {\n await this._initPromise;\n const payloads = (await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate)).payloads;\n return payloads;\n }\n async getFeatureFlagsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {\n await this._initPromise;\n return await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);\n }\n async getFeatureFlagsAndPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {\n await this._initPromise;\n const featureFlagDetails = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);\n if (!featureFlagDetails) return {\n flags: void 0,\n payloads: void 0,\n requestId: void 0\n };\n return {\n flags: featureFlagDetails.featureFlags,\n payloads: featureFlagDetails.featureFlagPayloads,\n requestId: featureFlagDetails.requestId\n };\n }\n async getFeatureFlagDetailsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {\n await this._initPromise;\n const extraPayload = {\n geoip_disable: disableGeoip ?? this.disableGeoip\n };\n if (flagKeysToEvaluate) extraPayload['flag_keys_to_evaluate'] = flagKeysToEvaluate;\n const result = await this.getFlags(distinctId, groups, personProperties, groupProperties, extraPayload);\n if (!result.success) return;\n const flagsResponse = result.response;\n if (flagsResponse.errorsWhileComputingFlags) console.error('[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices');\n if (flagsResponse.quotaLimited?.includes(\"feature_flags\")) {\n console.warn('[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts');\n return {\n flags: {},\n featureFlags: {},\n featureFlagPayloads: {},\n requestId: flagsResponse?.requestId,\n quotaLimited: flagsResponse.quotaLimited\n };\n }\n return flagsResponse;\n }\n async getSurveysStateless() {\n await this._initPromise;\n if (this.disabled) return [];\n if (true === this.disableSurveys) {\n this._logger.info('Loading surveys is disabled.');\n return [];\n }\n const url = `${this.host}/api/surveys/?token=${this.apiKey}`;\n const fetchOptions = {\n method: 'GET',\n headers: {\n ...this.getCustomHeaders(),\n 'Content-Type': 'application/json'\n }\n };\n const response = await this.fetchWithRetry(url, fetchOptions).then((response)=>{\n if (200 !== response.status || !response.json) {\n const msg = `Surveys API could not be loaded: ${response.status}`;\n const error = new Error(msg);\n this._logger.error(error);\n this._events.emit('error', new Error(msg));\n return;\n }\n return response.json();\n }).catch((error)=>{\n this._logger.error('Surveys API could not be loaded', error);\n this._events.emit('error', error);\n });\n const newSurveys = response?.surveys;\n if (newSurveys) this._logger.info('Surveys fetched from API: ', JSON.stringify(newSurveys));\n return newSurveys ?? [];\n }\n get props() {\n if (!this._props) this._props = this.getPersistedProperty(PostHogPersistedProperty.Props);\n return this._props || {};\n }\n set props(val) {\n this._props = val;\n }\n async register(properties) {\n this.wrap(()=>{\n this.props = {\n ...this.props,\n ...properties\n };\n this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);\n });\n }\n async unregister(property) {\n this.wrap(()=>{\n delete this.props[property];\n this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);\n });\n }\n processBeforeEnqueue(message) {\n return message;\n }\n async flushStorage() {}\n getQueueRouteKey(_message) {\n return DEFAULT_QUEUE_ROUTE;\n }\n persistedQueueKeyForRoute(_route) {\n return PostHogPersistedProperty.Queue;\n }\n getActiveQueueRoutes() {\n return [\n DEFAULT_QUEUE_ROUTE\n ];\n }\n getRouteQueue(route) {\n return this.getPersistedProperty(this.persistedQueueKeyForRoute(route)) || [];\n }\n enqueue(type, _message, options) {\n this.wrap(()=>{\n if (this.optedOut) return void this._events.emit(type, \"Library is disabled. Not sending event. To re-enable, call posthog.optIn()\");\n let message = this.prepareMessage(_message, options);\n message = this.processBeforeEnqueue(message);\n if (null === message) return;\n message = this.normalizeMessage(message);\n const queueKey = this.persistedQueueKeyForRoute(this.getQueueRouteKey(message));\n const queue = this.getPersistedProperty(queueKey) || [];\n if (queue.length >= this.maxQueueSize) {\n queue.shift();\n this._logger.warn('Queue is full, the oldest event is dropped.');\n }\n queue.push({\n message\n });\n this.setPersistedProperty(queueKey, queue);\n this._events.emit(type, message);\n if (queue.length >= this.flushAt) this.flushBackground();\n if (this.flushInterval && !this._flushTimer) this._flushTimer = safeSetTimeout(()=>this.flushBackground(), this.flushInterval);\n });\n }\n async sendImmediate(type, _message, options) {\n if (this.disabled) return void this._logger.warn('The client is disabled');\n if (!this._isInitialized) await this._initPromise;\n if (this.optedOut) return void this._events.emit(type, \"Library is disabled. Not sending event. To re-enable, call posthog.optIn()\");\n let message = this.prepareMessage(_message, options);\n message = this.processBeforeEnqueue(message);\n if (null === message) return;\n message = this.normalizeMessage(message);\n try {\n await this.sendBatch([\n message\n ], void 0, this.getQueueRouteKey(message));\n } catch (err) {\n this._events.emit('error', err);\n }\n }\n normalizeMessage(message) {\n const { type: _type, library, library_version, ...sanitizedMessage } = message;\n let properties = isPostHogEventProperties(sanitizedMessage.properties) ? sanitizedMessage.properties : void 0;\n if (void 0 !== library && properties?.$lib === void 0) properties = {\n ...properties || {},\n $lib: library\n };\n if (void 0 !== library_version && properties?.$lib_version === void 0) properties = {\n ...properties || {},\n $lib_version: library_version\n };\n if (properties) sanitizedMessage.properties = properties;\n sanitizedMessage.uuid = getEventUuid(sanitizedMessage.uuid, uuidv7);\n return sanitizedMessage;\n }\n prepareMessage(_message, options) {\n const message = {\n ..._message,\n timestamp: options?.timestamp ? options?.timestamp : currentISOTime(),\n uuid: getEventUuid(options?.uuid, uuidv7)\n };\n const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip;\n if (addGeoipDisableProperty) {\n if (!isPostHogEventProperties(message.properties)) message.properties = {};\n message.properties['$geoip_disable'] = true;\n }\n if (message.distinctId) {\n message.distinct_id = message.distinctId;\n delete message.distinctId;\n }\n return message;\n }\n clearFlushTimer() {\n if (this._flushTimer) {\n clearTimeout(this._flushTimer);\n this._flushTimer = void 0;\n }\n }\n flushBackground() {\n if (this.pendingFlushPromise) return;\n this.flush().catch(async (err)=>{\n await logFlushError(err);\n });\n }\n async waitForPendingPromises(maxPromiseId, ignoredPromises = []) {\n const ignoredPendingPromises = ignoredPromises.filter((promise)=>!!promise);\n let iteration = 0;\n while(true){\n const promises = this.promiseQueue.getPromises([\n ...ignoredPendingPromises,\n ...this.flushPromises\n ], maxPromiseId);\n if (0 === promises.length) return;\n if (iteration > 0) this._logger.debug(`flush() re-checking ${promises.length} pending promise(s) before flushing`);\n await Promise.all(promises.map((promise)=>promise.catch(()=>{})));\n iteration++;\n }\n }\n flushWithPendingPromises() {\n return this.flushInternal(true);\n }\n flush() {\n return this.flushInternal(false);\n }\n flushInternal(waitForPendingPromises) {\n if (this.disabled) return Promise.resolve();\n if (!waitForPendingPromises && this.pendingFlushPromise) return this.pendingFlushPromise;\n const previousFlushPromise = this.flushPromise;\n const maxPromiseId = this.promiseQueue.maxId;\n const nextFlushPromise = Promise.resolve().then(()=>{\n if (waitForPendingPromises) return this.waitForPendingPromises(maxPromiseId, [\n previousFlushPromise,\n nextFlushPromise\n ]);\n }).then(()=>allSettled([\n previousFlushPromise\n ])).then(()=>{\n if (this.pendingFlushPromise === nextFlushPromise) this.pendingFlushPromise = null;\n return this._flush();\n });\n this.pendingFlushPromise = nextFlushPromise;\n this.flushPromise = nextFlushPromise;\n this.flushPromises.add(nextFlushPromise);\n this.addPendingPromise(nextFlushPromise);\n allSettled([\n nextFlushPromise\n ]).then(()=>{\n this.flushPromises.delete(nextFlushPromise);\n if (this.pendingFlushPromise === nextFlushPromise) this.pendingFlushPromise = null;\n if (this.flushPromise === nextFlushPromise) this.flushPromise = null;\n });\n return nextFlushPromise;\n }\n getCustomHeaders() {\n const customUserAgent = this.getCustomUserAgent();\n const headers = {};\n if (customUserAgent && '' !== customUserAgent) headers['User-Agent'] = customUserAgent;\n return headers;\n }\n async sendBatch(batchMessages, retryOptions, _route = DEFAULT_QUEUE_ROUTE) {\n const data = {\n api_key: this.apiKey,\n batch: batchMessages,\n sent_at: currentISOTime()\n };\n if (this.historicalMigration) data.historical_migration = true;\n const payload = safeJsonStringify(data);\n const url = `${this.host}/batch/`;\n const gzippedPayload = this.disableCompression ? null : await gzipCompress(payload, this.isDebug);\n const fetchOptions = {\n method: 'POST',\n headers: {\n ...this.getCustomHeaders(),\n 'Content-Type': 'application/json',\n ...null !== gzippedPayload && {\n 'Content-Encoding': 'gzip'\n }\n },\n body: gzippedPayload || payload\n };\n const response = await this.fetchWithRetry(url, fetchOptions, retryOptions);\n await response.body?.cancel()?.catch(()=>{});\n }\n async _flush() {\n this.clearFlushTimer();\n await this._initPromise;\n const routes = this.getActiveQueueRoutes();\n if (!routes.some((route)=>this.getRouteQueue(route).length > 0)) return;\n const sentMessages = [];\n let firstError;\n for (const route of routes)try {\n await this._flushRoute(route, sentMessages);\n } catch (err) {\n if (void 0 === firstError) firstError = err;\n }\n if (void 0 !== firstError) throw firstError;\n this._events.emit('flush', sentMessages);\n }\n async _flushRoute(route, sentMessages) {\n const queueKey = this.persistedQueueKeyForRoute(route);\n let queue = this.getPersistedProperty(queueKey) || [];\n if (!queue.length) return;\n const originalQueueLength = queue.length;\n let sentFromRoute = 0;\n while(queue.length > 0 && sentFromRoute < originalQueueLength){\n const batchItems = queue.slice(0, this.maxBatchSize);\n const batchMessages = batchItems.map((item)=>void 0 === item.message ? item.message : this.normalizeMessage(item.message));\n const persistQueueChange = async ()=>{\n const refreshedQueue = this.getPersistedProperty(queueKey) || [];\n const newQueue = refreshedQueue.slice(batchItems.length);\n this.setPersistedProperty(queueKey, newQueue);\n queue = newQueue;\n this._dequeuedMessagesCount += batchItems.length;\n await this.flushStorage();\n };\n const retryOptions = {\n retryCheck: (err)=>{\n if (isPostHogFetchContentTooLargeError(err)) return false;\n return isPostHogFetchRetryableError(err);\n }\n };\n try {\n await this.sendBatch(batchMessages, retryOptions, route);\n } catch (err) {\n if (isPostHogFetchContentTooLargeError(err) && batchMessages.length > 1) {\n this.maxBatchSize = Math.max(1, Math.floor(batchMessages.length / 2));\n this._logger.warn(`Received 413 when sending batch of size ${batchMessages.length}, reducing batch size to ${this.maxBatchSize}`);\n continue;\n }\n if (!(err instanceof PostHogFetchNetworkError)) await persistQueueChange();\n this._events.emit('error', err);\n throw err;\n }\n await persistQueueChange();\n sentMessages.push(...batchMessages);\n sentFromRoute += batchMessages.length;\n }\n }\n async _sendLogsBatch(payload) {\n if (this.disabled) return {\n kind: 'fatal',\n error: new Error('The client is disabled')\n };\n const serialized = JSON.stringify(payload);\n const url = `${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`;\n const gzippedPayload = this.disableCompression ? null : await gzipCompress(serialized, this.isDebug);\n const fetchOptions = {\n method: 'POST',\n headers: {\n ...this.getCustomHeaders(),\n 'Content-Type': 'application/json',\n ...null !== gzippedPayload && {\n 'Content-Encoding': 'gzip'\n }\n },\n body: gzippedPayload || serialized\n };\n try {\n await this.fetchWithRetry(url, fetchOptions, {\n retryCheck: (err)=>{\n if (isPostHogFetchContentTooLargeError(err)) return false;\n return isPostHogFetchRetryableError(err);\n }\n });\n return {\n kind: 'ok'\n };\n } catch (err) {\n if (isPostHogFetchContentTooLargeError(err)) return {\n kind: 'too-large'\n };\n if (err instanceof PostHogFetchNetworkError) return {\n kind: 'retry-later',\n error: err\n };\n return {\n kind: 'fatal',\n error: err\n };\n }\n }\n async _sendMetricsBatch(payload) {\n if (this.disabled) return {\n kind: 'fatal',\n error: new Error('The client is disabled')\n };\n const serialized = JSON.stringify(payload);\n const url = `${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`;\n const gzippedPayload = this.disableCompression ? null : await gzipCompress(serialized, this.isDebug);\n const fetchOptions = {\n method: 'POST',\n headers: {\n ...this.getCustomHeaders(),\n 'Content-Type': 'application/json',\n ...null !== gzippedPayload && {\n 'Content-Encoding': 'gzip'\n }\n },\n body: gzippedPayload || serialized\n };\n try {\n await this.fetchWithRetry(url, fetchOptions, {\n retryCheck: (err)=>{\n if (isPostHogFetchContentTooLargeError(err)) return false;\n return isPostHogFetchRetryableError(err);\n }\n });\n return {\n kind: 'ok'\n };\n } catch (err) {\n if (isPostHogFetchContentTooLargeError(err)) return {\n kind: 'too-large'\n };\n if (isPostHogFetchRetryableError(err)) return {\n kind: 'retry-later',\n error: err\n };\n return {\n kind: 'fatal',\n error: err\n };\n }\n }\n async fetchWithRetry(url, options, retryOptions, requestTimeout) {\n const body = options.body ? options.body : '';\n let reqByteLength = -1;\n try {\n reqByteLength = body instanceof Blob ? body.size : Buffer.byteLength(body, STRING_FORMAT);\n } catch {\n if (body instanceof Blob) reqByteLength = body.size;\n else {\n const encoded = new TextEncoder().encode(body);\n reqByteLength = encoded.length;\n }\n }\n return await retriable(async ()=>{\n const ctrl = new AbortController();\n const timeoutMs = requestTimeout ?? this.requestTimeout;\n const timer = safeSetTimeout(()=>ctrl.abort(), timeoutMs);\n let res = null;\n try {\n res = await this.fetch(url, {\n signal: ctrl.signal,\n ...options\n });\n } catch (e) {\n throw new PostHogFetchNetworkError(e);\n } finally{\n clearTimeout(timer);\n }\n const isNoCors = 'no-cors' === options.mode;\n if (!isNoCors && (res.status < 200 || res.status >= 400)) throw new PostHogFetchHttpError(res, reqByteLength);\n return res;\n }, {\n ...this._retryOptions,\n ...retryOptions\n });\n }\n async _shutdown(shutdownTimeoutMs = 30000) {\n await this._initPromise;\n let hasTimedOut = false;\n this.clearFlushTimer();\n if (this.disabled) return;\n const doShutdown = async ()=>{\n try {\n await this.promiseQueue.join();\n while(true){\n const hasQueuedEvents = this.getActiveQueueRoutes().some((route)=>this.getRouteQueue(route).length > 0);\n if (!hasQueuedEvents) break;\n const dequeuedBeforeFlush = this._dequeuedMessagesCount;\n await this.flush();\n if (hasTimedOut) break;\n if (this._dequeuedMessagesCount === dequeuedBeforeFlush) {\n this._logger.warn('Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.');\n break;\n }\n }\n } catch (e) {\n if (!isPostHogFetchError(e)) throw e;\n await logFlushError(e);\n }\n };\n let timeoutHandle;\n try {\n return await Promise.race([\n new Promise((_, reject)=>{\n timeoutHandle = safeSetTimeout(()=>{\n this._logger.error('Timed out while shutting down PostHog');\n hasTimedOut = true;\n reject('Timeout while shutting down PostHog. Some events may not have been sent.');\n }, shutdownTimeoutMs);\n }),\n doShutdown()\n ]);\n } finally{\n clearTimeout(timeoutHandle);\n }\n }\n async shutdown(shutdownTimeoutMs = 30000) {\n if (this.shutdownPromise) this._logger.warn('shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup');\n else this.shutdownPromise = this._shutdown(shutdownTimeoutMs).finally(()=>{\n this.shutdownPromise = null;\n });\n return this.shutdownPromise;\n }\n}\nexport { PostHogCoreStateless, posthog_core_stateless_QuotaLimitedFeature as QuotaLimitedFeature, applyCallerFeatureFlagOverrides, isPostHogFetchNetworkError, logFlushError, maybeAdd };\n","import { createFlagsResponseFromFlagsAndPayloads, flagDetailsToResults, getEnabledFromValue, getFeatureFlagValue, getFlagValuesFromFlags, getPayloadsFromFlags, getVariantFromValue, normalizeFlagsResponse, parsePayload, updateFlagValue } from \"./featureFlagUtils.mjs\";\nimport { Compression, FeatureFlagError, PostHogPersistedProperty } from \"./types.mjs\";\nimport { PostHogCoreStateless, QuotaLimitedFeature, applyCallerFeatureFlagOverrides, maybeAdd } from \"./posthog-core-stateless.mjs\";\nimport { uuidv7 } from \"./vendor/uuidv7.mjs\";\nimport { getEventUuid, getPersonPropertiesHash, isArray, isEmptyObject, isNullish, isObject, isString } from \"./utils/index.mjs\";\nclass PostHogCore extends PostHogCoreStateless {\n constructor(apiKey, options){\n const disableGeoipOption = options?.disableGeoip ?? false;\n const featureFlagsRequestTimeoutMs = options?.featureFlagsRequestTimeoutMs ?? 10000;\n super(apiKey, {\n ...options,\n disableGeoip: disableGeoipOption,\n featureFlagsRequestTimeoutMs\n }), this.flagCallReported = {}, this._sessionMaxLengthSeconds = 86400, this.sessionProps = {}, this._cachedPersonProperties = null;\n this.sendFeatureFlagEvent = options?.sendFeatureFlagEvent ?? true;\n this.disableRemoteFeatureFlags = options?.disableRemoteFeatureFlags ?? false;\n this._sessionExpirationTimeSeconds = options?.sessionExpirationTimeSeconds ?? 1800;\n this._personProfiles = options?.personProfiles ?? 'identified_only';\n this._beforeSend = options?.before_send;\n }\n setupBootstrap(options) {\n const bootstrap = options?.bootstrap;\n if (!bootstrap) return;\n if (bootstrap.distinctId) if (bootstrap.isIdentifiedId) {\n const distinctId = this.getPersistedProperty(PostHogPersistedProperty.DistinctId);\n if (!distinctId) {\n this.setPersistedProperty(PostHogPersistedProperty.DistinctId, bootstrap.distinctId);\n this.setPersistedProperty(PostHogPersistedProperty.PersonMode, 'identified');\n }\n } else {\n const anonymousId = this.getPersistedProperty(PostHogPersistedProperty.AnonymousId);\n if (!anonymousId) this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, bootstrap.distinctId);\n }\n const bootstrapFeatureFlags = bootstrap.featureFlags;\n const bootstrapFeatureFlagPayloads = bootstrap.featureFlagPayloads ?? {};\n if (bootstrapFeatureFlags && Object.keys(bootstrapFeatureFlags).length) {\n const normalizedBootstrapFeatureFlagDetails = createFlagsResponseFromFlagsAndPayloads(bootstrapFeatureFlags, bootstrapFeatureFlagPayloads);\n if (Object.keys(normalizedBootstrapFeatureFlagDetails.flags).length > 0) {\n this.setBootstrappedFeatureFlagDetails(normalizedBootstrapFeatureFlagDetails);\n const currentFeatureFlagDetails = this.getKnownFeatureFlagDetails() || {\n flags: {},\n requestId: void 0\n };\n const newFeatureFlagDetails = {\n flags: {\n ...normalizedBootstrapFeatureFlagDetails.flags,\n ...currentFeatureFlagDetails.flags\n },\n requestId: normalizedBootstrapFeatureFlagDetails.requestId\n };\n this.setKnownFeatureFlagDetails(newFeatureFlagDetails);\n }\n }\n }\n clearProps() {\n this.props = void 0;\n this.sessionProps = {};\n this.flagCallReported = {};\n }\n on(event, cb) {\n return this._events.on(event, cb);\n }\n reset(propertiesToKeep) {\n this.wrap(()=>{\n const allPropertiesToKeep = [\n PostHogPersistedProperty.Queue,\n PostHogPersistedProperty.AiQueue,\n PostHogPersistedProperty.LogsQueue,\n ...propertiesToKeep || []\n ];\n this.clearProps();\n this._cachedPersonProperties = null;\n for (const key of Object.keys(PostHogPersistedProperty))if (!allPropertiesToKeep.includes(PostHogPersistedProperty[key])) this.setPersistedProperty(PostHogPersistedProperty[key], null);\n if (this.disableRemoteFeatureFlags && !this.disabled) {\n if (!allPropertiesToKeep.includes(PostHogPersistedProperty.FeatureFlagDetails)) this.setKnownFeatureFlagDetails({\n flags: {}\n });\n } else this.reloadFeatureFlags();\n });\n }\n async _shutdown(shutdownTimeoutMs = 30000) {\n try {\n return await super._shutdown(shutdownTimeoutMs);\n } finally{\n this.flagCallReported = {};\n }\n }\n getCommonEventProperties() {\n const featureFlags = this.getFeatureFlags();\n const featureVariantProperties = {};\n if (featureFlags) for (const [feature, variant] of Object.entries(featureFlags))featureVariantProperties[`$feature/${feature}`] = variant;\n return {\n ...maybeAdd('$active_feature_flags', featureFlags ? Object.keys(featureFlags) : void 0),\n ...featureVariantProperties,\n ...super.getCommonEventProperties()\n };\n }\n enrichProperties(properties) {\n const userProperties = properties || {};\n const enriched = {\n ...this.props,\n ...this.sessionProps,\n ...userProperties,\n ...this.getCommonEventProperties(),\n $session_id: this.getSessionId()\n };\n applyCallerFeatureFlagOverrides(enriched, userProperties);\n return enriched;\n }\n getSessionId() {\n if (!this._isInitialized) return '';\n let sessionId = this.getPersistedProperty(PostHogPersistedProperty.SessionId);\n const sessionLastTimestamp = this.getPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp) || 0;\n const sessionStartTimestamp = this.getPersistedProperty(PostHogPersistedProperty.SessionStartTimestamp) || 0;\n const now = Date.now();\n const sessionLastDif = now - sessionLastTimestamp;\n const sessionStartDif = now - sessionStartTimestamp;\n if (!sessionId || sessionLastDif > 1000 * this._sessionExpirationTimeSeconds || sessionStartDif > 1000 * this._sessionMaxLengthSeconds) {\n sessionId = uuidv7();\n this.setPersistedProperty(PostHogPersistedProperty.SessionId, sessionId);\n this.setPersistedProperty(PostHogPersistedProperty.SessionStartTimestamp, now);\n }\n this.setPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp, now);\n return sessionId;\n }\n resetSessionId() {\n this.wrap(()=>{\n this.setPersistedProperty(PostHogPersistedProperty.SessionId, null);\n this.setPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp, null);\n this.setPersistedProperty(PostHogPersistedProperty.SessionStartTimestamp, null);\n });\n }\n getAnonymousId() {\n if (!this._isInitialized) return '';\n let anonId = this.getPersistedProperty(PostHogPersistedProperty.AnonymousId);\n if (!anonId) {\n anonId = uuidv7();\n this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, anonId);\n }\n return anonId;\n }\n getDistinctId() {\n if (!this._isInitialized) return '';\n return this.getPersistedProperty(PostHogPersistedProperty.DistinctId) || this.getAnonymousId();\n }\n registerForSession(properties) {\n this.sessionProps = {\n ...this.sessionProps,\n ...properties\n };\n }\n unregisterForSession(property) {\n delete this.sessionProps[property];\n }\n identify(distinctId, properties, options) {\n this.wrap(()=>{\n if (!this._requirePersonProcessing('posthog.identify')) return;\n const previousDistinctId = this.getDistinctId();\n distinctId = distinctId || previousDistinctId;\n if (properties?.$groups) this.groups(properties.$groups);\n const userPropsOnce = properties?.$set_once;\n delete properties?.$set_once;\n const userProps = properties?.$set || properties;\n const allProperties = this.enrichProperties({\n $anon_distinct_id: this.getAnonymousId(),\n ...maybeAdd('$set', userProps),\n ...maybeAdd('$set_once', userPropsOnce)\n });\n const userPropsObj = isObject(userProps) ? userProps : void 0;\n const userPropsOnceObj = isObject(userPropsOnce) ? userPropsOnce : void 0;\n if (distinctId !== previousDistinctId) {\n this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, previousDistinctId);\n this.setPersistedProperty(PostHogPersistedProperty.DistinctId, distinctId);\n this.setPersistedProperty(PostHogPersistedProperty.PersonMode, 'identified');\n this.reloadFeatureFlags();\n super.identifyStateless(distinctId, allProperties, options);\n this._cachedPersonProperties = getPersonPropertiesHash(distinctId, userPropsObj, userPropsOnceObj);\n } else if (userPropsObj || userPropsOnceObj) this.setPersonProperties(userPropsObj, userPropsOnceObj);\n });\n }\n capture(event, properties, options) {\n if ('$exception' === event && !options?._originatedFromCaptureException) this._logger.warn(\"Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically.\");\n this.wrap(()=>{\n const distinctId = this.getDistinctId();\n if (properties?.$groups) this.groups(properties.$groups);\n const allProperties = this.enrichProperties(properties);\n const hasPersonProcessing = this._hasPersonProcessing();\n allProperties['$process_person_profile'] = hasPersonProcessing;\n allProperties['$is_identified'] = this._isIdentified();\n if (hasPersonProcessing) this._requirePersonProcessing('capture');\n super.captureStateless(distinctId, event, allProperties, options);\n });\n }\n alias(alias) {\n this.wrap(()=>{\n if (!this._requirePersonProcessing('posthog.alias')) return;\n const distinctId = this.getDistinctId();\n const allProperties = this.enrichProperties({});\n super.aliasStateless(alias, distinctId, allProperties);\n });\n }\n autocapture(eventType, elements, properties = {}, options) {\n this.wrap(()=>{\n const distinctId = this.getDistinctId();\n const payload = {\n distinct_id: distinctId,\n event: '$autocapture',\n properties: {\n ...this.enrichProperties(properties),\n $event_type: eventType,\n $elements: elements\n }\n };\n this.enqueue('autocapture', payload, options);\n });\n }\n groups(groups) {\n this.wrap(()=>{\n if (!this._requirePersonProcessing('posthog.group')) return;\n const existingGroups = this.props.$groups || {};\n this.register({\n $groups: {\n ...existingGroups,\n ...groups\n }\n });\n if (Object.keys(groups).find((type)=>existingGroups[type] !== groups[type])) this.reloadFeatureFlags();\n });\n }\n group(groupType, groupKey, groupProperties, options) {\n this.wrap(()=>{\n const existingGroups = this.props.$groups || {};\n const isNewGroup = existingGroups[groupType] !== groupKey;\n this.groups({\n [groupType]: groupKey\n });\n if (isNewGroup || groupProperties) this.groupIdentify(groupType, groupKey, groupProperties, options);\n });\n }\n groupIdentify(groupType, groupKey, groupProperties, options) {\n this.wrap(()=>{\n if (!this._requirePersonProcessing('posthog.groupIdentify')) return;\n const distinctId = this.getDistinctId();\n const eventProperties = this.enrichProperties({});\n super.groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties);\n });\n }\n setPersonPropertiesForFlags(properties, reloadFeatureFlags = true) {\n this.wrap(()=>{\n const existingProperties = this.getPersistedProperty(PostHogPersistedProperty.PersonProperties) || {};\n const propsToSet = properties?.['$set'] || (properties?.['$set_once'] ? {} : properties);\n const propsToSetOnce = properties?.['$set_once'];\n const setOnceProps = {};\n if (propsToSetOnce) {\n for(const key in propsToSetOnce)if (Object.prototype.hasOwnProperty.call(propsToSetOnce, key)) {\n if (!(key in existingProperties)) setOnceProps[key] = propsToSetOnce[key];\n }\n }\n this.setPersistedProperty(PostHogPersistedProperty.PersonProperties, {\n ...existingProperties,\n ...setOnceProps,\n ...propsToSet\n });\n if (reloadFeatureFlags) this.reloadFeatureFlags();\n });\n }\n resetPersonPropertiesForFlags() {\n this.wrap(()=>{\n this.setPersistedProperty(PostHogPersistedProperty.PersonProperties, null);\n });\n }\n setGroupPropertiesForFlags(properties) {\n this.wrap(()=>{\n const existingProperties = this.getPersistedProperty(PostHogPersistedProperty.GroupProperties) || {};\n if (0 !== Object.keys(existingProperties).length) Object.keys(existingProperties).forEach((groupType)=>{\n existingProperties[groupType] = {\n ...existingProperties[groupType],\n ...properties[groupType]\n };\n delete properties[groupType];\n });\n this.setPersistedProperty(PostHogPersistedProperty.GroupProperties, {\n ...existingProperties,\n ...properties\n });\n });\n }\n resetGroupPropertiesForFlags() {\n this.wrap(()=>{\n this.setPersistedProperty(PostHogPersistedProperty.GroupProperties, null);\n });\n }\n async remoteConfigAsync() {\n await this._initPromise;\n if (this.disabled) return;\n if (this._remoteConfigResponsePromise) return this._remoteConfigResponsePromise;\n return this._remoteConfigAsync();\n }\n async flagsAsync(options) {\n const { sendAnonDistinctId = true, fetchConfig = false, triggerOnRemoteConfig = false } = options ?? {};\n await this._initPromise;\n if (this.disabled) return;\n if (this.disableRemoteFeatureFlags && !fetchConfig) return void this._logger.info('Feature flags are disabled (disableRemoteFeatureFlags), skipping reload.');\n if (this._flagsResponsePromise) {\n this._logger.info('Feature flags are being loaded already, queuing reload.');\n if (this._pendingFlagsRequest) this._flagsResponsePromise.then(this._pendingFlagsRequest.resolve).catch(this._pendingFlagsRequest.reject);\n return new Promise((resolve, reject)=>{\n this._pendingFlagsRequest = {\n sendAnonDistinctId,\n fetchConfig,\n triggerOnRemoteConfig,\n resolve,\n reject\n };\n });\n }\n return this._flagsAsync({\n sendAnonDistinctId,\n fetchConfig,\n triggerOnRemoteConfig\n });\n }\n onRemoteConfig(_response) {}\n maybeNotifyRemoteConfig(shouldTrigger, response) {\n if (shouldTrigger) try {\n this.onRemoteConfig(response);\n } catch (e) {\n this._logger.error('Error in onRemoteConfig callback:', e);\n }\n }\n cacheSessionReplay(source, response) {\n const sessionReplay = response?.sessionRecording;\n if (sessionReplay) {\n this.setPersistedProperty(PostHogPersistedProperty.SessionReplay, sessionReplay);\n this._logger.info(`Session replay config from ${source}: `, JSON.stringify(sessionReplay));\n } else if ('boolean' == typeof sessionReplay && false === sessionReplay) {\n this._logger.info(`Session replay config from ${source} disabled.`);\n this.setPersistedProperty(PostHogPersistedProperty.SessionReplay, null);\n }\n }\n async _remoteConfigAsync() {\n this._remoteConfigResponsePromise = this._initPromise.then(()=>{\n let remoteConfig = this.getPersistedProperty(PostHogPersistedProperty.RemoteConfig);\n this._logger.info('Cached remote config: ', JSON.stringify(remoteConfig));\n return super.getRemoteConfig().then((response)=>{\n if (response) {\n const remoteConfigWithoutSurveys = {\n ...response\n };\n delete remoteConfigWithoutSurveys.surveys;\n this._logger.info('Fetched remote config: ', JSON.stringify(remoteConfigWithoutSurveys));\n if (false === this.disableSurveys) {\n const surveys = response.surveys;\n let hasSurveys = true;\n if (Array.isArray(surveys)) this._logger.info('Surveys fetched from remote config: ', JSON.stringify(surveys));\n else {\n this._logger.info('There are no surveys.');\n hasSurveys = false;\n }\n if (hasSurveys) this.setPersistedProperty(PostHogPersistedProperty.Surveys, surveys);\n else this.setPersistedProperty(PostHogPersistedProperty.Surveys, null);\n } else this.setPersistedProperty(PostHogPersistedProperty.Surveys, null);\n this.setPersistedProperty(PostHogPersistedProperty.RemoteConfig, remoteConfigWithoutSurveys);\n this.cacheSessionReplay('remote config', response);\n let willLoadFlags = false;\n if (false === response.hasFeatureFlags) {\n if (!this.disableRemoteFeatureFlags) this.setKnownFeatureFlagDetails({\n flags: {}\n });\n this._logger.warn('Remote config has no feature flags, will not load feature flags.');\n } else if (false !== this.preloadFeatureFlags && !this.disableRemoteFeatureFlags) {\n willLoadFlags = true;\n this.flagsAsync({\n sendAnonDistinctId: true,\n fetchConfig: true,\n triggerOnRemoteConfig: true\n });\n }\n if (!response.supportedCompression?.includes(Compression.GZipJS)) this.disableCompression = true;\n this.maybeNotifyRemoteConfig(!willLoadFlags, response);\n remoteConfig = response;\n }\n return remoteConfig;\n });\n }).finally(()=>{\n this._remoteConfigResponsePromise = void 0;\n });\n return this._remoteConfigResponsePromise;\n }\n async _flagsAsync(options) {\n const sendAnonDistinctId = options?.sendAnonDistinctId ?? true;\n const fetchConfig = options?.fetchConfig ?? false;\n const triggerOnRemoteConfig = options?.triggerOnRemoteConfig ?? false;\n this._flagsResponsePromise = this._initPromise.then(async ()=>{\n const distinctId = this.getDistinctId();\n const groups = this.props.$groups || {};\n const personProperties = this.getPersistedProperty(PostHogPersistedProperty.PersonProperties) || {};\n const groupProperties = this.getPersistedProperty(PostHogPersistedProperty.GroupProperties) || {};\n const deviceId = this.getPersistedProperty(PostHogPersistedProperty.DeviceId);\n const extraProperties = {\n $anon_distinct_id: sendAnonDistinctId ? this.getAnonymousId() : void 0,\n $device_id: deviceId ?? void 0,\n ...this.disableRemoteFeatureFlags ? {\n disable_flags: true\n } : {}\n };\n const result = await super.getFlags(distinctId, groups, personProperties, groupProperties, extraProperties, fetchConfig);\n if (!result.success) {\n if (!this.disableRemoteFeatureFlags) this.setKnownFeatureFlagDetails({\n flags: this.getKnownFeatureFlagDetails()?.flags ?? {},\n requestError: result.error,\n minimalFlagCalledEvents: this.getStoredFlagDetails()?.minimalFlagCalledEvents\n });\n return;\n }\n const res = result.response;\n if (res?.quotaLimited?.includes(QuotaLimitedFeature.FeatureFlags)) {\n if (!this.disableRemoteFeatureFlags) this.setKnownFeatureFlagDetails({\n flags: this.getKnownFeatureFlagDetails()?.flags ?? {},\n quotaLimited: res.quotaLimited,\n minimalFlagCalledEvents: this.getStoredFlagDetails()?.minimalFlagCalledEvents\n });\n this._logger.warn('[FEATURE FLAGS] Feature flags quota limit exceeded. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts');\n this.maybeNotifyRemoteConfig(triggerOnRemoteConfig, res);\n return res;\n }\n if (res?.featureFlags) {\n if (this.disableRemoteFeatureFlags) {\n this.cacheSessionReplay('flags', res);\n this.maybeNotifyRemoteConfig(triggerOnRemoteConfig, res);\n return res;\n }\n let newFeatureFlagDetails = res;\n if (res.errorsWhileComputingFlags) {\n const currentFlagDetails = this.getKnownFeatureFlagDetails();\n this._logger.info('Cached feature flags: ', JSON.stringify(currentFlagDetails));\n const filteredFlags = {};\n for(const key in res.flags)if (!res.flags[key].failed) filteredFlags[key] = res.flags[key];\n newFeatureFlagDetails = {\n ...res,\n flags: {\n ...currentFlagDetails?.flags,\n ...filteredFlags\n }\n };\n }\n this.cacheSessionReplay('flags', res);\n this.setKnownFeatureFlagDetails({\n flags: newFeatureFlagDetails.flags,\n requestId: res.requestId,\n evaluatedAt: res.evaluatedAt,\n errorsWhileComputingFlags: res.errorsWhileComputingFlags,\n quotaLimited: res.quotaLimited,\n minimalFlagCalledEvents: true === res.minimalFlagCalledEvents\n });\n this.setPersistedProperty(PostHogPersistedProperty.FlagsEndpointWasHit, true);\n this.maybeNotifyRemoteConfig(triggerOnRemoteConfig, res);\n }\n return res;\n }).finally(()=>{\n this._flagsResponsePromise = void 0;\n const pendingRequest = this._pendingFlagsRequest;\n if (pendingRequest) {\n this._pendingFlagsRequest = void 0;\n this._logger.info('Executing pending feature flags reload.');\n this.flagsAsync({\n sendAnonDistinctId: pendingRequest.sendAnonDistinctId,\n fetchConfig: pendingRequest.fetchConfig,\n triggerOnRemoteConfig: pendingRequest.triggerOnRemoteConfig\n }).then(pendingRequest.resolve).catch(pendingRequest.reject);\n }\n });\n return this._flagsResponsePromise;\n }\n setKnownFeatureFlagDetails(flagsResponse) {\n this.wrap(()=>{\n this.setPersistedProperty(PostHogPersistedProperty.FeatureFlagDetails, flagsResponse);\n this._events.emit('featureflags', getFlagValuesFromFlags(flagsResponse?.flags ?? {}));\n });\n }\n getKnownFeatureFlagDetails() {\n const storedDetails = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlagDetails);\n if (!storedDetails) {\n const featureFlags = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlags);\n const featureFlagPayloads = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlagPayloads);\n if (void 0 === featureFlags && void 0 === featureFlagPayloads) return;\n return createFlagsResponseFromFlagsAndPayloads(featureFlags ?? {}, featureFlagPayloads ?? {});\n }\n return normalizeFlagsResponse(storedDetails);\n }\n getStoredFlagDetails() {\n return this.getPersistedProperty(PostHogPersistedProperty.FeatureFlagDetails);\n }\n isMinimalFlagCalledEventsEnabled() {\n return this.getStoredFlagDetails()?.minimalFlagCalledEvents === true;\n }\n getKnownFeatureFlags() {\n const featureFlagDetails = this.getKnownFeatureFlagDetails();\n if (!featureFlagDetails) return;\n return getFlagValuesFromFlags(featureFlagDetails.flags);\n }\n getBootstrappedFeatureFlagDetails() {\n const details = this.getPersistedProperty(PostHogPersistedProperty.BootstrapFeatureFlagDetails);\n if (!details) return;\n return details;\n }\n setBootstrappedFeatureFlagDetails(details) {\n this.setPersistedProperty(PostHogPersistedProperty.BootstrapFeatureFlagDetails, details);\n }\n getBootstrappedFeatureFlags() {\n const details = this.getBootstrappedFeatureFlagDetails();\n if (!details) return;\n return getFlagValuesFromFlags(details.flags);\n }\n getBootstrappedFeatureFlagPayloads() {\n const details = this.getBootstrappedFeatureFlagDetails();\n if (!details) return;\n return getPayloadsFromFlags(details.flags);\n }\n getFeatureFlagResult(key, options) {\n return this._getFeatureFlagResult(key, options);\n }\n getAllFeatureFlags() {\n return flagDetailsToResults(this.getFeatureFlagDetails()?.flags ?? {});\n }\n _getFeatureFlagResult(key, options = {}) {\n const storedDetails = this.getStoredFlagDetails();\n const details = this.getFeatureFlagDetails();\n const isQuotaLimited = storedDetails?.quotaLimited?.includes(QuotaLimitedFeature.FeatureFlags);\n const featureFlag = details?.flags[key];\n const flagValue = getFeatureFlagValue(featureFlag);\n const sendEvent = (options.sendEvent ?? this.sendFeatureFlagEvent) && !this.flagCallReported[key]?.has(flagValue);\n if (sendEvent) {\n const errors = [];\n if (storedDetails?.requestError) {\n const { type, statusCode } = storedDetails.requestError;\n if ('timeout' === type) errors.push(FeatureFlagError.TIMEOUT);\n else if ('api_error' === type && void 0 !== statusCode) errors.push(FeatureFlagError.apiError(statusCode));\n else if ('connection_error' === type) errors.push(FeatureFlagError.CONNECTION_ERROR);\n else errors.push(FeatureFlagError.UNKNOWN_ERROR);\n } else if (storedDetails) {\n if (storedDetails.errorsWhileComputingFlags) errors.push(FeatureFlagError.ERRORS_WHILE_COMPUTING);\n if (isQuotaLimited) errors.push(FeatureFlagError.QUOTA_LIMITED);\n else if (void 0 === flagValue && !featureFlag) errors.push(FeatureFlagError.FLAG_MISSING);\n }\n const bootstrappedResponse = this.getBootstrappedFeatureFlags()?.[key];\n const bootstrappedPayload = this.getBootstrappedFeatureFlagPayloads()?.[key];\n const featureFlagError = errors.length > 0 ? errors.join(',') : void 0;\n this.flagCallReported[key] = this.flagCallReported[key] ?? new Set();\n this.flagCallReported[key].add(flagValue);\n const properties = {\n $feature_flag: key,\n $feature_flag_response: flagValue,\n ...maybeAdd('$feature_flag_id', featureFlag?.metadata?.id),\n ...maybeAdd('$feature_flag_version', featureFlag?.metadata?.version),\n ...maybeAdd('$feature_flag_reason', featureFlag?.reason?.description ?? featureFlag?.reason?.code),\n ...maybeAdd('$feature_flag_bootstrapped_response', bootstrappedResponse),\n ...maybeAdd('$feature_flag_bootstrapped_payload', bootstrappedPayload),\n $used_bootstrap_value: !this.getPersistedProperty(PostHogPersistedProperty.FlagsEndpointWasHit),\n ...maybeAdd('$feature_flag_request_id', details?.requestId),\n ...maybeAdd('$feature_flag_evaluated_at', details?.evaluatedAt),\n ...maybeAdd('$feature_flag_error', featureFlagError),\n ...maybeAdd('$feature_flag_has_experiment', featureFlag?.metadata?.has_experiment)\n };\n this.capture('$feature_flag_called', properties);\n }\n if (void 0 === flagValue) switch(options.missingFlagBehavior){\n case 'getFeatureFlagPayload':\n return details ? {\n key,\n enabled: false,\n payload: null\n } : void 0;\n case 'getFeatureFlag':\n return details && Object.keys(details.flags).length ? {\n key,\n enabled: false,\n payload: null\n } : void 0;\n case void 0:\n return;\n }\n const rawPayload = featureFlag?.metadata?.payload;\n const payload = void 0 !== rawPayload ? parsePayload(rawPayload) : null;\n return {\n key,\n enabled: getEnabledFromValue(flagValue),\n variant: getVariantFromValue(flagValue),\n payload\n };\n }\n getFeatureFlag(key, options) {\n const result = this._getFeatureFlagResult(key, {\n missingFlagBehavior: 'getFeatureFlag',\n sendEvent: options?.sendEvent\n });\n return result?.variant ?? result?.enabled;\n }\n getFeatureFlagPayload(key) {\n const result = this._getFeatureFlagResult(key, {\n missingFlagBehavior: 'getFeatureFlagPayload',\n sendEvent: false\n });\n return result?.payload;\n }\n getFeatureFlagPayloads() {\n return this.getFeatureFlagDetails()?.featureFlagPayloads;\n }\n getFeatureFlags() {\n return this.getFeatureFlagDetails()?.featureFlags;\n }\n getFeatureFlagDetails() {\n let details = this.getKnownFeatureFlagDetails();\n const overriddenFlags = this.getPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags);\n if (!overriddenFlags) return details;\n details = details ?? {\n featureFlags: {},\n featureFlagPayloads: {},\n flags: {}\n };\n const flags = {\n ...details.flags ?? {}\n };\n for(const key in overriddenFlags)if (overriddenFlags[key]) flags[key] = updateFlagValue(flags[key], overriddenFlags[key]);\n else delete flags[key];\n const result = {\n ...details,\n flags\n };\n return normalizeFlagsResponse(result);\n }\n getFeatureFlagsAndPayloads() {\n const flags = this.getFeatureFlags();\n const payloads = this.getFeatureFlagPayloads();\n return {\n flags,\n payloads\n };\n }\n isFeatureEnabled(key, options) {\n if (options?.defaultValue === void 0) {\n const response = this.getFeatureFlag(key, options);\n return void 0 === response ? void 0 : !!response;\n }\n const result = this._getFeatureFlagResult(key, {\n sendEvent: options.sendEvent\n });\n const value = result?.variant ?? result?.enabled;\n return void 0 === value ? options.defaultValue : !!value;\n }\n reloadFeatureFlags(options) {\n if (this.disableRemoteFeatureFlags && !this.disabled) return void this._initPromise.then(()=>options?.cb?.(void 0, this.getFeatureFlags()));\n this.flagsAsync({\n sendAnonDistinctId: true\n }).then((res)=>{\n options?.cb?.(void 0, res?.featureFlags);\n }).catch((e)=>{\n options?.cb?.(e, void 0);\n if (!options?.cb) this._logger.info('Error reloading feature flags', e);\n });\n }\n async reloadRemoteConfigAsync() {\n return await this.remoteConfigAsync();\n }\n async reloadFeatureFlagsAsync(sendAnonDistinctId) {\n if (this.disableRemoteFeatureFlags && !this.disabled) {\n await this._initPromise;\n return this.getFeatureFlags();\n }\n return (await this.flagsAsync({\n sendAnonDistinctId: sendAnonDistinctId\n }))?.featureFlags;\n }\n onFeatureFlags(cb) {\n return this.on('featureflags', async ()=>{\n const flags = this.getFeatureFlags();\n if (flags) cb(flags);\n });\n }\n onFeatureFlag(key, cb) {\n return this.on('featureflags', async ()=>{\n const flagResponse = this.getFeatureFlag(key);\n if (void 0 !== flagResponse) cb(flagResponse);\n });\n }\n async overrideFeatureFlag(flags) {\n this.wrap(()=>{\n if (null === flags) return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, null);\n return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, flags);\n });\n }\n updateFlags(flags, payloads, options) {\n this.wrap(()=>{\n const existingDetails = options?.merge ? this.getKnownFeatureFlagDetails()?.flags : void 0;\n const existingFlags = existingDetails ? getFlagValuesFromFlags(existingDetails) : {};\n const existingPayloads = {};\n for(const key in existingDetails){\n const storedPayload = existingDetails[key].metadata?.payload;\n if (void 0 !== storedPayload) existingPayloads[key] = parsePayload(storedPayload);\n }\n const finalFlags = {\n ...existingFlags,\n ...flags\n };\n const finalPayloads = {\n ...existingPayloads,\n ...payloads ?? {}\n };\n const flagDetails = {};\n for (const [key, value] of Object.entries(finalFlags)){\n const payload = finalPayloads[key];\n let serializedPayload;\n if (void 0 !== payload) try {\n serializedPayload = JSON.stringify(payload);\n } catch (e) {\n this._logger.error(`updateFlags: could not serialize the payload for flag \"${key}\", dropping it.`, e);\n }\n flagDetails[key] = {\n key,\n enabled: getEnabledFromValue(value),\n variant: getVariantFromValue(value),\n reason: void 0,\n metadata: {\n id: void 0,\n version: void 0,\n description: void 0,\n payload: serializedPayload\n }\n };\n }\n this.setKnownFeatureFlagDetails({\n flags: flagDetails\n });\n });\n }\n captureException(error, additionalProperties, hint) {\n try {\n const exceptionProperties = this.getErrorPropertiesBuilder().buildFromUnknown(error, hint);\n this.capture('$exception', {\n ...exceptionProperties,\n ...additionalProperties\n }, {\n _originatedFromCaptureException: true\n });\n } catch (e) {\n this._logger.error('Error while capturing $exception:', e);\n }\n }\n captureTraceFeedback(traceId, userFeedback) {\n this.capture('$ai_feedback', {\n $ai_feedback_text: userFeedback,\n $ai_trace_id: String(traceId)\n });\n }\n captureTraceMetric(traceId, metricName, metricValue) {\n this.capture('$ai_metric', {\n $ai_metric_name: metricName,\n $ai_metric_value: String(metricValue),\n $ai_trace_id: String(traceId)\n });\n }\n _isIdentified() {\n const personMode = this.getPersistedProperty(PostHogPersistedProperty.PersonMode);\n if ('identified' === personMode) return true;\n if (void 0 === personMode) {\n const distinctId = this.getPersistedProperty(PostHogPersistedProperty.DistinctId);\n const anonymousId = this.getPersistedProperty(PostHogPersistedProperty.AnonymousId);\n if (distinctId && anonymousId && distinctId !== anonymousId) return true;\n }\n return false;\n }\n _getGroups() {\n return this.props.$groups || {};\n }\n _hasPersonProcessing() {\n if ('always' === this._personProfiles) return true;\n if ('never' === this._personProfiles) return false;\n const isIdentified = this._isIdentified();\n const hasGroups = Object.keys(this._getGroups()).length > 0;\n const personProcessingEnabled = true === this.getPersistedProperty(PostHogPersistedProperty.EnablePersonProcessing);\n return isIdentified || hasGroups || personProcessingEnabled;\n }\n _requirePersonProcessing(functionName) {\n if ('never' === this._personProfiles) {\n this._logger.error(`${functionName} was called, but personProfiles is set to \"never\". This call will be ignored.`);\n return false;\n }\n this.setPersistedProperty(PostHogPersistedProperty.EnablePersonProcessing, true);\n return true;\n }\n createPersonProfile() {\n if (this._hasPersonProcessing()) return;\n if (!this._requirePersonProcessing('posthog.createPersonProfile')) return;\n this.capture('$set', {\n $set: {},\n $set_once: {}\n });\n }\n setPersonProperties(userPropertiesToSet, userPropertiesToSetOnce, reloadFeatureFlags = true) {\n this.wrap(()=>{\n const isSetEmpty = isNullish(userPropertiesToSet) || isEmptyObject(userPropertiesToSet);\n const isSetOnceEmpty = isNullish(userPropertiesToSetOnce) || isEmptyObject(userPropertiesToSetOnce);\n if (isSetEmpty && isSetOnceEmpty) return;\n if (!this._requirePersonProcessing('posthog.setPersonProperties')) return;\n const hash = getPersonPropertiesHash(this.getDistinctId(), userPropertiesToSet, userPropertiesToSetOnce);\n if (this._cachedPersonProperties === hash) return void this._logger.info('A duplicate setPersonProperties call was made with the same properties. It has been ignored.');\n this.setPersonPropertiesForFlags({\n $set: userPropertiesToSet || {},\n $set_once: userPropertiesToSetOnce || {}\n }, reloadFeatureFlags);\n this.capture('$set', {\n $set: userPropertiesToSet || {},\n $set_once: userPropertiesToSetOnce || {}\n });\n this._cachedPersonProperties = hash;\n });\n }\n unsetPersonProperties(propertyNames, reloadFeatureFlags = true) {\n this.wrap(()=>{\n const names = (isArray(propertyNames) ? propertyNames : [\n propertyNames\n ]).filter((name)=>isString(name) && name.length > 0);\n if (0 === names.length) return;\n if (!this._requirePersonProcessing('posthog.unsetPersonProperties')) return;\n const existingProperties = this.getPersistedProperty(PostHogPersistedProperty.PersonProperties) || {};\n const nextProperties = {\n ...existingProperties\n };\n for (const name of names)delete nextProperties[name];\n this.setPersistedProperty(PostHogPersistedProperty.PersonProperties, nextProperties);\n if (reloadFeatureFlags) this.reloadFeatureFlags();\n this.capture('$set', {\n $unset: names\n });\n this._cachedPersonProperties = null;\n });\n }\n processBeforeEnqueue(message) {\n if (!this._beforeSend) return message;\n const timestamp = message.timestamp;\n const props = message.properties || {};\n const captureEvent = {\n uuid: message.uuid,\n event: message.event,\n properties: props,\n $set: props.$set,\n $set_once: props.$set_once,\n timestamp: 'string' == typeof timestamp ? new Date(timestamp) : timestamp\n };\n const result = this._runBeforeSend(captureEvent);\n if (!result) return null;\n const resultProps = {\n ...result.properties ?? props\n };\n if (void 0 !== result.$set) resultProps.$set = result.$set;\n else delete resultProps.$set;\n if (void 0 !== result.$set_once) resultProps.$set_once = result.$set_once;\n else delete resultProps.$set_once;\n return {\n ...message,\n uuid: getEventUuid(result.uuid ?? message.uuid, uuidv7),\n event: result.event,\n properties: resultProps,\n timestamp: result.timestamp\n };\n }\n _runBeforeSend(captureEvent) {\n const beforeSend = this._beforeSend;\n if (!beforeSend) return captureEvent;\n const fns = Array.isArray(beforeSend) ? beforeSend : [\n beforeSend\n ];\n let result = captureEvent;\n for (const fn of fns)try {\n result = fn(result);\n if (!result) {\n this._logger.info(`Event '${captureEvent.event}' was rejected in before_send function`);\n return null;\n }\n } catch (e) {\n this._logger.error(`Error in before_send function for event '${captureEvent.event}':`, e);\n }\n return result;\n }\n}\nexport { PostHogCore };\n","import { isFunction } from \"./utils/type-utils.mjs\";\nconst DISTINCT_ID_HEADER = 'X-POSTHOG-DISTINCT-ID';\nconst SESSION_ID_HEADER = 'X-POSTHOG-SESSION-ID';\nconst PATCH_MARKER = '__posthog_tracing_headers_patched__';\nconst parseHostname = (url)=>{\n try {\n return new URL(url).hostname;\n } catch {\n return;\n }\n};\nconst shouldAddHeaders = (url, hostnames)=>{\n const hostname = parseHostname(url);\n if (!hostname) return false;\n return hostnames.includes(hostname);\n};\nconst patchFetchForTracingHeaders = (client, hostnames)=>{\n const globalAny = globalThis;\n const currentFetch = globalAny.fetch;\n if (!isFunction(currentFetch)) return ()=>{};\n const originalFetch = currentFetch[PATCH_MARKER]?.original ?? currentFetch;\n const wrappedFetch = async function(input, init) {\n try {\n const urlString = 'string' == typeof input ? input : input instanceof URL ? input.toString() : input instanceof Request ? input.url : void 0;\n if (urlString && shouldAddHeaders(urlString, hostnames)) {\n const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : void 0));\n const distinctId = client.getDistinctId();\n const sessionId = client.getSessionId();\n if (distinctId) headers.set(DISTINCT_ID_HEADER, distinctId);\n if (sessionId) headers.set(SESSION_ID_HEADER, sessionId);\n const initWithHeaders = {\n ...init ?? {},\n headers\n };\n return originalFetch.call(globalAny, input, initWithHeaders);\n }\n } catch {}\n return originalFetch.call(globalAny, input, init);\n };\n Object.defineProperty(wrappedFetch, PATCH_MARKER, {\n value: {\n original: originalFetch\n },\n enumerable: false\n });\n globalAny.fetch = wrappedFetch;\n return ()=>{\n if (globalAny.fetch === wrappedFetch) globalAny.fetch = originalFetch;\n };\n};\nexport { patchFetchForTracingHeaders };\n","import { flagDetailsToResults, getEnabledFromValue, getFeatureFlagValue, getVariantFromValue, minimizeFlagCalledEventProperties, parsePayload } from \"./featureFlagUtils.mjs\";\nimport { gzipCompress, isGzipData, isGzipRequest, isGzipSupported, isNativeAsyncGzipError, isNativeAsyncGzipReadError } from \"./gzip.mjs\";\nimport { buildOtlpLogRecord, buildOtlpLogsPayload, buildResourceAttributes, getOtlpSeverityNumber, getOtlpSeverityText, toOtlpAnyValue, toOtlpKeyValueList } from \"./logs/logs-utils.mjs\";\nimport { PostHogLogs } from \"./logs/index.mjs\";\nimport { DEFAULT_HISTOGRAM_BOUNDS, PostHogMetrics, buildMetricsResourceAttributes, buildOtlpMetricsPayload, resolveMetricsConfig } from \"./metrics/index.mjs\";\nimport { uuidv7 } from \"./vendor/uuidv7.mjs\";\nimport { getLengthFromRules, getRequirementsHint, getValidationError } from \"./surveys/validation.mjs\";\nexport * from \"./utils/index.mjs\";\nexport * from \"./cookie.mjs\";\nexport * from \"./posthog-core.mjs\";\nexport * from \"./posthog-core-stateless.mjs\";\nexport * from \"./tracing-headers.mjs\";\nexport * from \"./types.mjs\";\nimport * as __WEBPACK_EXTERNAL_MODULE__error_tracking_index_mjs_b3406d6f__ from \"./error-tracking/index.mjs\";\nexport { DEFAULT_HISTOGRAM_BOUNDS, __WEBPACK_EXTERNAL_MODULE__error_tracking_index_mjs_b3406d6f__ as ErrorTracking, PostHogLogs, PostHogMetrics, buildMetricsResourceAttributes, buildOtlpLogRecord, buildOtlpLogsPayload, buildOtlpMetricsPayload, buildResourceAttributes, flagDetailsToResults, getEnabledFromValue, getFeatureFlagValue, getLengthFromRules, getOtlpSeverityNumber, getOtlpSeverityText, getRequirementsHint, getValidationError, getVariantFromValue, gzipCompress, isGzipData, isGzipRequest, isGzipSupported, isNativeAsyncGzipError, isNativeAsyncGzipReadError, minimizeFlagCalledEventProperties, parsePayload, resolveMetricsConfig, toOtlpAnyValue, toOtlpKeyValueList, uuidv7 };\n","import { ErrorTracking } from \"@posthog/core\";\nimport { createReadStream } from \"node:fs\";\nimport { createInterface } from \"node:readline\";\nconst LRU_FILE_CONTENTS_CACHE = new ErrorTracking.ReduceableCache(25);\nconst LRU_FILE_CONTENTS_FS_READ_FAILED = new ErrorTracking.ReduceableCache(20);\nconst DEFAULT_LINES_OF_CONTEXT = 7;\nconst MAX_CONTEXTLINES_COLNO = 1000;\nconst MAX_CONTEXTLINES_LINENO = 10000;\nasync function addSourceContext(frames) {\n const filesToLines = {};\n for(let i = frames.length - 1; i >= 0; i--){\n const frame = frames[i];\n const filename = frame?.filename;\n if (!frame || 'string' != typeof filename || 'number' != typeof frame.lineno || shouldSkipContextLinesForFile(filename) || shouldSkipContextLinesForFrame(frame)) continue;\n const filesToLinesOutput = filesToLines[filename];\n if (!filesToLinesOutput) filesToLines[filename] = [];\n filesToLines[filename].push(frame.lineno);\n }\n const files = Object.keys(filesToLines);\n if (0 == files.length) return frames;\n const readlinePromises = [];\n for (const file of files){\n if (LRU_FILE_CONTENTS_FS_READ_FAILED.get(file)) continue;\n const filesToLineRanges = filesToLines[file];\n if (!filesToLineRanges) continue;\n filesToLineRanges.sort((a, b)=>a - b);\n const ranges = makeLineReaderRanges(filesToLineRanges);\n if (ranges.every((r)=>rangeExistsInContentCache(file, r))) continue;\n const cache = emplace(LRU_FILE_CONTENTS_CACHE, file, {});\n readlinePromises.push(getContextLinesFromFile(file, ranges, cache));\n }\n await Promise.all(readlinePromises).catch(()=>{});\n if (frames && frames.length > 0) addSourceContextToFrames(frames, LRU_FILE_CONTENTS_CACHE);\n LRU_FILE_CONTENTS_CACHE.reduce();\n return frames;\n}\nfunction getContextLinesFromFile(path, ranges, output) {\n return new Promise((resolve)=>{\n const stream = createReadStream(path);\n const lineReaded = createInterface({\n input: stream\n });\n function destroyStreamAndResolve() {\n stream.destroy();\n resolve();\n }\n let lineNumber = 0;\n let currentRangeIndex = 0;\n const range = ranges[currentRangeIndex];\n if (void 0 === range) return void destroyStreamAndResolve();\n let rangeStart = range[0];\n let rangeEnd = range[1];\n function onStreamError() {\n LRU_FILE_CONTENTS_FS_READ_FAILED.set(path, 1);\n lineReaded.close();\n lineReaded.removeAllListeners();\n destroyStreamAndResolve();\n }\n stream.on('error', onStreamError);\n lineReaded.on('error', onStreamError);\n lineReaded.on('close', destroyStreamAndResolve);\n lineReaded.on('line', (line)=>{\n lineNumber++;\n if (lineNumber < rangeStart) return;\n output[lineNumber] = snipLine(line, 0);\n if (lineNumber >= rangeEnd) {\n if (currentRangeIndex === ranges.length - 1) {\n lineReaded.close();\n lineReaded.removeAllListeners();\n return;\n }\n currentRangeIndex++;\n const range = ranges[currentRangeIndex];\n if (void 0 === range) {\n lineReaded.close();\n lineReaded.removeAllListeners();\n return;\n }\n rangeStart = range[0];\n rangeEnd = range[1];\n }\n });\n });\n}\nfunction addSourceContextToFrames(frames, cache) {\n for (const frame of frames)if (frame.filename && void 0 === frame.context_line && 'number' == typeof frame.lineno) {\n const contents = cache.get(frame.filename);\n if (void 0 === contents) continue;\n addContextToFrame(frame.lineno, frame, contents);\n }\n}\nfunction addContextToFrame(lineno, frame, contents) {\n if (void 0 === frame.lineno || void 0 === contents) return;\n frame.pre_context = [];\n for(let i = makeRangeStart(lineno); i < lineno; i++){\n const line = contents[i];\n if (void 0 === line) return void clearLineContext(frame);\n frame.pre_context.push(line);\n }\n if (void 0 === contents[lineno]) return void clearLineContext(frame);\n frame.context_line = contents[lineno];\n const end = makeRangeEnd(lineno);\n frame.post_context = [];\n for(let i = lineno + 1; i <= end; i++){\n const line = contents[i];\n if (void 0 === line) break;\n frame.post_context.push(line);\n }\n}\nfunction clearLineContext(frame) {\n delete frame.pre_context;\n delete frame.context_line;\n delete frame.post_context;\n}\nfunction shouldSkipContextLinesForFile(path) {\n return path.startsWith('node:') || path.endsWith('.min.js') || path.endsWith('.min.cjs') || path.endsWith('.min.mjs') || path.startsWith('data:');\n}\nfunction shouldSkipContextLinesForFrame(frame) {\n if (void 0 !== frame.lineno && frame.lineno > MAX_CONTEXTLINES_LINENO) return true;\n if (void 0 !== frame.colno && frame.colno > MAX_CONTEXTLINES_COLNO) return true;\n return false;\n}\nfunction rangeExistsInContentCache(file, range) {\n const contents = LRU_FILE_CONTENTS_CACHE.get(file);\n if (void 0 === contents) return false;\n for(let i = range[0]; i <= range[1]; i++)if (void 0 === contents[i]) return false;\n return true;\n}\nfunction makeLineReaderRanges(lines) {\n if (!lines.length) return [];\n let i = 0;\n const line = lines[0];\n if ('number' != typeof line) return [];\n let current = makeContextRange(line);\n const out = [];\n while(true){\n if (i === lines.length - 1) {\n out.push(current);\n break;\n }\n const next = lines[i + 1];\n if ('number' != typeof next) break;\n if (next <= current[1]) current[1] = next + DEFAULT_LINES_OF_CONTEXT;\n else {\n out.push(current);\n current = makeContextRange(next);\n }\n i++;\n }\n return out;\n}\nfunction makeContextRange(line) {\n return [\n makeRangeStart(line),\n makeRangeEnd(line)\n ];\n}\nfunction makeRangeStart(line) {\n return Math.max(1, line - DEFAULT_LINES_OF_CONTEXT);\n}\nfunction makeRangeEnd(line) {\n return line + DEFAULT_LINES_OF_CONTEXT;\n}\nfunction emplace(map, key, contents) {\n const value = map.get(key);\n if (void 0 === value) {\n map.set(key, contents);\n return contents;\n }\n return value;\n}\nfunction snipLine(line, colno) {\n let newLine = line;\n const lineLength = newLine.length;\n if (lineLength <= 150) return newLine;\n if (colno > lineLength) colno = lineLength;\n let start = Math.max(colno - 60, 0);\n if (start < 5) start = 0;\n let end = Math.min(start + 140, lineLength);\n if (end > lineLength - 5) end = lineLength;\n if (end === lineLength) start = Math.max(end - 140, 0);\n newLine = newLine.slice(start, end);\n if (start > 0) newLine = `...${newLine}`;\n if (end < lineLength) newLine += '...';\n return newLine;\n}\nexport { MAX_CONTEXTLINES_COLNO, MAX_CONTEXTLINES_LINENO, addSourceContext };\n","import { isAbsolute, relative, sep } from \"path\";\nfunction createRelativePathModifier(basePath = process.cwd()) {\n const isWindows = '\\\\' === sep;\n const toUnix = (p)=>isWindows ? p.replace(/\\\\/g, '/') : p;\n const normalizedBase = toUnix(basePath);\n return async (frames)=>{\n for (const frame of frames)if (!(!frame.filename || frame.filename.startsWith('node:') || frame.filename.startsWith('data:'))) {\n if (isAbsolute(frame.filename)) frame.filename = toUnix(relative(normalizedBase, toUnix(frame.filename)));\n }\n return frames;\n };\n}\nexport { createRelativePathModifier };\n","const version = '5.46.0';\nexport { version };\n","const FeatureFlagError = {\n ERRORS_WHILE_COMPUTING: 'errors_while_computing_flags',\n FLAG_MISSING: 'flag_missing',\n QUOTA_LIMITED: 'quota_limited',\n UNKNOWN_ERROR: 'unknown_error'\n};\nexport { FeatureFlagError };\n","import { FeatureFlagError } from \"./types.mjs\";\nclass FeatureFlagEvaluations {\n constructor(init){\n this._host = init.host;\n this._distinctId = init.distinctId;\n this._groups = init.groups;\n this._disableGeoip = init.disableGeoip;\n this._flags = init.flags;\n this._requestId = init.requestId;\n this._evaluatedAt = init.evaluatedAt;\n this._flagDefinitionsLoadedAt = init.flagDefinitionsLoadedAt;\n this._errorsWhileComputing = init.errorsWhileComputing ?? false;\n this._quotaLimited = init.quotaLimited ?? false;\n this._accessed = init.accessed ?? new Set();\n this._isSlice = init.isSlice ?? false;\n }\n isEnabled(key) {\n const flag = this._flags[key];\n this._recordAccess(key);\n return flag?.enabled ?? false;\n }\n getFlag(key) {\n const flag = this._flags[key];\n this._recordAccess(key);\n if (!flag) return;\n if (!flag.enabled) return false;\n return flag.variant ?? true;\n }\n getFlagPayload(key) {\n return this._flags[key]?.payload;\n }\n onlyAccessed() {\n const filtered = {};\n for (const key of this._accessed){\n const flag = this._flags[key];\n if (flag) filtered[key] = flag;\n }\n return this._cloneWith(filtered);\n }\n only(keys) {\n const filtered = {};\n const missing = [];\n for (const key of keys){\n const flag = this._flags[key];\n if (flag) filtered[key] = flag;\n else missing.push(key);\n }\n if (missing.length > 0) this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${missing.join(', ')}`);\n return this._cloneWith(filtered);\n }\n get keys() {\n return Object.keys(this._flags);\n }\n _getEventProperties() {\n const properties = {};\n const activeFlags = [];\n for (const [key, flag] of Object.entries(this._flags)){\n const value = false === flag.enabled ? false : flag.variant ?? true;\n properties[`$feature/${key}`] = value;\n if (flag.enabled) activeFlags.push(key);\n }\n if (activeFlags.length > 0) {\n activeFlags.sort();\n properties['$active_feature_flags'] = activeFlags;\n }\n return properties;\n }\n _cloneWith(flags) {\n return new FeatureFlagEvaluations({\n host: this._host,\n distinctId: this._distinctId,\n groups: this._groups,\n disableGeoip: this._disableGeoip,\n flags,\n requestId: this._requestId,\n evaluatedAt: this._evaluatedAt,\n flagDefinitionsLoadedAt: this._flagDefinitionsLoadedAt,\n errorsWhileComputing: this._errorsWhileComputing,\n quotaLimited: this._quotaLimited,\n accessed: new Set(this._accessed),\n isSlice: true\n });\n }\n _recordAccess(key) {\n this._accessed.add(key);\n if ('' === this._distinctId) return;\n if (this._isSlice && !(key in this._flags)) return;\n const flag = this._flags[key];\n const response = void 0 === flag ? void 0 : false === flag.enabled ? false : flag.variant ?? true;\n const properties = {\n $feature_flag: key,\n $feature_flag_response: response,\n $feature_flag_id: flag?.id,\n $feature_flag_version: flag?.version,\n $feature_flag_reason: flag?.reason,\n locally_evaluated: flag?.locallyEvaluated ?? false,\n [`$feature/${key}`]: response,\n $feature_flag_request_id: this._requestId,\n $feature_flag_evaluated_at: flag?.locallyEvaluated ? Date.now() : this._evaluatedAt\n };\n if (flag?.hasExperiment !== void 0) properties.$feature_flag_has_experiment = flag.hasExperiment;\n if (flag?.locallyEvaluated && void 0 !== this._flagDefinitionsLoadedAt) properties.$feature_flag_definitions_loaded_at = this._flagDefinitionsLoadedAt;\n const errors = [];\n if (this._errorsWhileComputing) errors.push(FeatureFlagError.ERRORS_WHILE_COMPUTING);\n if (this._quotaLimited) errors.push(FeatureFlagError.QUOTA_LIMITED);\n if (void 0 === flag) errors.push(FeatureFlagError.FLAG_MISSING);\n if (errors.length > 0) properties.$feature_flag_error = errors.join(',');\n this._host.captureFlagCalledEventIfNeeded({\n distinctId: this._distinctId,\n key,\n response,\n groups: this._groups,\n disableGeoip: this._disableGeoip,\n properties\n });\n }\n}\nexport { FeatureFlagEvaluations };\n","async function hashSHA1(text) {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) throw new Error('SubtleCrypto API not available');\n const hashBuffer = await subtle.digest('SHA-1', new TextEncoder().encode(text));\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n return hashArray.map((byte)=>byte.toString(16).padStart(2, '0')).join('');\n}\nexport { hashSHA1 };\n","import { safeSetTimeout } from \"@posthog/core\";\nimport { hashSHA1 } from \"./crypto.mjs\";\nconst SIXTY_SECONDS = 60000;\nconst LONG_SCALE = 0xfffffffffffffff;\nconst NULL_VALUES_ALLOWED_OPERATORS = [\n 'is_not',\n 'is_set'\n];\nclass ClientError extends Error {\n constructor(message){\n super();\n Error.captureStackTrace(this, this.constructor);\n this.name = 'ClientError';\n this.message = message;\n Object.setPrototypeOf(this, ClientError.prototype);\n }\n}\nfunction setCustomErrorPrototype(error, constructor) {\n error.name = constructor.name;\n Error.captureStackTrace(error, constructor);\n Object.setPrototypeOf(error, constructor.prototype);\n}\nclass InconclusiveMatchError extends Error {\n constructor(message){\n super(message);\n setCustomErrorPrototype(this, InconclusiveMatchError);\n }\n}\nclass RequiresServerEvaluation extends Error {\n constructor(message){\n super(message);\n setCustomErrorPrototype(this, RequiresServerEvaluation);\n }\n}\nclass FeatureFlagsPoller {\n constructor({ pollingInterval, personalApiKey, projectApiKey, timeout, host, customHeaders, ...options }){\n this.debugMode = false;\n this.shouldBeginExponentialBackoff = false;\n this.backOffCount = 0;\n this.pollingInterval = pollingInterval;\n this.personalApiKey = personalApiKey;\n this.featureFlags = [];\n this.featureFlagsByKey = {};\n this.groupTypeMapping = {};\n this.cohorts = {};\n this.loadedSuccessfullyOnce = false;\n this.timeout = timeout;\n this.projectApiKey = projectApiKey;\n this.host = host;\n this.poller = void 0;\n this.fetch = options.fetch || fetch;\n this.onError = options.onError;\n this.customHeaders = customHeaders;\n this.onLoad = options.onLoad;\n this.onMinimalFlagCalledEvents = options.onMinimalFlagCalledEvents;\n this.cacheProvider = options.cacheProvider;\n this.strictLocalEvaluation = options.strictLocalEvaluation ?? false;\n this.loadFeatureFlags();\n }\n debug(enabled = true) {\n this.debugMode = enabled;\n }\n logMsgIfDebug(fn) {\n if (this.debugMode) fn();\n }\n createEvaluationContext(distinctId, groups = {}, personProperties = {}, groupProperties = {}, evaluationCache = {}) {\n return {\n distinctId,\n groups,\n personProperties,\n groupProperties,\n evaluationCache\n };\n }\n async getFeatureFlag(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}) {\n await this.loadFeatureFlags();\n let response;\n let featureFlag;\n if (!this.loadedSuccessfullyOnce) return response;\n featureFlag = this.featureFlagsByKey[key];\n if (void 0 !== featureFlag) {\n const evaluationContext = this.createEvaluationContext(distinctId, groups, personProperties, groupProperties);\n try {\n const result = await this.computeFlagAndPayloadLocally(featureFlag, evaluationContext);\n response = result.value;\n this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${key} -> ${response}`));\n } catch (e) {\n if (e instanceof RequiresServerEvaluation || e instanceof InconclusiveMatchError) this.logMsgIfDebug(()=>console.debug(`${e.name} when computing flag locally: ${key}: ${e.message}`));\n else if (e instanceof Error) this.onError?.(new Error(`Error computing flag locally: ${key}: ${e}`));\n }\n }\n return response;\n }\n async getAllFlagsAndPayloads(evaluationContext, flagKeysToExplicitlyEvaluate) {\n await this.loadFeatureFlags();\n const response = {};\n const payloads = {};\n let fallbackToFlags = 0 == this.featureFlags.length;\n const flagsToEvaluate = flagKeysToExplicitlyEvaluate ? flagKeysToExplicitlyEvaluate.map((key)=>this.featureFlagsByKey[key]).filter(Boolean) : this.featureFlags;\n const sharedEvaluationContext = {\n ...evaluationContext,\n evaluationCache: evaluationContext.evaluationCache ?? {}\n };\n await Promise.all(flagsToEvaluate.map(async (flag)=>{\n try {\n const { value: matchValue, payload: matchPayload } = await this.computeFlagAndPayloadLocally(flag, sharedEvaluationContext);\n response[flag.key] = matchValue;\n if (matchPayload) payloads[flag.key] = matchPayload;\n } catch (e) {\n if (e instanceof RequiresServerEvaluation || e instanceof InconclusiveMatchError) this.logMsgIfDebug(()=>console.debug(`${e.name} when computing flag locally: ${flag.key}: ${e.message}`));\n else if (e instanceof Error) this.onError?.(new Error(`Error computing flag locally: ${flag.key}: ${e}`));\n fallbackToFlags = true;\n }\n }));\n return {\n response,\n payloads,\n fallbackToFlags\n };\n }\n async computeFlagAndPayloadLocally(flag, evaluationContext, options = {}) {\n const { matchValue, skipLoadCheck = false } = options;\n if (!skipLoadCheck) await this.loadFeatureFlags();\n if (!this.loadedSuccessfullyOnce) return {\n value: false,\n payload: null\n };\n let flagValue;\n flagValue = void 0 !== matchValue ? matchValue : await this.computeFlagValueLocally(flag, evaluationContext);\n const payload = this.getFeatureFlagPayload(flag.key, flagValue);\n return {\n value: flagValue,\n payload\n };\n }\n async computeFlagValueLocally(flag, evaluationContext) {\n const { distinctId, groups, personProperties, groupProperties } = evaluationContext;\n if (!flag.active) return false;\n if (flag.ensure_experience_continuity) throw new InconclusiveMatchError('Flag has experience continuity enabled');\n const flagFilters = flag.filters || {};\n const aggregation_group_type_index = flagFilters.aggregation_group_type_index;\n if (void 0 != aggregation_group_type_index) {\n const groupName = this.groupTypeMapping[String(aggregation_group_type_index)];\n if (!groupName) {\n this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${aggregation_group_type_index} for feature flag ${flag.key}`));\n throw new InconclusiveMatchError('Flag has unknown group type index');\n }\n if (!(groupName in groups)) {\n this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${flag.key} without group names passed in`));\n return false;\n }\n if ('device_id' === flag.bucketing_identifier && (personProperties?.$device_id === void 0 || personProperties?.$device_id === null || personProperties?.$device_id === '')) this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${flag.key}`));\n const focusedGroupProperties = groupProperties[groupName];\n return await this.matchFeatureFlagProperties(flag, groups[groupName], focusedGroupProperties, evaluationContext);\n }\n {\n const bucketingValue = this.getBucketingValueForFlag(flag, distinctId, personProperties);\n if (void 0 === bucketingValue) {\n this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${flag.key} without $device_id, falling back to server evaluation`));\n throw new InconclusiveMatchError(`Can't compute feature flag: ${flag.key} without $device_id`);\n }\n return await this.matchFeatureFlagProperties(flag, bucketingValue, personProperties, evaluationContext);\n }\n }\n getBucketingValueForFlag(flag, distinctId, properties) {\n if (flag.filters?.aggregation_group_type_index != void 0) return distinctId;\n if ('device_id' === flag.bucketing_identifier) {\n const deviceId = properties?.$device_id;\n if (null == deviceId || '' === deviceId) return;\n return deviceId;\n }\n return distinctId;\n }\n getFeatureFlagPayload(key, flagValue) {\n let payload = null;\n if (false !== flagValue && null != flagValue) {\n if ('boolean' == typeof flagValue) payload = this.featureFlagsByKey?.[key]?.filters?.payloads?.[flagValue.toString()] || null;\n else if ('string' == typeof flagValue) payload = this.featureFlagsByKey?.[key]?.filters?.payloads?.[flagValue] || null;\n if (null != payload) {\n if ('object' == typeof payload) return payload;\n if ('string' == typeof payload) try {\n return JSON.parse(payload);\n } catch {}\n return payload;\n }\n }\n return null;\n }\n async evaluateFlagDependency(property, properties, evaluationContext) {\n const { evaluationCache } = evaluationContext;\n const targetFlagKey = property.key;\n if (!this.featureFlagsByKey) throw new InconclusiveMatchError('Feature flags not available for dependency evaluation');\n if (!('dependency_chain' in property)) throw new InconclusiveMatchError(`Flag dependency property for '${targetFlagKey}' is missing required 'dependency_chain' field`);\n const dependencyChain = property.dependency_chain;\n if (!Array.isArray(dependencyChain)) throw new InconclusiveMatchError(`Flag dependency property for '${targetFlagKey}' has an invalid 'dependency_chain' (expected array, got ${typeof dependencyChain})`);\n if (0 === dependencyChain.length) throw new InconclusiveMatchError(`Circular dependency detected for flag '${targetFlagKey}' (empty dependency chain)`);\n for (const depFlagKey of dependencyChain){\n if (!(depFlagKey in evaluationCache)) {\n const depFlag = this.featureFlagsByKey[depFlagKey];\n if (depFlag) if (depFlag.active) try {\n const depResult = await this.computeFlagValueLocally(depFlag, evaluationContext);\n evaluationCache[depFlagKey] = depResult;\n } catch (error) {\n throw new InconclusiveMatchError(`Error evaluating flag dependency '${depFlagKey}' for flag '${targetFlagKey}': ${error}`);\n }\n else evaluationCache[depFlagKey] = false;\n else throw new InconclusiveMatchError(`Missing flag dependency '${depFlagKey}' for flag '${targetFlagKey}'`);\n }\n const cachedResult = evaluationCache[depFlagKey];\n if (null == cachedResult) throw new InconclusiveMatchError(`Dependency '${depFlagKey}' could not be evaluated`);\n }\n const targetFlagValue = evaluationCache[targetFlagKey];\n return this.flagEvaluatesToExpectedValue(property.value, targetFlagValue);\n }\n flagEvaluatesToExpectedValue(expectedValue, flagValue) {\n if ('boolean' == typeof expectedValue) return expectedValue === flagValue || 'string' == typeof flagValue && '' !== flagValue && true === expectedValue;\n if ('string' == typeof expectedValue) return flagValue === expectedValue;\n return false;\n }\n async matchFeatureFlagProperties(flag, bucketingValue, properties, evaluationContext) {\n const flagFilters = flag.filters || {};\n const flagConditions = flagFilters.groups || [];\n const flagAggregation = flagFilters.aggregation_group_type_index;\n const earlyExitEnabled = flagFilters.early_exit ?? false;\n const { groups, groupProperties } = evaluationContext;\n let isInconclusive = false;\n let result;\n for (const condition of flagConditions)try {\n const conditionAggregation = void 0 !== condition.aggregation_group_type_index ? condition.aggregation_group_type_index : flagAggregation;\n let effectiveProperties = properties;\n let effectiveBucketingValue = bucketingValue;\n if (conditionAggregation !== flagAggregation) {\n if (null != conditionAggregation) {\n const groupName = this.groupTypeMapping[String(conditionAggregation)];\n if (!groupName || !(groupName in groups)) {\n this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${flag.key}': group type index ${conditionAggregation} not available`));\n continue;\n }\n if (!(groupName in groupProperties)) {\n isInconclusive = true;\n continue;\n }\n effectiveProperties = groupProperties[groupName];\n effectiveBucketingValue = groups[groupName];\n }\n }\n const matchResult = await this.isConditionMatch(flag, effectiveBucketingValue, condition, effectiveProperties, evaluationContext);\n if ('match' === matchResult) {\n const variantOverride = condition.variant;\n const flagVariants = flagFilters.multivariate?.variants || [];\n result = variantOverride && flagVariants.some((variant)=>variant.key === variantOverride) ? variantOverride : await this.getMatchingVariant(flag, effectiveBucketingValue) || true;\n break;\n }\n if (earlyExitEnabled && 'out_of_rollout_bound' === matchResult) return false;\n } catch (e) {\n if (e instanceof RequiresServerEvaluation) throw e;\n if (e instanceof InconclusiveMatchError) isInconclusive = true;\n else throw e;\n }\n if (void 0 !== result) return result;\n if (isInconclusive) throw new InconclusiveMatchError(\"Can't determine if feature flag is enabled or not with given properties\");\n return false;\n }\n async isConditionMatch(flag, bucketingValue, condition, properties, evaluationContext) {\n const rolloutPercentage = condition.rollout_percentage;\n const warnFunction = (msg)=>{\n this.logMsgIfDebug(()=>console.warn(msg));\n };\n if ((condition.properties || []).length > 0) {\n for (const prop of condition.properties){\n const propertyType = prop.type;\n let matches = false;\n if ('cohort' === propertyType) {\n const inCohort = await matchCohort(prop, properties, this.cohorts, this.debugMode, (depProp)=>this.evaluateFlagDependency(depProp, properties, evaluationContext));\n matches = 'not_in' === prop.operator ? !inCohort : inCohort;\n } else matches = 'flag' === propertyType ? await this.evaluateFlagDependency(prop, properties, evaluationContext) : matchProperty(prop, properties, warnFunction);\n if (!matches) return 'no_match';\n }\n if (void 0 == rolloutPercentage) return 'match';\n }\n if (void 0 != rolloutPercentage && await _hash(flag.key, bucketingValue) > rolloutPercentage / 100.0) return 'out_of_rollout_bound';\n return 'match';\n }\n async getMatchingVariant(flag, bucketingValue) {\n const hashValue = await _hash(flag.key, bucketingValue, 'variant');\n const matchingVariant = this.variantLookupTable(flag).find((variant)=>hashValue >= variant.valueMin && hashValue < variant.valueMax);\n if (matchingVariant) return matchingVariant.key;\n }\n variantLookupTable(flag) {\n const lookupTable = [];\n let valueMin = 0;\n let valueMax = 0;\n const flagFilters = flag.filters || {};\n const multivariates = flagFilters.multivariate?.variants || [];\n multivariates.forEach((variant)=>{\n valueMax = valueMin + variant.rollout_percentage / 100.0;\n lookupTable.push({\n valueMin,\n valueMax,\n key: variant.key\n });\n valueMin = valueMax;\n });\n return lookupTable;\n }\n updateFlagState(flagData) {\n this.featureFlags = flagData.flags;\n this.featureFlagsByKey = flagData.flags.reduce((acc, curr)=>(acc[curr.key] = curr, acc), {});\n this.groupTypeMapping = flagData.groupTypeMapping;\n this.cohorts = flagData.cohorts;\n this.loadedSuccessfullyOnce = true;\n this.onMinimalFlagCalledEvents?.(true === flagData.minimalFlagCalledEvents);\n }\n warnAboutExperienceContinuityFlags(flags) {\n if (this.strictLocalEvaluation) return;\n const experienceContinuityFlags = flags.filter((f)=>f.ensure_experience_continuity);\n if (experienceContinuityFlags.length > 0) console.warn(`[PostHog] You are using local evaluation but ${experienceContinuityFlags.length} flag(s) have experience continuity enabled: ${experienceContinuityFlags.map((f)=>f.key).join(', ')}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`);\n }\n async loadFromCache(debugMessage) {\n if (!this.cacheProvider) return false;\n try {\n const cached = await this.cacheProvider.getFlagDefinitions();\n if (cached) {\n this.updateFlagState(cached);\n this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${debugMessage} (${cached.flags.length} flags)`));\n this.onLoad?.(this.featureFlags.length);\n this.warnAboutExperienceContinuityFlags(cached.flags);\n return true;\n }\n return false;\n } catch (err) {\n this.onError?.(new Error(`Failed to load from cache: ${err}`));\n return false;\n }\n }\n async loadFeatureFlags(forceReload = false) {\n if (this.loadedSuccessfullyOnce && !forceReload) return;\n if (!forceReload && this.nextFetchAllowedAt && Date.now() < this.nextFetchAllowedAt) return void this.logMsgIfDebug(()=>console.debug('[FEATURE FLAGS] Skipping fetch, in backoff period'));\n if (!this.loadingPromise) this.loadingPromise = this._loadFeatureFlags().catch((err)=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${err}`))).finally(()=>{\n this.loadingPromise = void 0;\n });\n return this.loadingPromise;\n }\n isLocalEvaluationReady() {\n return (this.loadedSuccessfullyOnce ?? false) && (this.featureFlags?.length ?? 0) > 0;\n }\n getFlagDefinitionsLoadedAt() {\n return this.flagDefinitionsLoadedAt;\n }\n getPollingInterval() {\n if (!this.shouldBeginExponentialBackoff) return this.pollingInterval;\n return Math.min(SIXTY_SECONDS, this.pollingInterval * 2 ** this.backOffCount);\n }\n beginBackoff() {\n this.shouldBeginExponentialBackoff = true;\n this.backOffCount += 1;\n this.nextFetchAllowedAt = Date.now() + this.getPollingInterval();\n }\n clearBackoff() {\n this.shouldBeginExponentialBackoff = false;\n this.backOffCount = 0;\n this.nextFetchAllowedAt = void 0;\n }\n async _loadFeatureFlags() {\n if (this.poller) {\n clearTimeout(this.poller);\n this.poller = void 0;\n }\n this.poller = setTimeout(()=>this.loadFeatureFlags(true), this.getPollingInterval());\n try {\n let shouldFetch = true;\n if (this.cacheProvider) try {\n shouldFetch = await this.cacheProvider.shouldFetchFlagDefinitions();\n } catch (err) {\n this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${err}`));\n }\n if (!shouldFetch) {\n const loaded = await this.loadFromCache('Loaded flags from cache (skipped fetch)');\n if (loaded) return;\n if (this.loadedSuccessfullyOnce) return;\n }\n const res = await this._requestFeatureFlagDefinitions();\n if (!res) return;\n switch(res.status){\n case 304:\n this.logMsgIfDebug(()=>console.debug('[FEATURE FLAGS] Flags not modified (304), using cached data'));\n this.flagsEtag = res.headers?.get('ETag') ?? this.flagsEtag;\n this.loadedSuccessfullyOnce = true;\n this.clearBackoff();\n return;\n case 401:\n this.beginBackoff();\n throw new ClientError(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);\n case 402:\n console.warn('[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts');\n this.featureFlags = [];\n this.featureFlagsByKey = {};\n this.groupTypeMapping = {};\n this.cohorts = {};\n this.onMinimalFlagCalledEvents?.(false);\n return;\n case 403:\n this.beginBackoff();\n throw new ClientError(`Your secret key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);\n case 429:\n this.beginBackoff();\n throw new ClientError(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);\n case 200:\n {\n const responseJson = await res.json() ?? {};\n if (!('flags' in responseJson)) return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(responseJson)}`));\n this.flagsEtag = res.headers?.get('ETag') ?? void 0;\n const flagData = {\n flags: responseJson.flags ?? [],\n groupTypeMapping: responseJson.group_type_mapping || {},\n cohorts: responseJson.cohorts || {},\n minimalFlagCalledEvents: true === responseJson.minimal_flag_called_events\n };\n this.updateFlagState(flagData);\n this.flagDefinitionsLoadedAt = Date.now();\n this.clearBackoff();\n if (this.cacheProvider && shouldFetch) try {\n await this.cacheProvider.onFlagDefinitionsReceived(flagData);\n } catch (err) {\n this.onError?.(new Error(`Failed to store in cache: ${err}`));\n }\n this.onLoad?.(this.featureFlags.length);\n this.warnAboutExperienceContinuityFlags(flagData.flags);\n break;\n }\n default:\n return;\n }\n } catch (err) {\n if (err instanceof ClientError) this.onError?.(err);\n }\n }\n getPersonalApiKeyRequestOptions(method = 'GET', etag) {\n const headers = {\n ...this.customHeaders,\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.personalApiKey}`\n };\n if (etag) headers['If-None-Match'] = etag;\n return {\n method,\n headers\n };\n }\n _requestFeatureFlagDefinitions() {\n const url = `${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`;\n const options = this.getPersonalApiKeyRequestOptions('GET', this.flagsEtag);\n let abortTimeout = null;\n if (this.timeout && 'number' == typeof this.timeout) {\n const controller = new AbortController();\n abortTimeout = safeSetTimeout(()=>{\n controller.abort();\n }, this.timeout);\n options.signal = controller.signal;\n }\n try {\n const fetch1 = this.fetch;\n return fetch1(url, options);\n } finally{\n clearTimeout(abortTimeout);\n }\n }\n async stopPoller(timeoutMs = 30000) {\n clearTimeout(this.poller);\n if (this.cacheProvider) try {\n const shutdownResult = this.cacheProvider.shutdown();\n if (shutdownResult instanceof Promise) await Promise.race([\n shutdownResult,\n new Promise((_, reject)=>setTimeout(()=>reject(new Error(`Cache shutdown timeout after ${timeoutMs}ms`)), timeoutMs))\n ]);\n } catch (err) {\n this.onError?.(new Error(`Error during cache shutdown: ${err}`));\n }\n }\n}\nasync function _hash(key, bucketingValue, salt = '') {\n const hashString = await hashSHA1(`${key}.${bucketingValue}${salt}`);\n return parseInt(hashString.slice(0, 15), 16) / LONG_SCALE;\n}\nfunction matchProperty(property, propertyValues, warnFunction) {\n const key = property.key;\n const value = property.value;\n const operator = property.operator || 'exact';\n if (key in propertyValues) {\n if ('is_not_set' === operator) return false;\n } else {\n if ('is_not_set' === operator) return true;\n throw new InconclusiveMatchError(`Property ${key} not found in propertyValues`);\n }\n const overrideValue = propertyValues[key];\n if (null == overrideValue && !NULL_VALUES_ALLOWED_OPERATORS.includes(operator)) {\n if (warnFunction) warnFunction(`Property ${key} cannot have a value of null/undefined with the ${operator} operator`);\n return false;\n }\n function computeExactMatch(value, overrideValue) {\n if (Array.isArray(value)) return value.map((val)=>String(val).toLowerCase()).includes(String(overrideValue).toLowerCase());\n return String(value).toLowerCase() === String(overrideValue).toLowerCase();\n }\n function compare(lhs, rhs, operator) {\n if ('gt' === operator) return lhs > rhs;\n if ('gte' === operator) return lhs >= rhs;\n if ('lt' === operator) return lhs < rhs;\n if ('lte' === operator) return lhs <= rhs;\n throw new Error(`Invalid operator: ${operator}`);\n }\n switch(operator){\n case 'exact':\n return computeExactMatch(value, overrideValue);\n case 'is_not':\n return !computeExactMatch(value, overrideValue);\n case 'is_set':\n return key in propertyValues;\n case 'icontains':\n return String(overrideValue).toLowerCase().includes(String(value).toLowerCase());\n case 'not_icontains':\n return !String(overrideValue).toLowerCase().includes(String(value).toLowerCase());\n case 'regex':\n return isValidRegex(String(value)) && null !== String(overrideValue).match(String(value));\n case 'not_regex':\n return isValidRegex(String(value)) && null === String(overrideValue).match(String(value));\n case 'gt':\n case 'gte':\n case 'lt':\n case 'lte':\n {\n const parsedValue = 'number' == typeof value ? value : parseFloat(String(value));\n let parsedOverride;\n parsedOverride = 'number' == typeof overrideValue ? overrideValue : null != overrideValue ? parseFloat(String(overrideValue)) : NaN;\n if (Number.isFinite(parsedValue) && Number.isFinite(parsedOverride)) return compare(parsedOverride, parsedValue, operator);\n return compare(String(overrideValue), String(value), operator);\n }\n case 'is_date_after':\n case 'is_date_before':\n {\n if ('boolean' == typeof value) throw new InconclusiveMatchError(\"Date operations cannot be performed on boolean values\");\n let parsedDate = relativeDateParseForFeatureFlagMatching(String(value));\n if (null == parsedDate) parsedDate = convertToDateTime(value);\n if (null == parsedDate) throw new InconclusiveMatchError(`Invalid date: ${value}`);\n const overrideDate = convertToDateTime(overrideValue);\n if ([\n 'is_date_before'\n ].includes(operator)) return overrideDate < parsedDate;\n return overrideDate > parsedDate;\n }\n case 'semver_eq':\n {\n const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));\n return 0 === cmp;\n }\n case 'semver_neq':\n {\n const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));\n return 0 !== cmp;\n }\n case 'semver_gt':\n {\n const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));\n return cmp > 0;\n }\n case 'semver_gte':\n {\n const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));\n return cmp >= 0;\n }\n case 'semver_lt':\n {\n const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));\n return cmp < 0;\n }\n case 'semver_lte':\n {\n const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));\n return cmp <= 0;\n }\n case 'semver_tilde':\n {\n const overrideParsed = parseSemver(String(overrideValue));\n const { lower, upper } = computeTildeBounds(String(value));\n return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;\n }\n case 'semver_caret':\n {\n const overrideParsed = parseSemver(String(overrideValue));\n const { lower, upper } = computeCaretBounds(String(value));\n return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;\n }\n case 'semver_wildcard':\n {\n const overrideParsed = parseSemver(String(overrideValue));\n const { lower, upper } = computeWildcardBounds(String(value));\n return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;\n }\n default:\n throw new InconclusiveMatchError(`Unknown operator: ${operator}`);\n }\n}\nfunction checkCohortExists(cohortId, cohortProperties) {\n if (!(cohortId in cohortProperties)) throw new RequiresServerEvaluation(`cohort ${cohortId} not found in local cohorts - likely a static cohort that requires server evaluation`);\n}\nasync function matchCohort(property, propertyValues, cohortProperties, debugMode = false, flagDependencyEvaluator) {\n const cohortId = String(property.value);\n checkCohortExists(cohortId, cohortProperties);\n const propertyGroup = cohortProperties[cohortId];\n return matchPropertyGroup(propertyGroup, propertyValues, cohortProperties, debugMode, flagDependencyEvaluator);\n}\nasync function matchPropertyGroup(propertyGroup, propertyValues, cohortProperties, debugMode = false, flagDependencyEvaluator) {\n if (!propertyGroup) return true;\n const propertyGroupType = propertyGroup.type;\n const properties = propertyGroup.values;\n if (!properties || 0 === properties.length) return true;\n let errorMatchingLocally = false;\n if ('values' in properties[0]) {\n for (const prop of properties)try {\n const matches = await matchPropertyGroup(prop, propertyValues, cohortProperties, debugMode, flagDependencyEvaluator);\n if ('AND' === propertyGroupType) {\n if (!matches) return false;\n } else if (matches) return true;\n } catch (err) {\n if (err instanceof RequiresServerEvaluation) throw err;\n if (err instanceof InconclusiveMatchError) {\n if (debugMode) console.debug(`Failed to compute property ${prop} locally: ${err}`);\n errorMatchingLocally = true;\n } else throw err;\n }\n if (errorMatchingLocally) throw new InconclusiveMatchError(\"Can't match cohort without a given cohort property value\");\n return 'AND' === propertyGroupType;\n }\n for (const prop of properties)try {\n let matches;\n if ('cohort' === prop.type) matches = await matchCohort(prop, propertyValues, cohortProperties, debugMode, flagDependencyEvaluator);\n else if ('flag' === prop.type) {\n if (!flagDependencyEvaluator) throw new InconclusiveMatchError(`Flag dependency '${prop.key || 'unknown'}' cannot be evaluated without a flag dependency evaluator`);\n matches = await flagDependencyEvaluator(prop);\n } else matches = matchProperty(prop, propertyValues);\n const negation = prop.negation || false;\n if ('AND' === propertyGroupType) {\n if (!matches && !negation) return false;\n if (matches && negation) return false;\n } else {\n if (matches && !negation) return true;\n if (!matches && negation) return true;\n }\n } catch (err) {\n if (err instanceof RequiresServerEvaluation) throw err;\n if (err instanceof InconclusiveMatchError) {\n if (debugMode) console.debug(`Failed to compute property ${prop} locally: ${err}`);\n errorMatchingLocally = true;\n } else throw err;\n }\n if (errorMatchingLocally) throw new InconclusiveMatchError(\"can't match cohort without a given cohort property value\");\n return 'AND' === propertyGroupType;\n}\nfunction isValidRegex(regex) {\n try {\n new RegExp(regex);\n return true;\n } catch (err) {\n return false;\n }\n}\nfunction parseSemverNumericIdentifier(part, raw) {\n if (!/^\\d+$/.test(part)) throw new InconclusiveMatchError(`Invalid semver: ${raw}`);\n if (part.length > 1 && '0' === part[0]) throw new InconclusiveMatchError(`Invalid semver: ${raw}`);\n return parseInt(part, 10);\n}\nfunction parseSemver(value) {\n const text = String(value).trim().replace(/^[vV]/, '');\n const baseVersion = text.split('-')[0].split('+')[0];\n if (!baseVersion || baseVersion.startsWith('.')) throw new InconclusiveMatchError(`Invalid semver: ${value}`);\n const parts = baseVersion.split('.');\n const parsePart = (part)=>{\n if (void 0 === part || '' === part) return 0;\n return parseSemverNumericIdentifier(part, value);\n };\n const major = parsePart(parts[0]);\n const minor = parsePart(parts[1]);\n const patch = parsePart(parts[2]);\n return [\n major,\n minor,\n patch\n ];\n}\nfunction compareSemverTuples(a, b) {\n for(let i = 0; i < 3; i++){\n if (a[i] < b[i]) return -1;\n if (a[i] > b[i]) return 1;\n }\n return 0;\n}\nfunction computeTildeBounds(value) {\n const parsed = parseSemver(value);\n const lower = [\n parsed[0],\n parsed[1],\n parsed[2]\n ];\n const upper = [\n parsed[0],\n parsed[1] + 1,\n 0\n ];\n return {\n lower,\n upper\n };\n}\nfunction computeCaretBounds(value) {\n const parsed = parseSemver(value);\n const [major, minor, patch] = parsed;\n const lower = [\n major,\n minor,\n patch\n ];\n let upper;\n upper = major > 0 ? [\n major + 1,\n 0,\n 0\n ] : minor > 0 ? [\n 0,\n minor + 1,\n 0\n ] : [\n 0,\n 0,\n patch + 1\n ];\n return {\n lower,\n upper\n };\n}\nfunction computeWildcardBounds(value) {\n const text = String(value).trim().replace(/^[vV]/, '');\n const cleanedText = text.replace(/\\.\\*$/, '').replace(/\\*$/, '');\n if (!cleanedText) throw new InconclusiveMatchError(`Invalid wildcard semver: ${value}`);\n const parts = cleanedText.split('.');\n const parseWildcardPart = (part)=>{\n try {\n return parseSemverNumericIdentifier(part, value);\n } catch {\n throw new InconclusiveMatchError(`Invalid wildcard semver: ${value}`);\n }\n };\n const major = parseWildcardPart(parts[0]);\n let lower;\n let upper;\n if (1 === parts.length) {\n lower = [\n major,\n 0,\n 0\n ];\n upper = [\n major + 1,\n 0,\n 0\n ];\n } else {\n const minor = parseWildcardPart(parts[1]);\n lower = [\n major,\n minor,\n 0\n ];\n upper = [\n major,\n minor + 1,\n 0\n ];\n }\n return {\n lower,\n upper\n };\n}\nfunction convertToDateTime(value) {\n if (value instanceof Date) return value;\n if ('string' == typeof value || 'number' == typeof value) {\n const date = new Date(value);\n if (!isNaN(date.valueOf())) return date;\n throw new InconclusiveMatchError(`${value} is in an invalid date format`);\n }\n throw new InconclusiveMatchError(`The date provided ${value} must be a string, number, or date object`);\n}\nfunction relativeDateParseForFeatureFlagMatching(value) {\n const regex = /^-?(?<number>[0-9]+)(?<interval>[a-z])$/;\n const match = value.match(regex);\n const parsedDt = new Date(new Date().toISOString());\n if (!match) return null;\n {\n if (!match.groups) return null;\n const number = parseInt(match.groups['number']);\n if (number >= 10000) return null;\n const interval = match.groups['interval'];\n if ('h' == interval) parsedDt.setUTCHours(parsedDt.getUTCHours() - number);\n else if ('d' == interval) parsedDt.setUTCDate(parsedDt.getUTCDate() - number);\n else if ('w' == interval) parsedDt.setUTCDate(parsedDt.getUTCDate() - 7 * number);\n else if ('m' == interval) parsedDt.setUTCMonth(parsedDt.getUTCMonth() - number);\n else {\n if ('y' != interval) return null;\n parsedDt.setUTCFullYear(parsedDt.getUTCFullYear() - number);\n }\n return parsedDt;\n }\n}\nexport { ClientError, FeatureFlagsPoller, InconclusiveMatchError, RequiresServerEvaluation, matchProperty, parseSemver, relativeDateParseForFeatureFlagMatching };\n","function makeUncaughtExceptionHandler(captureFn, onFatalFn) {\n let calledFatalError = false;\n return Object.assign((error)=>{\n const userProvidedListenersCount = global.process.listeners('uncaughtException').filter((listener)=>'domainUncaughtExceptionClear' !== listener.name && true !== listener._posthogErrorHandler).length;\n const processWouldExit = 0 === userProvidedListenersCount;\n captureFn(error, {\n mechanism: {\n type: 'onuncaughtexception',\n handled: false\n }\n });\n if (!calledFatalError && processWouldExit) {\n calledFatalError = true;\n onFatalFn(error);\n }\n }, {\n _posthogErrorHandler: true\n });\n}\nfunction addUncaughtExceptionListener(captureFn, onFatalFn) {\n globalThis.process?.on('uncaughtException', makeUncaughtExceptionHandler(captureFn, onFatalFn));\n}\nfunction addUnhandledRejectionListener(captureFn) {\n globalThis.process?.on('unhandledRejection', (reason)=>captureFn(reason, {\n mechanism: {\n type: 'onunhandledrejection',\n handled: false\n }\n }));\n}\nexport { addUncaughtExceptionListener, addUnhandledRejectionListener };\n","import { addUncaughtExceptionListener, addUnhandledRejectionListener } from \"./autocapture.mjs\";\nimport { BucketedRateLimiter, isObject, resolveExceptionRateLimiterConfig } from \"@posthog/core\";\nconst SHUTDOWN_TIMEOUT = 2000;\nclass ErrorTracking {\n constructor(client, options, _logger){\n this.client = client;\n this._exceptionAutocaptureEnabled = options.enableExceptionAutocapture || false;\n this._logger = _logger;\n this._rateLimiter = new BucketedRateLimiter({\n ...resolveExceptionRateLimiterConfig(options),\n refillInterval: 10000,\n _logger: this._logger\n });\n this.startAutocaptureIfEnabled();\n }\n static isPreviouslyCapturedError(x) {\n return isObject(x) && '__posthog_previously_captured_error' in x && true === x.__posthog_previously_captured_error;\n }\n static async buildEventMessage(builder, error, hint, distinctId, additionalProperties) {\n const properties = {\n ...additionalProperties\n };\n const exceptionProperties = builder.buildFromUnknown(error, hint);\n exceptionProperties.$exception_list = await builder.modifyFrames(exceptionProperties.$exception_list);\n return {\n event: '$exception',\n distinctId: distinctId,\n properties: {\n ...exceptionProperties,\n ...properties\n },\n _originatedFromCaptureException: true\n };\n }\n startAutocaptureIfEnabled() {\n if (this.isEnabled()) {\n addUncaughtExceptionListener(this.onException.bind(this), this.onFatalError.bind(this));\n addUnhandledRejectionListener(this.onException.bind(this));\n }\n }\n onException(exception, hint) {\n this.client.addPendingPromise((async ()=>{\n if (!ErrorTracking.isPreviouslyCapturedError(exception)) {\n const eventMessage = await ErrorTracking.buildEventMessage(this.client.getErrorPropertiesBuilder(), exception, hint);\n const exceptionProperties = eventMessage.properties;\n const exceptionType = exceptionProperties?.$exception_list[0]?.type ?? 'Exception';\n const isRateLimited = this._rateLimiter.consumeRateLimit(exceptionType);\n if (isRateLimited) return void this._logger.info('Skipping exception capture because of client rate limiting.', {\n exception: exceptionType\n });\n return this.client._capturePreparedEvent(eventMessage, false);\n }\n })());\n }\n async onFatalError(exception) {\n console.error(exception);\n await this.client.shutdown(SHUTDOWN_TIMEOUT);\n globalThis.process.exit(1);\n }\n isEnabled() {\n return !this.client.isDisabled && this._exceptionAutocaptureEnabled;\n }\n shutdown() {\n this._rateLimiter.stop();\n }\n}\nexport { ErrorTracking as default };\n","class PostHogMemoryStorage {\n getProperty(key) {\n return this._memoryStorage[key];\n }\n setProperty(key, value) {\n this._memoryStorage[key] = null !== value ? value : void 0;\n }\n constructor(){\n this._memoryStorage = {};\n }\n}\nexport { PostHogMemoryStorage };\n","function isCaptureMode(value) {\n return 'v0' === value || 'v1' === value;\n}\nfunction resolveCaptureMode() {\n const envMode = 'undefined' != typeof process ? process.env?.POSTHOG_CAPTURE_MODE : void 0;\n return isCaptureMode(envMode) ? envMode : 'v0';\n}\nexport { resolveCaptureMode };\n","const AI_EVENT_PREFIX = '$ai_';\nconst ANALYTICS_ROUTE = 'analytics';\nconst AI_ROUTE = 'ai';\nfunction isLegacyOnlyEvent(message) {\n return 'string' == typeof message.event && message.event.startsWith(AI_EVENT_PREFIX);\n}\nexport { AI_ROUTE, ANALYTICS_ROUTE, isLegacyOnlyEvent };\n","class CaptureV1Error extends Error {\n constructor({ requestId, drops, retryExhausted, cause }){\n super(CaptureV1Error.buildMessage(requestId, drops, retryExhausted, cause)), this.name = 'CaptureV1Error';\n this.requestId = requestId;\n this.drops = drops;\n this.retryExhausted = retryExhausted;\n this.cause = cause;\n }\n static buildMessage(requestId, drops, retryExhausted, cause) {\n let message = `Capture V1 batch ${requestId} did not fully deliver: ${drops.length} dropped, ${retryExhausted.length} undelivered`;\n if (cause instanceof Error) message += ` (${cause.message})`;\n return message;\n }\n}\nexport { CaptureV1Error };\n","function coerceBool(value) {\n if ('boolean' == typeof value) return value;\n if ('number' == typeof value) return 0 !== value;\n if ('string' == typeof value) {\n const normalized = value.trim().toLowerCase();\n if ('true' === normalized || '1' === normalized) return true;\n if ('false' === normalized || '0' === normalized) return false;\n }\n}\nfunction coerceString(value) {\n return 'string' == typeof value ? value : void 0;\n}\nconst OPTION_SENTINELS = [\n {\n property: '$cookieless_mode',\n optionKey: 'cookieless_mode',\n coerce: coerceBool\n },\n {\n property: '$ignore_sent_at',\n optionKey: 'disable_skew_correction',\n coerce: coerceBool\n },\n {\n property: '$process_person_profile',\n optionKey: 'process_person_profile',\n coerce: coerceBool\n },\n {\n property: '$product_tour_id',\n optionKey: 'product_tour_id',\n coerce: coerceString\n }\n];\nconst TOPLEVEL_SENTINELS = [\n {\n property: '$session_id',\n field: 'session_id'\n },\n {\n property: '$window_id',\n field: 'window_id'\n }\n];\nfunction isRecord(value) {\n return 'object' == typeof value && null !== value && !Array.isArray(value);\n}\nfunction toRfc3339(timestamp) {\n if ('string' == typeof timestamp) {\n const asDate = new Date(timestamp);\n return Number.isNaN(asDate.getTime()) ? new Date().toISOString() : timestamp;\n }\n if (timestamp instanceof Date) return Number.isNaN(timestamp.getTime()) ? new Date().toISOString() : timestamp.toISOString();\n const asDate = null == timestamp ? new Date() : new Date(timestamp);\n return Number.isNaN(asDate.getTime()) ? new Date().toISOString() : asDate.toISOString();\n}\nfunction relocateInto(properties, key, value) {\n if (void 0 !== value && !(key in properties)) properties[key] = value;\n}\nfunction buildV1Event(message) {\n const sourceProperties = isRecord(message.properties) ? message.properties : {};\n const properties = {\n ...sourceProperties\n };\n const options = {};\n for (const { property, optionKey, coerce } of OPTION_SENTINELS)if (property in properties) {\n const coerced = coerce(properties[property]);\n if (void 0 !== coerced) options[optionKey] = coerced;\n delete properties[property];\n }\n const topLevel = {};\n for (const { property, field } of TOPLEVEL_SENTINELS)if (property in properties) {\n const value = properties[property];\n if ('string' == typeof value) topLevel[field] = value;\n delete properties[property];\n }\n delete properties.$lib;\n delete properties.$lib_version;\n relocateInto(properties, '$set', message.$set);\n relocateInto(properties, '$set_once', message.$set_once);\n return {\n event: String(message.event ?? ''),\n uuid: String(message.uuid ?? ''),\n distinct_id: String(message.distinct_id ?? ''),\n timestamp: toRfc3339(message.timestamp),\n ...topLevel,\n options,\n properties\n };\n}\nfunction buildV1Batch(messages, { createdAt, historicalMigration }) {\n const batch = {\n created_at: createdAt,\n batch: messages.map(buildV1Event)\n };\n if (historicalMigration) batch.historical_migration = true;\n return batch;\n}\nexport { buildV1Batch, buildV1Event, coerceBool, coerceString };\n","import { gzipCompress, safeJsonStringify, safeSetTimeout, uuidv7 } from \"@posthog/core\";\nimport { CaptureV1Error } from \"./errors.mjs\";\nimport { buildV1Batch } from \"./transform.mjs\";\nconst V1_ANALYTICS_PATH = '/i/v1/analytics/events';\nconst DEFAULT_MAX_BACKOFF_MS = 30000;\nconst RETRYABLE_STATUSES = new Set([\n 408,\n 500,\n 502,\n 503,\n 504\n]);\nclass V1CaptureSender {\n constructor(config, hooks){\n this.config = config;\n this.maxBackoffMs = config.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS;\n this.fetchFn = hooks.fetch;\n this.onError = hooks.onError;\n this.now = hooks.now ?? Date.now;\n this.sleep = hooks.sleep ?? ((ms)=>new Promise((resolve)=>safeSetTimeout(resolve, ms)));\n this.generateRequestId = hooks.generateRequestId ?? uuidv7;\n this.compress = hooks.compress ?? gzipCompress;\n }\n async sendV1Batch(messages) {\n if (0 === messages.length) return;\n const requestId = this.generateRequestId();\n const createdAt = new Date(this.now()).toISOString();\n const { batch } = buildV1Batch(messages, {\n createdAt,\n historicalMigration: this.config.historicalMigration\n });\n const url = `${this.config.host}${V1_ANALYTICS_PATH}`;\n const drops = [];\n let pending = batch;\n const maxAttempts = Math.max(1, this.config.maxAttempts);\n for(let attempt = 1; attempt <= maxAttempts; attempt++){\n const isLastAttempt = attempt === maxAttempts;\n const payload = safeJsonStringify({\n created_at: createdAt,\n ...this.config.historicalMigration ? {\n historical_migration: true\n } : {},\n batch: pending\n });\n let response;\n try {\n response = await this.sendOnce(url, payload, attempt, requestId);\n } catch (transportError) {\n if (isLastAttempt) return this.surfaceBatchFailure(requestId, drops, pending, transportError);\n await this.sleep(this.backoffDelay(attempt));\n continue;\n }\n const { status } = response;\n if (status < 200 || status >= 300) {\n if (!isLastAttempt && RETRYABLE_STATUSES.has(status)) {\n const retryAfterMs = this.parseRetryAfter(response);\n await this.cancelBody(response);\n await this.sleep(this.backoffDelay(attempt, retryAfterMs));\n continue;\n }\n const httpError = await this.buildHttpError(response, status);\n return this.surfaceBatchFailure(requestId, drops, pending, httpError);\n }\n let parsed;\n try {\n parsed = await this.parseResponse(response);\n } catch {\n return this.surfaceBatchFailure(requestId, drops, pending, new Error(`Capture V1 returned an unparseable ${status} response body`));\n }\n const retryable = this.classify(pending, parsed, drops);\n if (0 === retryable.length) return this.surfacePartialDrops(requestId, drops);\n if (isLastAttempt) return void this.onError(new CaptureV1Error({\n requestId,\n drops,\n retryExhausted: retryable.map((event)=>event.uuid)\n }));\n pending = retryable;\n const retryAfterMs = this.parseRetryAfter(response);\n await this.sleep(this.backoffDelay(attempt, retryAfterMs));\n }\n }\n async sendOnce(url, payload, attempt, requestId) {\n const headers = this.buildHeaders(attempt, requestId);\n let body = payload;\n if (this.config.compressionEnabled) {\n const compressed = await this.compress(payload, this.config.isDebug);\n if (null !== compressed) {\n body = compressed;\n headers['Content-Encoding'] = 'gzip';\n }\n }\n const controller = new AbortController();\n const timer = safeSetTimeout(()=>controller.abort(), this.config.requestTimeoutMs);\n try {\n return await this.fetchFn(url, {\n method: 'POST',\n headers,\n body,\n signal: controller.signal\n });\n } finally{\n clearTimeout(timer);\n }\n }\n buildHeaders(attempt, requestId) {\n const sdkInfo = `${this.config.libraryId}/${this.config.libraryVersion}`;\n const headers = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.config.apiKey}`,\n 'PostHog-Sdk-Info': sdkInfo,\n 'PostHog-Attempt': String(attempt),\n 'PostHog-Request-Id': requestId,\n 'PostHog-Request-Timestamp': new Date(this.now()).toISOString()\n };\n if (this.config.userAgent) headers['User-Agent'] = this.config.userAgent;\n return headers;\n }\n classify(pending, parsed, drops) {\n const results = parsed.results ?? {};\n const retryable = [];\n for (const event of pending){\n const result = results[event.uuid];\n if (result) {\n if ('drop' === result.result) drops.push({\n uuid: event.uuid,\n details: result.details ?? void 0\n });\n else if ('retry' === result.result) retryable.push(event);\n }\n }\n return retryable;\n }\n backoffDelay(attempt, retryAfterMs) {\n const exponential = Math.min(this.config.initialRetryDelayMs * 2 ** (attempt - 1), this.maxBackoffMs);\n if (void 0 === retryAfterMs) return exponential;\n return Math.max(exponential, Math.min(retryAfterMs, this.maxBackoffMs));\n }\n parseRetryAfter(response) {\n const raw = response.headers?.get('Retry-After');\n if (!raw) return;\n const trimmed = raw.trim();\n if (/^\\d+$/.test(trimmed)) {\n const seconds = parseInt(trimmed, 10);\n return Number.isFinite(seconds) && seconds > 0 ? 1000 * seconds : void 0;\n }\n const dateMs = Date.parse(trimmed);\n if (Number.isNaN(dateMs)) return;\n const delta = dateMs - this.now();\n return delta > 0 ? delta : void 0;\n }\n async parseResponse(response) {\n const text = await response.text();\n const parsed = JSON.parse(text);\n if ('object' != typeof parsed || null === parsed || Array.isArray(parsed)) throw new Error('unexpected response shape');\n const results = parsed.results;\n if (void 0 !== results && ('object' != typeof results || null === results || Array.isArray(results))) throw new Error('unexpected results shape');\n return {\n results: results ?? {}\n };\n }\n async buildHttpError(response, status) {\n let bodyText = '';\n try {\n bodyText = (await response.text()).slice(0, 512);\n } catch {}\n const suffix = bodyText ? `: ${bodyText}` : '';\n return new Error(`Capture V1 request failed with HTTP ${status}${suffix}`);\n }\n surfaceBatchFailure(requestId, drops, pending, cause) {\n this.onError(new CaptureV1Error({\n requestId,\n drops,\n retryExhausted: pending.map((event)=>event.uuid),\n cause\n }));\n }\n surfacePartialDrops(requestId, drops) {\n if (drops.length > 0) this.onError(new CaptureV1Error({\n requestId,\n drops,\n retryExhausted: []\n }));\n }\n async cancelBody(response) {\n await response.body?.cancel()?.catch(()=>{});\n }\n}\nexport { V1CaptureSender };\n","import { version } from \"./version.mjs\";\nimport { PostHogCoreStateless, PostHogMetrics, PostHogPersistedProperty, isBlockedUA, isPlainObject, minimizeFlagCalledEventProperties, resolveMetricsConfig, safeSetTimeout, uuidv7 } from \"@posthog/core\";\nimport { FeatureFlagError } from \"./types.mjs\";\nimport { FeatureFlagEvaluations } from \"./feature-flag-evaluations.mjs\";\nimport { FeatureFlagsPoller, InconclusiveMatchError, RequiresServerEvaluation } from \"./extensions/feature-flags/feature-flags.mjs\";\nimport error_tracking from \"./extensions/error-tracking/index.mjs\";\nimport { PostHogMemoryStorage } from \"./storage-memory.mjs\";\nimport { resolveCaptureMode } from \"./capture-v1/config.mjs\";\nimport { AI_ROUTE, ANALYTICS_ROUTE, isLegacyOnlyEvent } from \"./capture-v1/routing.mjs\";\nimport { V1CaptureSender } from \"./capture-v1/sender.mjs\";\nconst MINIMUM_POLLING_INTERVAL = 100;\nconst THIRTY_SECONDS = 30000;\nconst MAX_CACHE_SIZE = 50000;\nconst WAITUNTIL_DEBOUNCE_MS = 50;\nconst WAITUNTIL_MAX_WAIT_MS = 500;\nconst DEFAULT_NODE_HOST = 'https://us.i.posthog.com';\nconst _emittedDeprecations = new Set();\nfunction emitDeprecationWarningOnce(id, message) {\n if (_emittedDeprecations.has(id)) return;\n _emittedDeprecations.add(id);\n console.warn(`[PostHog] ${message}`);\n}\nfunction _resetDeprecationWarningsForTests() {\n _emittedDeprecations.clear();\n}\nfunction normalizeApiKey(value) {\n return 'string' == typeof value ? value.trim() : '';\n}\nfunction normalizePersonalApiKey(value) {\n const normalizedValue = 'string' == typeof value ? value.trim() : '';\n return normalizedValue || void 0;\n}\nfunction normalizeHost(value) {\n const normalizedValue = 'string' == typeof value ? value.trim() : '';\n return normalizedValue || DEFAULT_NODE_HOST;\n}\nfunction normalizeUnsetPersonProperties(value) {\n const propertyNames = Array.isArray(value) ? value : [\n value\n ];\n return propertyNames.filter((propertyName)=>'string' == typeof propertyName && propertyName.trim().length > 0);\n}\nfunction buildFlagEventProperties(flagValues) {\n if (!flagValues) return {};\n const additionalProperties = {};\n for (const [feature, variant] of Object.entries(flagValues))additionalProperties[`$feature/${feature}`] = variant;\n const activeFlags = Object.keys(flagValues).filter((flag)=>false !== flagValues[flag]).sort();\n if (activeFlags.length > 0) additionalProperties['$active_feature_flags'] = activeFlags;\n return additionalProperties;\n}\nclass PostHogBackendClient extends PostHogCoreStateless {\n constructor(apiKey, options = {}){\n const normalizedApiKey = normalizeApiKey(apiKey);\n const normalizedOptions = {\n ...options,\n maxQueueSize: options.maxQueueSize ?? 10000,\n flushInterval: options.flushInterval ?? 5000,\n host: normalizeHost(options.host),\n personalApiKey: normalizePersonalApiKey(options.secretKey ?? options.personalApiKey)\n };\n super(normalizedApiKey, normalizedOptions), this._memoryStorage = new PostHogMemoryStorage(), this._minimalFlagCalledEvents = false;\n this.options = normalizedOptions;\n this.captureMode = resolveCaptureMode();\n this.context = this.initializeContext();\n this.options.featureFlagsPollingInterval = 'number' == typeof normalizedOptions.featureFlagsPollingInterval ? Math.max(normalizedOptions.featureFlagsPollingInterval, MINIMUM_POLLING_INTERVAL) : THIRTY_SECONDS;\n if ('number' == typeof normalizedOptions.waitUntilDebounceMs) this.options.waitUntilDebounceMs = Math.max(normalizedOptions.waitUntilDebounceMs, 0);\n if ('number' == typeof normalizedOptions.waitUntilMaxWaitMs) this.options.waitUntilMaxWaitMs = Math.max(normalizedOptions.waitUntilMaxWaitMs, 0);\n if (!this.disabled && normalizedOptions.personalApiKey) {\n if (normalizedOptions.personalApiKey.includes('phc_')) throw new Error('Your Personal API key is invalid. These keys are prefixed with \"phx_\" and can be created in PostHog project settings.');\n const shouldEnableLocalEvaluation = false !== normalizedOptions.enableLocalEvaluation;\n if (shouldEnableLocalEvaluation) this.featureFlagsPoller = new FeatureFlagsPoller({\n pollingInterval: this.options.featureFlagsPollingInterval,\n personalApiKey: normalizedOptions.personalApiKey,\n projectApiKey: normalizedApiKey,\n timeout: normalizedOptions.requestTimeout ?? 10000,\n host: this.host,\n fetch: normalizedOptions.fetch,\n onError: (err)=>{\n this._events.emit('error', err);\n },\n onLoad: (count)=>{\n this._events.emit('localEvaluationFlagsLoaded', count);\n },\n onMinimalFlagCalledEvents: (enabled)=>{\n this._minimalFlagCalledEvents = enabled;\n },\n customHeaders: this.getCustomHeaders(),\n cacheProvider: normalizedOptions.flagDefinitionCacheProvider,\n strictLocalEvaluation: normalizedOptions.strictLocalEvaluation\n });\n }\n this.errorTracking = new error_tracking(this, normalizedOptions, this._logger);\n this.distinctIdHasSentFlagCalls = {};\n this.maxCacheSize = normalizedOptions.maxCacheSize || MAX_CACHE_SIZE;\n }\n enqueue(type, message, options) {\n super.enqueue(type, message, options);\n this.scheduleDebouncedFlush();\n }\n async flush() {\n const flushPromise = this.flushWithPendingPromises();\n const waitUntil = this.options.waitUntil;\n if (waitUntil && !this._waitUntilCycle) try {\n waitUntil(flushPromise.catch(()=>{}));\n } catch {}\n return flushPromise;\n }\n scheduleDebouncedFlush() {\n const waitUntil = this.options.waitUntil;\n if (!waitUntil) return;\n if (this.disabled || this.optedOut) return;\n if (!this._waitUntilCycle) {\n let resolve;\n const promise = new Promise((r)=>{\n resolve = r;\n });\n try {\n waitUntil(promise);\n } catch {\n return;\n }\n this._waitUntilCycle = {\n resolve: resolve,\n startedAt: Date.now(),\n timer: void 0\n };\n }\n const elapsed = Date.now() - this._waitUntilCycle.startedAt;\n const maxWaitMs = this.options.waitUntilMaxWaitMs ?? WAITUNTIL_MAX_WAIT_MS;\n const flushNow = elapsed >= maxWaitMs;\n if (void 0 !== this._waitUntilCycle.timer) clearTimeout(this._waitUntilCycle.timer);\n if (flushNow) return void this.resolveWaitUntilFlush();\n const debounceMs = this.options.waitUntilDebounceMs ?? WAITUNTIL_DEBOUNCE_MS;\n this._waitUntilCycle.timer = safeSetTimeout(()=>{\n this.resolveWaitUntilFlush();\n }, debounceMs);\n }\n _consumeWaitUntilCycle() {\n const cycle = this._waitUntilCycle;\n if (cycle) {\n clearTimeout(cycle.timer);\n this._waitUntilCycle = void 0;\n }\n return cycle?.resolve;\n }\n async resolveWaitUntilFlush() {\n const resolve = this._consumeWaitUntilCycle();\n try {\n await this.flushWithPendingPromises();\n } catch {} finally{\n resolve?.();\n }\n }\n getPersistedProperty(key) {\n return this._memoryStorage.getProperty(key);\n }\n setPersistedProperty(key, value) {\n return this._memoryStorage.setProperty(key, value);\n }\n fetch(url, options) {\n return this.options.fetch ? this.options.fetch(url, options) : fetch(url, options);\n }\n getQueueRouteKey(message) {\n return 'v1' === this.captureMode && isLegacyOnlyEvent(message) ? AI_ROUTE : ANALYTICS_ROUTE;\n }\n persistedQueueKeyForRoute(route) {\n return route === AI_ROUTE ? PostHogPersistedProperty.AiQueue : PostHogPersistedProperty.Queue;\n }\n getActiveQueueRoutes() {\n return 'v1' === this.captureMode ? [\n ANALYTICS_ROUTE,\n AI_ROUTE\n ] : [\n ANALYTICS_ROUTE\n ];\n }\n async sendBatch(batchMessages, retryOptions, route = ANALYTICS_ROUTE) {\n if ('v1' !== this.captureMode || route === AI_ROUTE) return super.sendBatch(batchMessages, retryOptions, route);\n const v1Events = batchMessages.filter((message)=>void 0 !== message);\n await this.getV1Sender().sendV1Batch(v1Events);\n }\n getV1Sender() {\n if (!this._v1Sender) this._v1Sender = new V1CaptureSender({\n host: this.host,\n apiKey: this.apiKey,\n libraryId: this.getLibraryId(),\n libraryVersion: this.getLibraryVersion(),\n userAgent: this.getCustomUserAgent() || void 0,\n historicalMigration: this.historicalMigration,\n compressionEnabled: !this.disableCompression,\n requestTimeoutMs: this.requestTimeout,\n maxAttempts: (this.options.fetchRetryCount ?? 3) + 1,\n initialRetryDelayMs: this.options.fetchRetryDelay ?? 3000,\n isDebug: this.isDebug\n }, {\n fetch: (url, fetchOptions)=>this.fetch(url, fetchOptions),\n onError: (error)=>this._events.emit('error', error)\n });\n return this._v1Sender;\n }\n getLibraryVersion() {\n return version;\n }\n get metrics() {\n if (!this._metrics) this._metrics = new PostHogMetrics(this, resolveMetricsConfig(this.options.metrics), this._logger);\n return this._metrics;\n }\n getCustomUserAgent() {\n return `${this.getLibraryId()}/${this.getLibraryVersion()}`;\n }\n getCommonEventProperties() {\n const commonProperties = super.getCommonEventProperties();\n if (this.options.isServer ?? true) commonProperties.$is_server = true;\n return commonProperties;\n }\n enable() {\n return super.optIn();\n }\n disable() {\n return super.optOut();\n }\n debug(enabled = true) {\n super.debug(enabled);\n this.featureFlagsPoller?.debug(enabled);\n }\n _warnIfInvalidCapture(props, stringArgumentWarning, exceptionCaptureWarning) {\n if ('string' == typeof props) this._logger.warn(stringArgumentWarning);\n if ('$exception' === props.event && !props._originatedFromCaptureException) this._logger.warn(exceptionCaptureWarning);\n }\n _sendPreparedEvent(type, props, immediate, prepareOptions) {\n return this.addPendingPromise(this._prepareEventMessage(props, prepareOptions).then(({ distinctId, event, properties, options })=>{\n const captureOptions = {\n timestamp: options.timestamp,\n disableGeoip: options.disableGeoip,\n uuid: options.uuid\n };\n const message = {\n distinctId,\n event,\n properties: {\n ...properties,\n ...this.getCommonEventProperties()\n }\n };\n return immediate ? this.sendImmediate(type, message, captureOptions) : this.enqueue(type, message, captureOptions);\n }).catch((err)=>{\n if (err) console.error(err);\n }));\n }\n _capturePreparedEvent(props, immediate) {\n return this._sendPreparedEvent('capture', props, immediate);\n }\n capture(props) {\n this._warnIfInvalidCapture(props, 'Called capture() with a string as the first argument when an object was expected.', \"Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically.\");\n this._capturePreparedEvent(props, false);\n }\n async captureImmediate(props) {\n this._warnIfInvalidCapture(props, 'Called captureImmediate() with a string as the first argument when an object was expected.', \"Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default.\");\n return this._capturePreparedEvent(props, true);\n }\n identify({ distinctId, properties = {}, disableGeoip }) {\n const { $set, $set_once, $anon_distinct_id, ...rest } = properties;\n const setProps = $set || rest;\n const setOnceProps = $set_once || {};\n const eventProperties = {\n $set: setProps,\n $set_once: setOnceProps,\n $anon_distinct_id: $anon_distinct_id ?? void 0\n };\n this._sendPreparedEvent('identify', {\n distinctId,\n event: '$identify',\n properties: eventProperties,\n disableGeoip\n }, false, {\n includeContextProperties: false\n });\n }\n async identifyImmediate({ distinctId, properties = {}, disableGeoip }) {\n const { $set, $set_once, $anon_distinct_id, ...rest } = properties;\n const setProps = $set || rest;\n const setOnceProps = $set_once || {};\n const eventProperties = {\n $set: setProps,\n $set_once: setOnceProps,\n $anon_distinct_id: $anon_distinct_id ?? void 0\n };\n await this._sendPreparedEvent('identify', {\n distinctId,\n event: '$identify',\n properties: eventProperties,\n disableGeoip\n }, true, {\n includeContextProperties: false\n });\n }\n setPersonProperties({ distinctId, properties = {}, propertiesOnce = {} }) {\n if (0 === Object.keys(properties).length && 0 === Object.keys(propertiesOnce).length) return;\n const eventProperties = {};\n if (Object.keys(properties).length > 0) eventProperties.$set = properties;\n if (Object.keys(propertiesOnce).length > 0) eventProperties.$set_once = propertiesOnce;\n this.capture({\n distinctId,\n event: '$set',\n properties: eventProperties\n });\n }\n unsetPersonProperties({ distinctId, properties }) {\n const propertyNames = normalizeUnsetPersonProperties(properties);\n if (0 === propertyNames.length) return;\n this.capture({\n distinctId,\n event: '$set',\n properties: {\n $unset: propertyNames\n }\n });\n }\n alias(data) {\n this._sendPreparedEvent('alias', {\n distinctId: data.distinctId,\n event: '$create_alias',\n properties: {\n distinct_id: data.distinctId,\n alias: data.alias\n },\n disableGeoip: data.disableGeoip\n }, false, {\n includeContextProperties: false\n });\n }\n async aliasImmediate(data) {\n await this._sendPreparedEvent('alias', {\n distinctId: data.distinctId,\n event: '$create_alias',\n properties: {\n distinct_id: data.distinctId,\n alias: data.alias\n },\n disableGeoip: data.disableGeoip\n }, true, {\n includeContextProperties: false\n });\n }\n isLocalEvaluationReady() {\n return this.featureFlagsPoller?.isLocalEvaluationReady() ?? false;\n }\n async waitForLocalEvaluationReady(timeoutMs = THIRTY_SECONDS) {\n if (this.isLocalEvaluationReady()) return true;\n if (void 0 === this.featureFlagsPoller) return false;\n return new Promise((resolve)=>{\n const timeout = setTimeout(()=>{\n cleanup();\n resolve(false);\n }, timeoutMs);\n const cleanup = this._events.on('localEvaluationFlagsLoaded', (count)=>{\n clearTimeout(timeout);\n cleanup();\n resolve(count > 0);\n });\n });\n }\n _resolveDistinctId(distinctIdOrOptions, options) {\n if ('string' == typeof distinctIdOrOptions) return {\n distinctId: distinctIdOrOptions,\n options\n };\n return {\n distinctId: this.context?.get()?.distinctId,\n options: distinctIdOrOptions\n };\n }\n async _getFeatureFlagResult(key, distinctId, options = {}, matchValue) {\n if (this.disabled) return void this._logger.warn('The client is disabled');\n const sendFeatureFlagEvents = options.sendFeatureFlagEvents ?? true;\n if (void 0 !== this._flagOverrides && key in this._flagOverrides) {\n const overrideValue = this._flagOverrides[key];\n if (void 0 === overrideValue) return;\n const overridePayload = this._payloadOverrides?.[key];\n return {\n key,\n enabled: false !== overrideValue,\n variant: 'string' == typeof overrideValue ? overrideValue : void 0,\n payload: overridePayload\n };\n }\n const { groups, disableGeoip } = options;\n let { onlyEvaluateLocally, personProperties, groupProperties } = options;\n const adjustedProperties = this.addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties);\n personProperties = adjustedProperties.allPersonProperties;\n groupProperties = adjustedProperties.allGroupProperties;\n const evaluationContext = this.createFeatureFlagEvaluationContext(distinctId, groups, this.personPropertiesForLocalEvaluation(distinctId, personProperties), groupProperties);\n if (void 0 == onlyEvaluateLocally) onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;\n let result;\n let flagWasLocallyEvaluated = false;\n let requestId;\n let evaluatedAt;\n let featureFlagError;\n let flagId;\n let flagVersion;\n let flagReason;\n let flagHasExperiment;\n const localEvaluationEnabled = void 0 !== this.featureFlagsPoller;\n if (localEvaluationEnabled) {\n await this.featureFlagsPoller?.loadFeatureFlags();\n const flag = this.featureFlagsPoller?.featureFlagsByKey[key];\n if (flag) try {\n const localResult = await this.featureFlagsPoller?.computeFlagAndPayloadLocally(flag, evaluationContext, {\n matchValue\n });\n if (localResult) {\n flagWasLocallyEvaluated = true;\n const value = localResult.value;\n flagId = flag.id;\n flagReason = 'Evaluated locally';\n flagHasExperiment = flag.has_experiment;\n result = {\n key,\n enabled: false !== value,\n variant: 'string' == typeof value ? value : void 0,\n payload: localResult.payload ?? void 0\n };\n }\n } catch (e) {\n if (e instanceof RequiresServerEvaluation || e instanceof InconclusiveMatchError) this._logger?.info(`${e.name} when computing flag locally: ${key}: ${e.message}`);\n else throw e;\n }\n }\n if (!flagWasLocallyEvaluated && !onlyEvaluateLocally) {\n const flagsResponse = await super.getFeatureFlagDetailsStateless(evaluationContext.distinctId, evaluationContext.groups, personProperties, groupProperties, disableGeoip, [\n key\n ]);\n if (void 0 === flagsResponse) featureFlagError = FeatureFlagError.UNKNOWN_ERROR;\n else {\n this._minimalFlagCalledEvents = true === flagsResponse.minimalFlagCalledEvents;\n requestId = flagsResponse.requestId;\n evaluatedAt = flagsResponse.evaluatedAt;\n const errors = [];\n if (flagsResponse.errorsWhileComputingFlags) errors.push(FeatureFlagError.ERRORS_WHILE_COMPUTING);\n if (flagsResponse.quotaLimited?.includes('feature_flags')) errors.push(FeatureFlagError.QUOTA_LIMITED);\n const flagDetail = flagsResponse.flags[key];\n if (void 0 === flagDetail) errors.push(FeatureFlagError.FLAG_MISSING);\n else {\n flagId = flagDetail.metadata?.id;\n flagVersion = flagDetail.metadata?.version;\n flagReason = flagDetail.reason?.description ?? flagDetail.reason?.code;\n flagHasExperiment = flagDetail.metadata?.has_experiment;\n let parsedPayload;\n if (flagDetail.metadata?.payload !== void 0) try {\n parsedPayload = JSON.parse(flagDetail.metadata.payload);\n } catch {\n parsedPayload = flagDetail.metadata.payload;\n }\n result = {\n key,\n enabled: flagDetail.enabled,\n variant: flagDetail.variant,\n payload: parsedPayload\n };\n }\n if (errors.length > 0) featureFlagError = errors.join(',');\n }\n }\n if (sendFeatureFlagEvents) {\n const response = void 0 === result ? void 0 : false === result.enabled ? false : result.variant ?? true;\n const properties = {\n $feature_flag: key,\n $feature_flag_response: response,\n $feature_flag_id: flagId,\n $feature_flag_version: flagVersion,\n $feature_flag_reason: flagReason,\n locally_evaluated: flagWasLocallyEvaluated,\n [`$feature/${key}`]: response,\n $feature_flag_request_id: requestId,\n $feature_flag_evaluated_at: flagWasLocallyEvaluated ? Date.now() : evaluatedAt\n };\n if (void 0 !== flagHasExperiment) properties.$feature_flag_has_experiment = flagHasExperiment;\n if (flagWasLocallyEvaluated && this.featureFlagsPoller) {\n const flagDefinitionsLoadedAt = this.featureFlagsPoller.getFlagDefinitionsLoadedAt();\n if (void 0 !== flagDefinitionsLoadedAt) properties.$feature_flag_definitions_loaded_at = flagDefinitionsLoadedAt;\n }\n if (featureFlagError) properties.$feature_flag_error = featureFlagError;\n this._captureFlagCalledEventIfNeeded({\n distinctId,\n key,\n response,\n groups,\n disableGeoip,\n properties\n });\n }\n if (void 0 !== result && void 0 !== this._payloadOverrides && key in this._payloadOverrides) result = {\n ...result,\n payload: this._payloadOverrides[key]\n };\n return result;\n }\n async getFeatureFlag(key, distinctId, options) {\n emitDeprecationWarningOnce('getFeatureFlag', \"`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.\");\n const result = await this._getFeatureFlagResult(key, distinctId, {\n ...options,\n sendFeatureFlagEvents: options?.sendFeatureFlagEvents ?? this.options.sendFeatureFlagEvent ?? true\n });\n if (void 0 === result) return;\n if (false === result.enabled) return false;\n return result.variant ?? true;\n }\n async getFeatureFlagPayload(key, distinctId, matchValue, options) {\n emitDeprecationWarningOnce('getFeatureFlagPayload', \"`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.\");\n if (void 0 !== this._payloadOverrides && key in this._payloadOverrides) return this._payloadOverrides[key];\n const result = await this._getFeatureFlagResult(key, distinctId, {\n ...options,\n sendFeatureFlagEvents: false\n }, matchValue);\n if (void 0 === result) return;\n return result.payload ?? null;\n }\n async getFeatureFlagResult(key, distinctIdOrOptions, options) {\n const { distinctId: resolvedDistinctId, options: resolvedOptions } = this._resolveDistinctId(distinctIdOrOptions, options);\n if (!resolvedDistinctId) return void this._logger.warn(\"[PostHog] distinctId is required \\u2014 pass it explicitly or use withContext()\");\n return this._getFeatureFlagResult(key, resolvedDistinctId, {\n ...resolvedOptions,\n sendFeatureFlagEvents: resolvedOptions?.sendFeatureFlagEvents ?? this.options.sendFeatureFlagEvent ?? true\n });\n }\n async getRemoteConfigPayload(flagKey) {\n if (this.disabled) return void this._logger.warn('The client is disabled');\n if (!this.options.personalApiKey) throw new Error('Personal API key is required for remote config payload decryption');\n const response = await this._requestRemoteConfigPayload(flagKey);\n if (!response) return;\n const parsed = await response.json();\n if ('string' == typeof parsed) try {\n return JSON.parse(parsed);\n } catch (e) {}\n return parsed;\n }\n async isFeatureEnabled(key, distinctId, options) {\n emitDeprecationWarningOnce('isFeatureEnabled', \"`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.\");\n const result = await this._getFeatureFlagResult(key, distinctId, {\n ...options,\n sendFeatureFlagEvents: options?.sendFeatureFlagEvents ?? this.options.sendFeatureFlagEvent ?? true\n });\n if (void 0 === result) return;\n if (false === result.enabled) return false;\n const feat = result.variant ?? true;\n return !!feat || false;\n }\n async getAllFlags(distinctIdOrOptions, options) {\n const { distinctId: resolvedDistinctId, options: resolvedOptions } = this._resolveDistinctId(distinctIdOrOptions, options);\n if (!resolvedDistinctId) {\n this._logger.warn(\"[PostHog] distinctId is required to get feature flags \\u2014 pass it explicitly or use withContext()\");\n return {};\n }\n const response = await this.getAllFlagsAndPayloads(resolvedDistinctId, resolvedOptions);\n return response.featureFlags || {};\n }\n async getAllFlagsAndPayloads(distinctIdOrOptions, options) {\n const { distinctId: resolvedDistinctId, options: resolvedOptions } = this._resolveDistinctId(distinctIdOrOptions, options);\n if (!resolvedDistinctId) {\n this._logger.warn(\"[PostHog] distinctId is required to get feature flags and payloads \\u2014 pass it explicitly or use withContext()\");\n return {\n featureFlags: {},\n featureFlagPayloads: {}\n };\n }\n if (this.disabled) {\n this._logger.warn('The client is disabled');\n return {\n featureFlags: {},\n featureFlagPayloads: {}\n };\n }\n const { groups, disableGeoip, flagKeys } = resolvedOptions || {};\n let { onlyEvaluateLocally, personProperties, groupProperties } = resolvedOptions || {};\n const adjustedProperties = this.addLocalPersonAndGroupProperties(resolvedDistinctId, groups, personProperties, groupProperties);\n personProperties = adjustedProperties.allPersonProperties;\n groupProperties = adjustedProperties.allGroupProperties;\n const evaluationContext = this.createFeatureFlagEvaluationContext(resolvedDistinctId, groups, this.personPropertiesForLocalEvaluation(resolvedDistinctId, personProperties), groupProperties);\n if (void 0 == onlyEvaluateLocally) onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;\n const localEvaluationResult = await this.featureFlagsPoller?.getAllFlagsAndPayloads(evaluationContext, flagKeys);\n let featureFlags = {};\n let featureFlagPayloads = {};\n let fallbackToFlags = true;\n if (localEvaluationResult) {\n featureFlags = localEvaluationResult.response;\n featureFlagPayloads = localEvaluationResult.payloads;\n fallbackToFlags = localEvaluationResult.fallbackToFlags;\n }\n if (fallbackToFlags && !onlyEvaluateLocally) {\n const remoteEvaluationResult = await super.getFeatureFlagsAndPayloadsStateless(evaluationContext.distinctId, evaluationContext.groups, personProperties, groupProperties, disableGeoip, flagKeys);\n featureFlags = {\n ...featureFlags,\n ...remoteEvaluationResult.flags || {}\n };\n featureFlagPayloads = {\n ...featureFlagPayloads,\n ...remoteEvaluationResult.payloads || {}\n };\n }\n if (void 0 !== this._flagOverrides) featureFlags = {\n ...featureFlags,\n ...this._flagOverrides\n };\n if (void 0 !== this._payloadOverrides) featureFlagPayloads = {\n ...featureFlagPayloads,\n ...this._payloadOverrides\n };\n return {\n featureFlags,\n featureFlagPayloads\n };\n }\n async evaluateFlags(distinctIdOrOptions, options) {\n const { distinctId: resolvedDistinctId, options: resolvedOptions } = this._resolveDistinctId(distinctIdOrOptions, options);\n if (!resolvedDistinctId) {\n this._logger.warn(\"[PostHog] distinctId is required to evaluate feature flags \\u2014 pass it explicitly or use withContext()\");\n return new FeatureFlagEvaluations({\n host: this._getFeatureFlagEvaluationsHost(),\n distinctId: '',\n flags: {}\n });\n }\n if (this.disabled) {\n this._logger.warn('The client is disabled');\n return new FeatureFlagEvaluations({\n host: this._getFeatureFlagEvaluationsHost(),\n distinctId: resolvedDistinctId,\n flags: {}\n });\n }\n const { groups, disableGeoip, flagKeys } = resolvedOptions || {};\n let { onlyEvaluateLocally, personProperties, groupProperties } = resolvedOptions || {};\n const adjustedProperties = this.addLocalPersonAndGroupProperties(resolvedDistinctId, groups, personProperties, groupProperties);\n personProperties = adjustedProperties.allPersonProperties;\n groupProperties = adjustedProperties.allGroupProperties;\n const evaluationContext = this.createFeatureFlagEvaluationContext(resolvedDistinctId, groups, this.personPropertiesForLocalEvaluation(resolvedDistinctId, personProperties), groupProperties);\n if (void 0 == onlyEvaluateLocally) onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;\n const records = {};\n let requestId;\n let evaluatedAt;\n let errorsWhileComputing = false;\n let quotaLimited = false;\n const localResult = await this.featureFlagsPoller?.getAllFlagsAndPayloads(evaluationContext, flagKeys);\n const locallyEvaluatedKeys = new Set();\n if (localResult) for (const [key, value] of Object.entries(localResult.response)){\n const flagDef = this.featureFlagsPoller?.featureFlagsByKey[key];\n records[key] = {\n key,\n enabled: false !== value,\n variant: 'string' == typeof value ? value : void 0,\n payload: localResult.payloads[key],\n id: flagDef?.id,\n version: void 0,\n reason: 'Evaluated locally',\n locallyEvaluated: true,\n hasExperiment: flagDef?.has_experiment\n };\n locallyEvaluatedKeys.add(key);\n }\n const fallbackToFlags = localResult ? localResult.fallbackToFlags : true;\n if (fallbackToFlags && !onlyEvaluateLocally) {\n const details = await super.getFeatureFlagDetailsStateless(evaluationContext.distinctId, evaluationContext.groups, personProperties, groupProperties, disableGeoip, flagKeys);\n if (details) {\n this._minimalFlagCalledEvents = true === details.minimalFlagCalledEvents;\n requestId = details.requestId;\n evaluatedAt = details.evaluatedAt;\n errorsWhileComputing = Boolean(details.errorsWhileComputingFlags);\n quotaLimited = Array.isArray(details.quotaLimited) && details.quotaLimited.includes('feature_flags');\n for (const [key, detail] of Object.entries(details.flags)){\n if (locallyEvaluatedKeys.has(key)) continue;\n let parsedPayload;\n if (detail.metadata?.payload !== void 0) try {\n parsedPayload = JSON.parse(detail.metadata.payload);\n } catch {\n parsedPayload = detail.metadata.payload;\n }\n records[key] = {\n key,\n enabled: detail.enabled,\n variant: detail.variant,\n payload: parsedPayload,\n id: detail.metadata?.id,\n version: detail.metadata?.version,\n reason: detail.reason?.description ?? detail.reason?.code,\n locallyEvaluated: false,\n hasExperiment: detail.metadata?.has_experiment\n };\n }\n }\n }\n if (void 0 !== this._flagOverrides) for (const [key, value] of Object.entries(this._flagOverrides)){\n if (void 0 === value) {\n delete records[key];\n continue;\n }\n const existing = records[key];\n records[key] = {\n key,\n enabled: false !== value,\n variant: 'string' == typeof value ? value : void 0,\n payload: existing?.payload,\n id: existing?.id,\n version: existing?.version,\n reason: existing?.reason,\n locallyEvaluated: existing?.locallyEvaluated ?? false,\n hasExperiment: existing?.hasExperiment\n };\n }\n if (void 0 !== this._payloadOverrides) for (const [key, payload] of Object.entries(this._payloadOverrides)){\n const existing = records[key];\n if (existing) records[key] = {\n ...existing,\n payload\n };\n }\n return new FeatureFlagEvaluations({\n host: this._getFeatureFlagEvaluationsHost(),\n distinctId: resolvedDistinctId,\n groups,\n disableGeoip,\n flags: records,\n requestId,\n evaluatedAt,\n flagDefinitionsLoadedAt: this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),\n errorsWhileComputing,\n quotaLimited\n });\n }\n _shouldSendMinimalFlagCalledEvent(event, properties) {\n return '$feature_flag_called' === event && this._minimalFlagCalledEvents && false === properties.$feature_flag_has_experiment;\n }\n _captureFlagCalledEventIfNeeded(params) {\n const { distinctId, key, response, groups, disableGeoip, properties } = params;\n const groupSuffix = groups && Object.keys(groups).length > 0 ? `_${JSON.stringify(Object.entries(groups).sort(([a], [b])=>a < b ? -1 : a > b ? 1 : 0))}` : '';\n const featureFlagReportedKey = `${key}_${response}${groupSuffix}`;\n if (distinctId in this.distinctIdHasSentFlagCalls && this.distinctIdHasSentFlagCalls[distinctId].has(featureFlagReportedKey)) return;\n if (Object.keys(this.distinctIdHasSentFlagCalls).length >= this.maxCacheSize) this.distinctIdHasSentFlagCalls = {};\n if (this.distinctIdHasSentFlagCalls[distinctId] instanceof Set) this.distinctIdHasSentFlagCalls[distinctId].add(featureFlagReportedKey);\n else this.distinctIdHasSentFlagCalls[distinctId] = new Set([\n featureFlagReportedKey\n ]);\n this.capture({\n distinctId,\n event: '$feature_flag_called',\n properties,\n groups,\n disableGeoip\n });\n }\n _getFeatureFlagEvaluationsHost() {\n if (!this._featureFlagEvaluationsHost) this._featureFlagEvaluationsHost = {\n captureFlagCalledEventIfNeeded: (params)=>this._captureFlagCalledEventIfNeeded(params),\n logWarning: (message)=>{\n if (false !== this.options.featureFlagsLogWarnings) console.warn(`[PostHog] ${message}`);\n }\n };\n return this._featureFlagEvaluationsHost;\n }\n groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip }) {\n this._sendPreparedEvent('capture', {\n distinctId: distinctId || `$${groupType}_${groupKey}`,\n event: '$groupidentify',\n properties: {\n $group_type: groupType,\n $group_key: groupKey,\n $group_set: properties || {}\n },\n disableGeoip\n }, false, {\n includeContextProperties: false\n });\n }\n async groupIdentifyImmediate({ groupType, groupKey, properties, distinctId, disableGeoip }) {\n await this._sendPreparedEvent('capture', {\n distinctId: distinctId || `$${groupType}_${groupKey}`,\n event: '$groupidentify',\n properties: {\n $group_type: groupType,\n $group_key: groupKey,\n $group_set: properties || {}\n },\n disableGeoip\n }, true, {\n includeContextProperties: false\n });\n }\n async reloadFeatureFlags() {\n await this.featureFlagsPoller?.loadFeatureFlags(true);\n }\n overrideFeatureFlags(overrides) {\n const flagArrayToRecord = (flags)=>Object.fromEntries(flags.map((f)=>[\n f,\n true\n ]));\n if (false === overrides) {\n this._flagOverrides = void 0;\n this._payloadOverrides = void 0;\n return;\n }\n if (Array.isArray(overrides)) {\n this._flagOverrides = flagArrayToRecord(overrides);\n return;\n }\n if (this._isFeatureFlagOverrideOptions(overrides)) {\n if ('flags' in overrides) {\n if (false === overrides.flags) this._flagOverrides = void 0;\n else if (Array.isArray(overrides.flags)) this._flagOverrides = flagArrayToRecord(overrides.flags);\n else if (void 0 !== overrides.flags) this._flagOverrides = {\n ...overrides.flags\n };\n }\n if ('payloads' in overrides) {\n if (false === overrides.payloads) this._payloadOverrides = void 0;\n else if (void 0 !== overrides.payloads) this._payloadOverrides = {\n ...overrides.payloads\n };\n }\n return;\n }\n this._flagOverrides = {\n ...overrides\n };\n }\n _isFeatureFlagOverrideOptions(overrides) {\n if ('object' != typeof overrides || null === overrides || Array.isArray(overrides)) return false;\n const obj = overrides;\n if ('flags' in obj) {\n const flagsValue = obj['flags'];\n if (false === flagsValue || Array.isArray(flagsValue) || 'object' == typeof flagsValue && null !== flagsValue) return true;\n }\n if ('payloads' in obj) {\n const payloadsValue = obj['payloads'];\n if (false === payloadsValue || 'object' == typeof payloadsValue && null !== payloadsValue) return true;\n }\n return false;\n }\n withContext(data, fn, options) {\n if (!this.context) return fn();\n return this.context.run(data, fn, options);\n }\n getContext() {\n return this.context?.get();\n }\n enterContext(data, options) {\n this.context?.enter(data, options);\n }\n async _shutdown(shutdownTimeoutMs) {\n const shutdownDeadlineMs = Date.now() + (shutdownTimeoutMs ?? 30000);\n const resolve = this._consumeWaitUntilCycle();\n await this.featureFlagsPoller?.stopPoller(shutdownTimeoutMs);\n this.errorTracking.shutdown();\n if (this._metrics) {\n await Promise.race([\n this._metrics.flush().catch(()=>{}),\n new Promise((resolve)=>safeSetTimeout(resolve, Math.max(0, shutdownDeadlineMs - Date.now())))\n ]);\n this._metrics.reset();\n }\n try {\n return await super._shutdown(Math.max(0, shutdownDeadlineMs - Date.now()));\n } finally{\n this.distinctIdHasSentFlagCalls = {};\n resolve?.();\n }\n }\n async _requestRemoteConfigPayload(flagKey) {\n if (this.disabled || !this.apiKey || !this.options.personalApiKey) return;\n const url = `${this.host}/api/projects/@current/feature_flags/${flagKey}/remote_config?token=${encodeURIComponent(this.apiKey)}`;\n const options = {\n method: 'GET',\n headers: {\n ...this.getCustomHeaders(),\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.options.personalApiKey}`\n }\n };\n let abortTimeout = null;\n if (this.options.requestTimeout && 'number' == typeof this.options.requestTimeout) {\n const controller = new AbortController();\n abortTimeout = safeSetTimeout(()=>{\n controller.abort();\n }, this.options.requestTimeout);\n options.signal = controller.signal;\n }\n try {\n return await this.fetch(url, options);\n } catch (error) {\n this._events.emit('error', error);\n return;\n } finally{\n if (abortTimeout) clearTimeout(abortTimeout);\n }\n }\n extractPropertiesFromEvent(eventProperties, groups) {\n if (!eventProperties) return {\n personProperties: {},\n groupProperties: {}\n };\n const personProperties = {};\n const groupProperties = {};\n for (const [key, value] of Object.entries(eventProperties))if (isPlainObject(value) && groups && key in groups) {\n const groupProps = {};\n for (const [groupKey, groupValue] of Object.entries(value))groupProps[String(groupKey)] = String(groupValue);\n groupProperties[String(key)] = groupProps;\n } else personProperties[String(key)] = String(value);\n return {\n personProperties,\n groupProperties\n };\n }\n async getFeatureFlagsForEvent(distinctId, groups, disableGeoip, sendFeatureFlagsOptions) {\n if (this.disabled || !this.apiKey) return void this._logger.warn('The client is disabled');\n const finalPersonProperties = sendFeatureFlagsOptions?.personProperties || {};\n const finalGroupProperties = sendFeatureFlagsOptions?.groupProperties || {};\n const flagKeys = sendFeatureFlagsOptions?.flagKeys;\n const onlyEvaluateLocally = sendFeatureFlagsOptions?.onlyEvaluateLocally ?? this.options.strictLocalEvaluation ?? false;\n if (onlyEvaluateLocally) if (!((this.featureFlagsPoller?.featureFlags?.length || 0) > 0)) return {};\n else {\n const groupsWithStringValues = {};\n for (const [key, value] of Object.entries(groups || {}))groupsWithStringValues[key] = String(value);\n return await this.getAllFlags(distinctId, {\n groups: groupsWithStringValues,\n personProperties: finalPersonProperties,\n groupProperties: finalGroupProperties,\n disableGeoip,\n onlyEvaluateLocally: true,\n flagKeys\n });\n }\n if ((this.featureFlagsPoller?.featureFlags?.length || 0) > 0) {\n const groupsWithStringValues = {};\n for (const [key, value] of Object.entries(groups || {}))groupsWithStringValues[key] = String(value);\n return await this.getAllFlags(distinctId, {\n groups: groupsWithStringValues,\n personProperties: finalPersonProperties,\n groupProperties: finalGroupProperties,\n disableGeoip,\n onlyEvaluateLocally: true,\n flagKeys\n });\n }\n return (await super.getFeatureFlagsStateless(distinctId, groups, finalPersonProperties, finalGroupProperties, disableGeoip)).flags;\n }\n addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties) {\n const allPersonProperties = {\n ...personProperties || {}\n };\n const allGroupProperties = {};\n if (groups) for (const groupName of Object.keys(groups))allGroupProperties[groupName] = {\n $group_key: groups[groupName],\n ...groupProperties?.[groupName] || {}\n };\n return {\n allPersonProperties,\n allGroupProperties\n };\n }\n personPropertiesForLocalEvaluation(distinctId, personProperties) {\n return {\n distinct_id: distinctId,\n ...personProperties || {}\n };\n }\n createFeatureFlagEvaluationContext(distinctId, groups, personProperties, groupProperties) {\n return {\n distinctId,\n groups: groups || {},\n personProperties: personProperties || {},\n groupProperties: groupProperties || {},\n evaluationCache: {}\n };\n }\n captureException(error, distinctId, additionalProperties, uuid, flags) {\n if (!error_tracking.isPreviouslyCapturedError(error)) {\n const syntheticException = new Error('PostHog syntheticException');\n this.addPendingPromise(error_tracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {\n syntheticException\n }, distinctId, additionalProperties).then((msg)=>this._capturePreparedEvent({\n ...msg,\n uuid,\n flags\n }, false)));\n }\n }\n async captureExceptionImmediate(error, distinctId, additionalProperties, flags) {\n if (!error_tracking.isPreviouslyCapturedError(error)) {\n const syntheticException = new Error('PostHog syntheticException');\n return this.addPendingPromise(error_tracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {\n syntheticException\n }, distinctId, additionalProperties).then((msg)=>this.captureImmediate({\n ...msg,\n flags\n })));\n }\n }\n async prepareEventMessage(props) {\n return this._prepareEventMessage(props);\n }\n async _prepareEventMessage(props, options = {}) {\n const { distinctId, event, properties, groups, flags, sendFeatureFlags, timestamp, disableGeoip, uuid } = props;\n const contextData = this.context?.get();\n const includeContextProperties = options.includeContextProperties ?? true;\n let mergedDistinctId = distinctId || contextData?.distinctId;\n const mergedProperties = includeContextProperties ? {\n ...this.props,\n ...contextData?.properties || {},\n ...properties || {}\n } : {\n ...properties || {}\n };\n if (!mergedDistinctId) {\n mergedDistinctId = uuidv7();\n mergedProperties.$process_person_profile = false;\n }\n if (includeContextProperties && contextData?.sessionId && !mergedProperties.$session_id) mergedProperties.$session_id = contextData.sessionId;\n const finalProperties = this._shouldSendMinimalFlagCalledEvent(event, mergedProperties) ? minimizeFlagCalledEventProperties(mergedProperties) : mergedProperties;\n const eventMessage = this._runBeforeSend({\n distinctId: mergedDistinctId,\n event,\n properties: finalProperties,\n groups,\n flags,\n sendFeatureFlags,\n timestamp,\n disableGeoip,\n uuid\n });\n if (!eventMessage) return Promise.reject(null);\n const eventProperties = await Promise.resolve().then(async ()=>{\n if (flags) {\n if (sendFeatureFlags) console.warn('[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.');\n return flags._getEventProperties();\n }\n if (sendFeatureFlags) {\n emitDeprecationWarningOnce('sendFeatureFlags', \"`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead — it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.\");\n const sendFeatureFlagsOptions = 'object' == typeof sendFeatureFlags ? sendFeatureFlags : void 0;\n const flagValues = await this.getFeatureFlagsForEvent(eventMessage.distinctId, groups, disableGeoip, sendFeatureFlagsOptions);\n return buildFlagEventProperties(flagValues);\n }\n return {};\n }).catch(()=>({})).then((additionalProperties)=>{\n const resolvedGroups = eventMessage.groups || groups;\n return {\n ...additionalProperties,\n ...eventMessage.properties || {},\n ...void 0 !== resolvedGroups && Object.keys(resolvedGroups).length > 0 ? {\n $groups: resolvedGroups\n } : {}\n };\n });\n if ('$pageview' === eventMessage.event && this.options.__preview_capture_bot_pageviews && 'string' == typeof eventProperties.$raw_user_agent) {\n if (isBlockedUA(eventProperties.$raw_user_agent, this.options.custom_blocked_useragents || [])) {\n eventMessage.event = '$bot_pageview';\n eventProperties.$browser_type = 'bot';\n }\n }\n return {\n distinctId: eventMessage.distinctId,\n event: eventMessage.event,\n properties: eventProperties,\n options: {\n timestamp: eventMessage.timestamp,\n disableGeoip: eventMessage.disableGeoip,\n uuid: eventMessage.uuid\n }\n };\n }\n _runBeforeSend(eventMessage) {\n const beforeSend = this.options.before_send;\n if (!beforeSend) return eventMessage;\n const fns = Array.isArray(beforeSend) ? beforeSend : [\n beforeSend\n ];\n let result = eventMessage;\n for (const fn of fns){\n result = fn(result);\n if (!result) {\n this._logger.info(`Event '${eventMessage.event}' was rejected in beforeSend function`);\n return null;\n }\n if (!result.properties || 0 === Object.keys(result.properties).length) {\n const message = `Event '${result.event}' has no properties after beforeSend function, this is likely an error.`;\n this._logger.warn(message);\n }\n }\n return result;\n }\n}\nexport { PostHogBackendClient, _resetDeprecationWarningsForTests };\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nclass PostHogContext {\n constructor(){\n this.storage = new AsyncLocalStorage();\n }\n get() {\n return this.storage.getStore();\n }\n run(context, fn, options) {\n return this.storage.run(this.resolve(context, options), fn);\n }\n enter(context, options) {\n this.storage.enterWith(this.resolve(context, options));\n }\n resolve(context, options) {\n if (options?.fresh === true) return context;\n const current = this.get() || {};\n return {\n distinctId: context.distinctId ?? current.distinctId,\n sessionId: context.sessionId ?? current.sessionId,\n properties: {\n ...current.properties || {},\n ...context.properties || {}\n }\n };\n }\n}\nexport { PostHogContext };\n","const NAME = 'posthog-node';\nfunction createEventProcessor(_posthog, { organization, projectId, prefix, severityAllowList = [\n 'error'\n], sendExceptionsToPostHog = true } = {}) {\n return (event)=>{\n const shouldProcessLevel = '*' === severityAllowList || severityAllowList.includes(event.level);\n if (!shouldProcessLevel) return event;\n if (!event.tags) event.tags = {};\n const userId = event.tags[PostHogSentryIntegration.POSTHOG_ID_TAG];\n if (void 0 === userId) return event;\n const uiHost = _posthog.options.host ?? 'https://us.i.posthog.com';\n const personUrl = new URL(`/project/${_posthog.apiKey}/person/${userId}`, uiHost).toString();\n event.tags['PostHog Person URL'] = personUrl;\n const exceptions = event.exception?.values || [];\n const exceptionList = exceptions.map((exception)=>({\n ...exception,\n stacktrace: exception.stacktrace ? {\n ...exception.stacktrace,\n type: 'raw',\n frames: (exception.stacktrace.frames || []).map((frame)=>({\n ...frame,\n platform: \"node:javascript\"\n }))\n } : void 0\n }));\n const properties = {\n $exception_message: exceptions[0]?.value || event.message,\n $exception_type: exceptions[0]?.type,\n $exception_level: event.level,\n $exception_list: exceptionList,\n $sentry_event_id: event.event_id,\n $sentry_exception: event.exception,\n $sentry_exception_message: exceptions[0]?.value || event.message,\n $sentry_exception_type: exceptions[0]?.type,\n $sentry_tags: event.tags\n };\n if (organization && projectId) properties['$sentry_url'] = (prefix || 'https://sentry.io/organizations/') + organization + '/issues/?project=' + projectId + '&query=' + event.event_id;\n if (sendExceptionsToPostHog) _posthog.capture({\n event: '$exception',\n distinctId: userId,\n properties\n });\n return event;\n };\n}\nfunction sentryIntegration(_posthog, options) {\n const processor = createEventProcessor(_posthog, options);\n return {\n name: NAME,\n processEvent (event) {\n return processor(event);\n }\n };\n}\nclass PostHogSentryIntegration {\n static #_ = this.POSTHOG_ID_TAG = 'posthog_distinct_id';\n constructor(_posthog, organization, prefix, severityAllowList, sendExceptionsToPostHog){\n this.name = NAME;\n this.name = NAME;\n this.setupOnce = function(addGlobalEventProcessor, getCurrentHub) {\n const projectId = getCurrentHub()?.getClient()?.getDsn()?.projectId;\n addGlobalEventProcessor(createEventProcessor(_posthog, {\n organization,\n projectId,\n prefix,\n severityAllowList,\n sendExceptionsToPostHog: sendExceptionsToPostHog ?? true\n }));\n };\n }\n}\nexport { PostHogSentryIntegration, createEventProcessor, sentryIntegration };\n","import { stripUrlHash } from \"@posthog/core\";\nfunction normalizeRequestCurrentUrl(currentUrl, disableCaptureUrlHashes) {\n return disableCaptureUrlHashes ? stripUrlHash(currentUrl) : currentUrl;\n}\nfunction normalizeRequestPath(path, disableCaptureUrlHashes) {\n const pathWithoutSearch = stripUrlSearch(path);\n return disableCaptureUrlHashes ? stripUrlHash(pathWithoutSearch) : pathWithoutSearch;\n}\nfunction stripUrlSearch(url) {\n if (!url) return url;\n const searchIndex = url.indexOf('?');\n const hashIndex = url.indexOf('#');\n if (-1 === searchIndex || -1 !== hashIndex && hashIndex < searchIndex) return url;\n return `${url.slice(0, searchIndex)}${-1 === hashIndex ? '' : url.slice(hashIndex)}`;\n}\nexport { normalizeRequestCurrentUrl, normalizeRequestPath };\n","import error_tracking from \"./error-tracking/index.mjs\";\nimport { addProperty, getFirstHeaderValue, getPostHogTracingHeaderValues } from \"./tracing-headers.mjs\";\nimport { normalizeRequestCurrentUrl, normalizeRequestPath } from \"./url-utils.mjs\";\nfunction getClientIp(req) {\n const forwarded = getFirstHeaderValue(req.headers['x-forwarded-for']);\n if (forwarded) {\n const ip = forwarded.split(',')[0].trim();\n if (ip) return ip;\n }\n return req.socket?.remoteAddress;\n}\nfunction buildRequestContextData(posthog, req) {\n const { sessionId, distinctId } = getPostHogTracingHeaderValues(req.headers);\n const properties = {};\n const disableCaptureUrlHashes = true === posthog.options.disable_capture_url_hashes;\n addProperty(properties, '$current_url', normalizeRequestCurrentUrl(req.originalUrl || req.url, disableCaptureUrlHashes));\n addProperty(properties, '$request_method', req.method);\n addProperty(properties, '$request_path', normalizeRequestPath(req.path, disableCaptureUrlHashes));\n addProperty(properties, '$user_agent', getFirstHeaderValue(req.headers['user-agent']));\n addProperty(properties, '$ip', getClientIp(req));\n return {\n ...void 0 !== sessionId ? {\n sessionId\n } : {},\n ...void 0 !== distinctId ? {\n distinctId\n } : {},\n properties\n };\n}\nfunction setupExpressRequestContext(_posthog, app) {\n app.use(posthogRequestContext(_posthog));\n}\nfunction posthogRequestContext(posthog) {\n return (req, _res, next)=>{\n posthog.withContext(buildRequestContextData(posthog, req), ()=>next());\n };\n}\nfunction setupExpressErrorHandler(_posthog, app) {\n app.use(posthogErrorHandler(_posthog));\n}\nfunction posthogErrorHandler(posthog) {\n return (error, req, res, next)=>{\n if (error_tracking.isPreviouslyCapturedError(error)) return void next(error);\n const contextData = buildRequestContextData(posthog, req);\n const syntheticException = new Error('Synthetic exception');\n const hint = {\n mechanism: {\n type: 'middleware',\n handled: false\n },\n syntheticException\n };\n const additionalProperties = {\n ...void 0 !== contextData.sessionId ? {\n $session_id: contextData.sessionId\n } : {},\n ...contextData.properties || {},\n $response_status_code: res.statusCode\n };\n posthog.addPendingPromise(error_tracking.buildEventMessage(posthog.getErrorPropertiesBuilder(), error, hint, contextData.distinctId, additionalProperties).then((msg)=>posthog._capturePreparedEvent(msg, false)));\n next(error);\n };\n}\nexport { setupExpressErrorHandler, setupExpressRequestContext };\n","import { FeatureFlagEvaluations } from \"./feature-flag-evaluations.mjs\";\nimport { FeatureFlagError, cookieStateToProperties, cookieStoreFromHeader, getPostHogCookieName, parsePostHogCookie, readPostHogCookie, serializePostHogCookie, uuidv7 } from \"@posthog/core\";\nexport * from \"./extensions/sentry-integration.mjs\";\nexport * from \"./extensions/express.mjs\";\nexport * from \"./types.mjs\";\nexport { FeatureFlagError, FeatureFlagEvaluations, cookieStateToProperties, cookieStoreFromHeader, getPostHogCookieName, parsePostHogCookie, readPostHogCookie, serializePostHogCookie, uuidv7 };\n","import { createModulerModifier } from \"../extensions/error-tracking/modifiers/module.node.mjs\";\nimport { addSourceContext } from \"../extensions/error-tracking/modifiers/context-lines.node.mjs\";\nimport { createRelativePathModifier } from \"../extensions/error-tracking/modifiers/relative-path.node.mjs\";\nimport { PostHogBackendClient } from \"../client.mjs\";\nimport { ErrorTracking } from \"@posthog/core\";\nimport { PostHogContext } from \"../extensions/context/context.mjs\";\nexport * from \"../exports.mjs\";\nclass PostHog extends PostHogBackendClient {\n getLibraryId() {\n return 'posthog-node';\n }\n initializeContext() {\n return new PostHogContext();\n }\n createErrorPropertiesBuilder() {\n return new ErrorTracking.ErrorPropertiesBuilder([\n new ErrorTracking.EventCoercer(),\n new ErrorTracking.ErrorCoercer(),\n new ErrorTracking.ObjectCoercer(),\n new ErrorTracking.StringCoercer(),\n new ErrorTracking.PrimitiveCoercer()\n ], ErrorTracking.createStackParser(\"node:javascript\", ErrorTracking.nodeStackLineParser), [\n createModulerModifier(),\n addSourceContext,\n createRelativePathModifier()\n ]);\n }\n}\nexport { PostHog };\n","import { loadConfigSync } from '../config-yaml.js';\n\nexport function telemetryEnvironmentForcesOff(): boolean {\n const envValue = process.env.OVERDECK_TELEMETRY?.trim().toLowerCase();\n return envValue === '0' || envValue === 'false';\n}\n\nexport function resolveTelemetryEnabled(): boolean {\n if (telemetryEnvironmentForcesOff()) return false;\n return loadConfigSync().config.telemetry?.enabled !== false;\n}\n","import { randomUUID } from 'node:crypto';\nimport {\n chmodSync,\n mkdirSync,\n readFileSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from 'node:fs';\nimport { join } from 'node:path';\nimport { getOverdeckHome } from '../paths.js';\n\nconst INSTALL_ID_FILE = 'telemetry-id';\nconst INSTALL_ID_REPAIR_LOCK = 'telemetry-id.repair.lock';\nconst REPAIR_WAIT_MS = 10;\nconst REPAIR_LOCK_LEASE_MS = 1_000;\nconst REPAIR_MAX_ATTEMPTS = 200;\nconst REPAIR_WAIT_ARRAY = new Int32Array(new SharedArrayBuffer(4));\nconst UUID_V4_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\nfunction readValidInstallId(path: string): string | null {\n const installId = readFileSync(path, 'utf8').trim();\n return UUID_V4_PATTERN.test(installId) ? installId : null;\n}\n\nfunction errorCode(error: unknown): string | undefined {\n return error instanceof Error && 'code' in error\n ? String(error.code)\n : undefined;\n}\n\nfunction repairOwnerIsAlive(lockPath: string): boolean {\n try {\n const rawOwner = readFileSync(lockPath, 'utf8').trim();\n let ownerPid: number;\n let createdAt: number;\n try {\n const owner = JSON.parse(rawOwner) as { pid?: unknown; createdAt?: unknown };\n ownerPid = Number(owner.pid);\n createdAt = Number(owner.createdAt);\n } catch {\n ownerPid = Number(rawOwner);\n createdAt = statSync(lockPath).mtimeMs;\n }\n if (\n !Number.isInteger(ownerPid) ||\n ownerPid <= 0 ||\n !Number.isFinite(createdAt) ||\n Date.now() - createdAt >= REPAIR_LOCK_LEASE_MS\n ) return false;\n process.kill(ownerPid, 0);\n return true;\n } catch (error) {\n return errorCode(error) === 'EPERM';\n }\n}\n\nfunction replaceInvalidInstallId(path: string): void {\n const installId = randomUUID();\n const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;\n try {\n writeFileSync(temporaryPath, `${installId}\\n`, {\n encoding: 'utf8',\n mode: 0o600,\n flag: 'wx',\n });\n renameSync(temporaryPath, path);\n chmodSync(path, 0o600);\n } finally {\n rmSync(temporaryPath, { force: true });\n }\n}\n\nfunction repairInvalidInstallId(path: string, overdeckHome: string): string {\n const lockPath = join(overdeckHome, INSTALL_ID_REPAIR_LOCK);\n for (let attempt = 0; attempt < REPAIR_MAX_ATTEMPTS; attempt += 1) {\n try {\n writeFileSync(lockPath, `${JSON.stringify({\n pid: process.pid,\n createdAt: Date.now(),\n })}\\n`, {\n encoding: 'utf8',\n mode: 0o600,\n flag: 'wx',\n });\n } catch (error) {\n if (errorCode(error) !== 'EEXIST') throw error;\n const winner = readValidInstallId(path);\n if (winner) return winner;\n if (!repairOwnerIsAlive(lockPath)) {\n rmSync(lockPath, { force: true });\n continue;\n }\n Atomics.wait(REPAIR_WAIT_ARRAY, 0, 0, REPAIR_WAIT_MS);\n continue;\n }\n\n try {\n const winner = readValidInstallId(path);\n if (winner) return winner;\n replaceInvalidInstallId(path);\n const repaired = readValidInstallId(path);\n if (!repaired) throw new Error(`Failed to repair ${path}`);\n return repaired;\n } finally {\n rmSync(lockPath, { force: true });\n }\n }\n throw new Error(`Timed out waiting to repair ${path}`);\n}\n\nexport function getOrCreateInstallId(): string {\n const overdeckHome = getOverdeckHome();\n const installIdPath = join(overdeckHome, INSTALL_ID_FILE);\n\n try {\n const existing = readValidInstallId(installIdPath);\n return existing ?? repairInvalidInstallId(installIdPath, overdeckHome);\n } catch (error) {\n if (!(error instanceof Error) || !('code' in error) || error.code !== 'ENOENT') throw error;\n }\n\n mkdirSync(overdeckHome, { recursive: true });\n const installId = randomUUID();\n\n try {\n writeFileSync(installIdPath, `${installId}\\n`, { encoding: 'utf8', mode: 0o600, flag: 'wx' });\n return installId;\n } catch (error) {\n if (!(error instanceof Error) || !('code' in error) || error.code !== 'EEXIST') throw error;\n const existing = readValidInstallId(installIdPath);\n return existing ?? repairInvalidInstallId(installIdPath, overdeckHome);\n }\n}\n","import { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { inspect } from 'node:util';\nimport { PostHog } from 'posthog-node';\nimport type { TelemetryEventName, TelemetryPropertiesFor } from '@overdeck/contracts';\nimport { packageRoot } from '../paths.js';\nimport { resolveTelemetryEnabled } from './config.js';\nimport { getOrCreateInstallId } from './install-id.js';\n\nconst DEFAULT_POSTHOG_API_KEY = 'phc_pwvHeDutnCmAm8tZh5hRaQ7mMoho3T9gb4t4qRjK2Zjt';\nconst DEFAULT_POSTHOG_HOST = 'https://us.i.posthog.com';\nconst SHUTDOWN_TIMEOUT_MS = 2_000;\nconst FLAG_TIMEOUT_MS = 500;\n\nexport type AnalyticsClientType = 'cli' | 'server';\n\nexport interface AnalyticsServiceOptions {\n captureProcessExceptions?: boolean;\n fatalProcessExit?: (code: number) => never;\n featureFlagOverrides?: Readonly<Record<string, boolean>>;\n}\n\nexport type TelemetryExceptionAction =\n | 'cli_command'\n | 'pipeline_transition'\n | 'server_boot'\n | 'uncaught_exception'\n | 'unhandled_rejection';\n\nexport interface TelemetryExceptionContext {\n action: TelemetryExceptionAction;\n}\n\nlet cachedOverdeckVersion: string | undefined;\nlet processAnalyticsClientType: AnalyticsClientType = 'server';\nconst sharedAnalyticsServices = new Map<AnalyticsClientType, AnalyticsService>();\nconst pendingAnalyticsTasks = new Set<Promise<unknown>>();\n\nfunction getOverdeckVersion(): string {\n if (cachedOverdeckVersion) return cachedOverdeckVersion;\n try {\n const manifest = JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8')) as { version?: unknown };\n cachedOverdeckVersion = typeof manifest.version === 'string' ? manifest.version : 'unknown';\n } catch {\n cachedOverdeckVersion = 'unknown';\n }\n return cachedOverdeckVersion;\n}\n\nfunction telemetryBlockedForProcess(): boolean {\n return Boolean(process.env.VITEST) || process.env.NODE_ENV === 'test';\n}\n\nexport class AnalyticsService {\n private client: PostHog | undefined;\n private processExceptionHandlers: {\n uncaughtException: (error: Error) => void;\n unhandledRejection: (reason: unknown) => void;\n } | undefined;\n private fatalExceptionInFlight = false;\n\n constructor(\n private readonly clientType: AnalyticsClientType,\n private readonly options: AnalyticsServiceOptions = {},\n ) {}\n\n capture<Event extends TelemetryEventName>(\n event: Event,\n properties: TelemetryPropertiesFor<Event>,\n ): void {\n const client = this.getClient();\n if (!client) return;\n\n try {\n client.capture({\n distinctId: getOrCreateInstallId(),\n event,\n properties: {\n ...properties,\n $process_person_profile: false,\n platform: process.platform,\n arch: process.arch,\n overdeckVersion: getOverdeckVersion(),\n clientType: this.clientType,\n },\n });\n } catch {\n // Analytics must never fail the caller.\n }\n }\n\n captureException(_error: unknown, context: TelemetryExceptionContext): void {\n const client = this.getClient();\n if (!client) return;\n\n const sanitized = new Error(`Overdeck ${context.action} operation failed`);\n sanitized.name = 'OverdeckTelemetryException';\n sanitized.stack = undefined;\n\n try {\n client.captureException(\n sanitized,\n getOrCreateInstallId(),\n {\n action: context.action,\n $process_person_profile: false,\n platform: process.platform,\n arch: process.arch,\n overdeckVersion: getOverdeckVersion(),\n clientType: this.clientType,\n },\n );\n } catch {\n // Analytics must never fail the caller.\n }\n }\n\n async isFeatureEnabled(flag: string, fallback: boolean): Promise<boolean> {\n const override = this.options.featureFlagOverrides?.[flag];\n if (typeof override === 'boolean') return override;\n\n const client = this.getClient();\n if (!client) return fallback;\n\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n const result = await Promise.race([\n client.isFeatureEnabled(flag, getOrCreateInstallId(), {\n sendFeatureFlagEvents: false,\n }),\n new Promise<boolean>((resolve) => {\n timeout = setTimeout(() => resolve(fallback), FLAG_TIMEOUT_MS);\n }),\n ]);\n return typeof result === 'boolean' ? result : fallback;\n } catch {\n return fallback;\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n }\n\n async shutdown(timeoutMs = SHUTDOWN_TIMEOUT_MS): Promise<void> {\n this.detachProcessExceptionHandlers();\n const client = this.client;\n if (!client) return;\n this.client = undefined;\n\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n const shutdown = Promise.resolve(client.shutdown(Math.max(0, timeoutMs)));\n if (timeoutMs <= 0) return;\n await Promise.race([\n shutdown,\n new Promise<void>((resolve) => { timeout = setTimeout(resolve, timeoutMs); }),\n ]);\n } catch {\n // Analytics must never fail shutdown.\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n }\n\n private attachProcessExceptionHandlers(): void {\n if (!this.options.captureProcessExceptions || this.processExceptionHandlers) return;\n const uncaughtException = (error: Error): void => {\n this.captureFatalProcessException(error, 'uncaught_exception');\n };\n const unhandledRejection = (reason: unknown): void => {\n this.captureFatalProcessException(reason, 'unhandled_rejection');\n };\n this.processExceptionHandlers = { uncaughtException, unhandledRejection };\n process.on('uncaughtException', uncaughtException);\n process.on('unhandledRejection', unhandledRejection);\n }\n\n private captureFatalProcessException(\n error: unknown,\n action: Extract<TelemetryExceptionAction, 'uncaught_exception' | 'unhandled_rejection'>,\n ): void {\n if (this.fatalExceptionInFlight) return;\n this.fatalExceptionInFlight = true;\n process.exitCode = 1;\n try {\n const detail = error instanceof Error\n ? error.stack ?? `${error.name}: ${error.message}`\n : inspect(error);\n process.stderr.write(`${detail}\\n`);\n } catch {\n // Local logging failure must not prevent the bounded fatal flush and exit.\n }\n this.captureException(error, { action });\n void this.shutdown().finally(() => {\n const exit = this.options.fatalProcessExit ?? process.exit;\n exit(1);\n });\n }\n\n private detachProcessExceptionHandlers(): void {\n const handlers = this.processExceptionHandlers;\n if (!handlers) return;\n process.off('uncaughtException', handlers.uncaughtException);\n process.off('unhandledRejection', handlers.unhandledRejection);\n this.processExceptionHandlers = undefined;\n }\n\n private getClient(): PostHog | undefined {\n let enabled = false;\n try {\n enabled = !telemetryBlockedForProcess() && resolveTelemetryEnabled();\n } catch {\n // A configuration read failure must fail closed.\n }\n\n if (!enabled) {\n void this.shutdown();\n return undefined;\n }\n if (this.client) return this.client;\n\n try {\n this.client = new PostHog(\n process.env.POSTHOG_API_KEY ?? DEFAULT_POSTHOG_API_KEY,\n {\n host: process.env.POSTHOG_HOST ?? DEFAULT_POSTHOG_HOST,\n enableExceptionAutocapture: false,\n },\n );\n this.attachProcessExceptionHandlers();\n return this.client;\n } catch {\n return undefined;\n }\n }\n}\n\nexport function setAnalyticsClientTypeForProcess(clientType: AnalyticsClientType): void {\n processAnalyticsClientType = clientType;\n}\n\nexport function getAnalyticsClientTypeForProcess(): AnalyticsClientType {\n return processAnalyticsClientType;\n}\n\nexport function getAnalyticsService(clientType: AnalyticsClientType): AnalyticsService {\n const existing = sharedAnalyticsServices.get(clientType);\n if (existing) return existing;\n\n const analytics = new AnalyticsService(clientType, {\n captureProcessExceptions: clientType === 'server',\n });\n sharedAnalyticsServices.set(clientType, analytics);\n return analytics;\n}\n\nexport function trackAnalyticsTask<Task extends Promise<unknown>>(task: Task): Task {\n pendingAnalyticsTasks.add(task);\n const remove = (): void => { pendingAnalyticsTasks.delete(task); };\n void task.then(remove, remove);\n return task;\n}\n\nasync function waitForPendingAnalyticsTasks(timeoutMs: number): Promise<void> {\n if (pendingAnalyticsTasks.size === 0 || timeoutMs <= 0) return;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n Promise.allSettled([...pendingAnalyticsTasks]),\n new Promise<void>((resolve) => {\n timeout = setTimeout(resolve, timeoutMs);\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\nexport async function shutdownAnalyticsServices(): Promise<void> {\n const deadline = Date.now() + SHUTDOWN_TIMEOUT_MS;\n await waitForPendingAnalyticsTasks(SHUTDOWN_TIMEOUT_MS);\n const remainingMs = Math.max(0, deadline - Date.now());\n await Promise.all(\n [...sharedAnalyticsServices.values()].map((analytics) =>\n analytics.shutdown(remainingMs)),\n );\n}\n\nexport async function synchronizeAnalyticsServices(): Promise<void> {\n let enabled = false;\n try {\n enabled = resolveTelemetryEnabled();\n } catch {\n // A configuration read failure must fail closed.\n }\n if (enabled) return;\n await shutdownAnalyticsServices();\n}\n","import type {\n Harness,\n PipelineStageChangedProperties,\n TelemetryModelFamily,\n} from '@overdeck/contracts';\nimport {\n readPipelineTelemetryAgentState,\n type PipelineTelemetryAgentState,\n} from './pipeline-agent-reader.js';\nimport {\n getAnalyticsClientTypeForProcess,\n getAnalyticsService,\n trackAnalyticsTask,\n} from './service.js';\nconst HARNESSES = new Set<Harness>(['claude-code', 'ohmypi', 'codex', 'acp', 'kimi-code', 'opencode', 'muse']);\n\nexport interface PipelineTelemetryContext {\n harness: Harness;\n model: TelemetryModelFamily;\n}\n\ntype PipelineMembershipReader = (issueId: string) => Promise<boolean>;\n\nasync function readCanonicalPipelineMembership(issueId: string): Promise<boolean> {\n const [membershipModule, gatherModule, recordModule] = await Promise.all([\n import('../pipeline-membership.js'),\n import('../pipeline-membership-gather.js'),\n import('../pan-dir/record.js'),\n ]);\n const project = recordModule.resolveProjectForIssue(issueId);\n if (!project) return false;\n const signals = await gatherModule.gatherProjectLensSignals(project);\n const issueSignals = signals.find(\n (candidate) => candidate.issueId.toUpperCase() === issueId.toUpperCase(),\n );\n return issueSignals\n ? membershipModule.resolvePipelineMembership(issueSignals).inPipeline\n : false;\n}\n\nexport function toTelemetryModelFamily(model: string): TelemetryModelFamily {\n const normalized = model.toLowerCase();\n if (normalized.includes('claude')) return 'claude';\n if (normalized.includes('gpt') || /^o\\d/.test(normalized)) return 'gpt';\n if (normalized.includes('gemini')) return 'gemini';\n if (normalized.includes('kimi')) return 'kimi';\n if (normalized.includes('minimax')) return 'minimax';\n if (normalized.includes('glm')) return 'glm';\n if (normalized.includes('mimo')) return 'mimo';\n return 'other';\n}\n\nexport async function resolvePipelineTelemetryContext(\n issueId: string,\n readAgent: (agentId: string) => PipelineTelemetryAgentState | null = readPipelineTelemetryAgentState,\n readMembership: PipelineMembershipReader = readCanonicalPipelineMembership,\n): Promise<PipelineTelemetryContext | null> {\n if (!await readMembership(issueId)) return null;\n const state = readAgent(`agent-${issueId.toLowerCase()}`);\n if (\n !state?.harness ||\n !HARNESSES.has(state.harness) ||\n typeof state.model !== 'string' ||\n state.model.trim().length === 0\n ) return null;\n return {\n harness: state.harness,\n model: toTelemetryModelFamily(state.model),\n };\n}\n\nexport function capturePipelineStage(\n stage: PipelineStageChangedProperties['stage'],\n context: PipelineTelemetryContext | null,\n analytics: {\n capture: (\n event: 'pipeline_stage_changed',\n properties: PipelineStageChangedProperties,\n ) => void;\n } = getAnalyticsService(getAnalyticsClientTypeForProcess()),\n): void {\n if (!context) return;\n try {\n analytics.capture('pipeline_stage_changed', { stage, ...context });\n } catch {\n // Telemetry must never affect a pipeline transition.\n }\n}\n\nexport function capturePipelineStageForIssue(\n issueId: string,\n stage: PipelineStageChangedProperties['stage'],\n): Promise<void> {\n return trackAnalyticsTask((async () => {\n try {\n capturePipelineStage(stage, await resolvePipelineTelemetryContext(issueId));\n } catch {\n // Membership and agent context are best-effort and must not affect the transition.\n }\n })());\n}\n","interface ReviewGuardStatus {\n stuck?: boolean;\n stuckReason?: string;\n stuckAt?: string;\n stuckDetails?: string;\n reviewedAtCommit?: string;\n lastVerifiedCommit?: string;\n}\n\ninterface ReviewGuardUpdate {\n reviewStatus?: string;\n testStatus?: string;\n reviewedAtCommit?: string;\n lastVerifiedCommit?: string;\n}\n\ntype StuckFields = Pick<ReviewGuardStatus, 'stuck' | 'stuckReason' | 'stuckAt' | 'stuckDetails'>;\n\nexport function clearSupersededReviewInfrastructureFailure(\n status: ReviewGuardStatus | null,\n): Partial<StuckFields> {\n if (status?.stuckReason !== 'review_infrastructure_failure') return {};\n return {\n stuck: false,\n stuckReason: undefined,\n stuckAt: undefined,\n stuckDetails: undefined,\n };\n}\n\ninterface VerdictEvidenceHeadMismatch {\n gate: 'review' | 'test';\n evidenceHead: string;\n targetHead: string;\n}\n\nfunction findVerdictEvidenceHeadMismatch(\n status: ReviewGuardStatus,\n update: ReviewGuardUpdate,\n): VerdictEvidenceHeadMismatch | null {\n const terminalTest = update.testStatus !== undefined\n && ['passed', 'failed'].includes(update.testStatus);\n if (\n terminalTest\n && update.lastVerifiedCommit\n && status.reviewedAtCommit\n && update.lastVerifiedCommit !== status.reviewedAtCommit\n ) {\n return { gate: 'test', evidenceHead: update.lastVerifiedCommit, targetHead: status.reviewedAtCommit };\n }\n return null;\n}\n\nexport function rejectVerdictEvidenceHeadMismatch(\n issueId: string,\n status: ReviewGuardStatus,\n update: ReviewGuardUpdate,\n onReject: () => void,\n): boolean {\n const mismatch = findVerdictEvidenceHeadMismatch(status, update);\n if (!mismatch) return false;\n console.warn(\n `[review-status] Rejecting ${mismatch.gate} verdict for ${issueId}: `\n + `evidence HEAD ${mismatch.evidenceHead} does not match target HEAD ${mismatch.targetHead}.`,\n );\n onReject();\n return true;\n}\n","import { join } from 'path';\nimport { homedir } from 'os';\nimport { Data, Effect } from 'effect';\nimport { notifyPipelineSync } from './pipeline-notifier.js';\nimport { emitActivityEntrySync, emitActivityTtsSync } from './activity-logger.js';\nimport {\n upsertReviewStatusSync as dbUpsert,\n deleteReviewStatus as dbDelete,\n getReviewStatusFromDbSync,\n getAllReviewStatusesFromDb,\n getReviewStatusesFromDb,\n markWorkspaceStuck as dbMarkStuck,\n clearWorkspaceStuck as dbClearStuck,\n clearWorkspaceStuckAndResetHistory as dbClearStuckAndResetHistory,\n} from './overdeck/review-status-sync.js';\nimport {\n registerCanonicalReviewStatusResolver,\n registerReviewStatusMapReader,\n} from './cloister/review-status-source.js';\nimport { normalizeReviewStatusSync } from './review-status-normalize.js';\nimport { updateIssueRecordForReviewStatusSync, readJournalStatusSync } from './overdeck/review-status-record-sync.js';\nimport { carriesNewTerminalVerdict } from './pan-dir/pipeline-verdict-merge.js';\nimport {\n reviewGatesPassedSync,\n verificationSatisfied, settleMergedVerification,\n type BlockerReason, type ReviewStatus, type StatusHistoryEntry,\n} from './review-status-reconcile.js';\nimport { isReviewRequestStale, needsReviewDispatch } from './review-dispatch-decision.js';\nimport { REVIEW_STATUS_HISTORY_LIMIT } from './review-status-reconcile.js';\nimport { truncateReviewStatusNote } from './review-status-limits.js';\nimport { resolveJournalReconciledReviewStatusSync } from './review-status-read.js';\nimport { capturePipelineStageForIssue } from './telemetry/pipeline.js';\nimport type { ReviewStatusUpdate } from './workspace-anchor-drift.js';\nimport type { HeadAnchor } from './git-utils.js';\nimport { rejectVerdictEvidenceHeadMismatch } from './review-verdict-guards.js';\nimport { registerVerdictPreservationStatusReader, registerWorkStartVerdictAdapter } from './cloister/work-start-verdicts.js';\n\nexport { reviewGatesPassedSync, verificationSatisfied, MERGED_VERIFICATION_REASON } from './review-status-reconcile.js';\nexport type { BlockerReason, ReviewStatus, StatusHistoryEntry } from './review-status-reconcile.js';\nexport type { ReviewStatusUpdate } from './workspace-anchor-drift.js';\n\nexport interface MergeGateEligibility {\n eligible: boolean;\n reason?: string;\n}\n\n/**\n * Authoritative \"allowed to merge\" predicate (PAN-1759). The flywheel\n * orchestrator's pipeline verb says it INTENDS to merge an issue; this record\n * says the pipeline ALLOWS it. Both must hold before an issue enters the merge\n * queue or a UAT batch — RUN-20 tagged a mid-review issue with a merge verb\n * and it rode into a promotable batch. Same criteria as the\n * fixStuckReadyForMerge repair sweep: review passed, test passed/skipped,\n * verification not failed, not already merged.\n */\nexport function mergeGateEligibility(\n status: Pick<ReviewStatus, 'reviewStatus' | 'testStatus' | 'verificationStatus' | 'mergeStatus' | 'retiredAt'> | null,\n): MergeGateEligibility {\n if (!status) return { eligible: false, reason: 'no review record' };\n if (status.retiredAt) return { eligible: false, reason: 'retired' };\n if (status.reviewStatus !== 'passed' && status.reviewStatus !== 'skipped') {\n return { eligible: false, reason: `review is ${status.reviewStatus}` };\n }\n if (status.testStatus !== 'passed' && status.testStatus !== 'skipped') {\n return { eligible: false, reason: `test is ${status.testStatus}` };\n }\n if (!verificationSatisfied(status)) return { eligible: false, reason: 'verification failed' };\n if (status.mergeStatus === 'merged') return { eligible: false, reason: 'already merged' };\n return { eligible: true };\n}\n// PAN-2579: register the cycle-free status-map reader used by concurrency.ts for\n// warm-idle advancing classification (see cloister/review-status-source.ts).\nregisterReviewStatusMapReader(() => getAllReviewStatusesFromDb());\nregisterCanonicalReviewStatusResolver((issueId) => getReviewStatusSync(issueId));\nregisterVerdictPreservationStatusReader((issueId) => { const status = getReviewStatusSync(issueId); return status ? { ...status, reviewedAtCommit: status.reviewedAtCommit as HeadAnchor | undefined } : null; });\nregisterWorkStartVerdictAdapter({ refreshReviewedAnchor: (issueId, anchor) => setReviewStatusSync(issueId, { reviewedAtCommit: anchor }), resetPipelineVerdicts: (issueId) => resetPipelineVerdictsForWorkStartSync(issueId) !== null });\n\nconst DEFAULT_STATUS_FILE = join(homedir(), '.overdeck', 'review-status.json');\n\nexport function loadReviewStatuses(filePath = DEFAULT_STATUS_FILE): Record<string, ReviewStatus> {\n // SQLite is the authoritative store for the default (server) path.\n // Non-default JSON paths have been moved to review-status-json.ts so that\n // dashboard-reachable code never imports sync FS operations.\n if (filePath !== DEFAULT_STATUS_FILE) {\n throw new Error(\n `Non-default review-status paths are not supported in review-status.ts. ` +\n `Import from review-status-json.ts for JSON file operations.`\n );\n }\n return getAllReviewStatusesFromDb();\n}\n\nexport function loadReviewStatusesForIssues(issueIds: string[]): Record<string, ReviewStatus> {\n return getReviewStatusesFromDb(issueIds);\n}\n\nexport function loadReadyForMergeFlags(issueIds: string[]): Map<string, boolean> {\n const normalizedIds = [...new Set(issueIds.map((id) => id.toUpperCase()).filter(Boolean))];\n const dbStatuses = loadReviewStatusesForIssues(normalizedIds);\n const flags = new Map<string, boolean>();\n\n for (const issueId of normalizedIds) {\n const dbStatus = dbStatuses[issueId] ?? null;\n const journal = readJournalStatusSync(issueId);\n let status = dbStatus;\n\n if (journal) {\n if ((journal.durable as { closedOut?: boolean }).closedOut === true) {\n flags.set(issueId, false);\n continue;\n }\n\n if (!dbStatus || (dbStatus.updatedAt ?? '') < journal.updatedAt) {\n const merged: ReviewStatus = {\n ...(dbStatus ?? {\n issueId,\n reviewStatus: 'pending' as const,\n testStatus: 'pending' as const,\n updatedAt: journal.updatedAt,\n readyForMerge: false,\n }),\n };\n for (const [key, value] of Object.entries(journal.durable)) if (value !== undefined) (merged as unknown as Record<string, unknown>)[key] = value;\n for (const key of journal.clearedFields ?? []) delete (merged as unknown as Record<string, unknown>)[key];\n merged.issueId = issueId;\n merged.updatedAt = journal.updatedAt;\n const hasBlockers = (merged.blockerReasons?.length ?? 0) > 0;\n merged.readyForMerge = merged.retiredAt || hasBlockers ? false : reviewGatesPassedSync(merged);\n status = normalizeReviewStatusSync(merged);\n }\n }\n\n flags.set(issueId, status?.readyForMerge ?? false);\n }\n\n return flags;\n}\n\nexport function saveReviewStatuses(statuses: Record<string, ReviewStatus>, filePath = DEFAULT_STATUS_FILE): void {\n // SQLite is the authoritative store for the default (server) path.\n // Mirrors the old JSON overwrite semantics: upsert every entry in the map and\n // delete any SQLite rows whose keys are absent from the map (replace-all).\n if (filePath !== DEFAULT_STATUS_FILE) {\n throw new Error(\n `Non-default review-status paths are not supported in review-status.ts. ` +\n `Import from review-status-json.ts for JSON file operations.`\n );\n }\n const incoming = new Set(Object.keys(statuses));\n const existing = getAllReviewStatusesFromDb();\n for (const id of Object.keys(existing)) {\n if (!incoming.has(id)) {\n dbDelete(id);\n }\n }\n for (const status of Object.values(statuses)) {\n dbUpsert(status);\n }\n}\n\nexport function setReviewStatusSync(\n issueId: string,\n update: ReviewStatusUpdate,\n existing?: ReviewStatus,\n): ReviewStatus {\n // Guard: bare numeric IDs (no alphabetic prefix) must never reach the DB.\n // They would create orphaned rows that pollute pending lists and metrics.\n if (/^\\d+$/.test(issueId)) {\n console.warn(\n `[review-status] Rejecting setReviewStatus for bare numeric ID \"${issueId}\" — ` +\n `issue IDs must include a project prefix (e.g. PAN-${issueId}).`\n );\n return {\n issueId,\n reviewStatus: 'pending' as const,\n testStatus: 'pending' as const,\n updatedAt: new Date().toISOString(),\n readyForMerge: false,\n };\n }\n\n issueId = issueId.toUpperCase();\n\n // Read only the single row we're updating (avoids TOCTOU: bulk read-modify-write\n // races when two concurrent calls for different issue IDs run concurrently).\n // If `existing` is provided (e.g. from mutateBlockers), skip the read to\n // avoid double-read on the webhook ingestion path (PAN-905).\n // PAN-1988: the merge base goes through getReviewStatusSync (journal-reconciled +\n // notes-enriched), NOT the raw DB read. Otherwise a partial update (e.g. a testStatus\n // change carrying no review notes) would merge against a DB row whose notes/flags lag\n // the journal and silently erase the journal's feedback. A write triggered by reconciliation\n // must pass that reconciled status as `existing` so it does not recurse through this read.\n const status: ReviewStatus = existing ?? getReviewStatusSync(issueId) ?? {\n issueId,\n reviewStatus: 'pending' as const,\n testStatus: 'pending' as const,\n updatedAt: new Date().toISOString(),\n readyForMerge: false,\n };\n\n if (rejectVerdictEvidenceHeadMismatch(\n issueId, status, update, () => notifyPipelineSync({ type: 'status_changed', issueId, status }),\n )) return status;\n\n // Guard: reject reviewStatus regression from 'passed' to 'reviewing' unless the caller\n // is explicitly resetting the merge lifecycle (update includes mergeStatus).\n // This is belt-and-suspenders — endpoint-level guards should catch this first.\n if (update.reviewStatus === 'reviewing' && status.reviewStatus === 'passed' && update.mergeStatus === undefined) {\n console.warn(`[review-status] Rejecting reviewStatus regression from 'passed' to 'reviewing' for ${issueId} (mergeStatus not being reset)`);\n notifyPipelineSync({ type: 'status_changed', issueId, status: status as ReviewStatus });\n return status as ReviewStatus;\n }\n\n // PAN-2578: a bare 'reviewing' write must never clobber a terminal blocked/failed verdict.\n // A review agent can finish FASTER than the dispatch path that spawned it (PAN-399: the\n // verification gate completed 2 minutes after the agent recorded BLOCKED, and the dispatch\n // route's redundant `{ reviewStatus: 'reviewing' }` write destroyed the verdict in both the\n // DB and the journal). Blocked/failed → reviewing is legal ONLY when the caller explicitly\n // starts a NEW review cycle by carrying reviewSpawnedAt (spawnReviewRoleForIssue does).\n if (\n update.reviewStatus === 'reviewing' &&\n (status.reviewStatus === 'blocked' || status.reviewStatus === 'failed') &&\n update.reviewSpawnedAt === undefined\n ) {\n console.warn(\n `[review-status] Rejecting stale 'reviewing' write for ${issueId} — a terminal ` +\n `'${status.reviewStatus}' verdict is already recorded for this review cycle. Only a ` +\n `new dispatch (carrying reviewSpawnedAt) may re-enter 'reviewing'.`\n );\n notifyPipelineSync({ type: 'status_changed', issueId, status: status as ReviewStatus });\n return status as ReviewStatus;\n }\n\n // PAN-424: Reject testStatus regression from 'passed' to 'dispatch_failed' or 'failed'.\n // Once tests pass, duplicate dispatch failures must not overwrite the result.\n if (\n (update.testStatus === 'dispatch_failed' || update.testStatus === 'failed') &&\n status.testStatus === 'passed'\n ) {\n console.warn(`[review-status] Rejecting testStatus regression from 'passed' to '${update.testStatus}' for ${issueId}`);\n delete update.testStatus;\n delete update.testNotes;\n }\n\n const freshPrIdentity =\n (update.prNumber !== undefined && update.prNumber !== status.prNumber)\n || (update.prUrl !== undefined && update.prUrl !== status.prUrl);\n const merged = settleMergedVerification({ ...status, ...update });\n if (freshPrIdentity) merged.retiredAt = undefined;\n\n // Terminal verdicts consume the request that spawned this review. Preserve a newer request\n // because it represents an explicit re-review requested while the current review was running.\n const terminalReviewVerdict = update.reviewStatus !== status.reviewStatus &&\n ['passed', 'blocked', 'failed', 'skipped'].includes(update.reviewStatus ?? '');\n if (terminalReviewVerdict && merged.reviewRequestedAt &&\n (!merged.reviewSpawnedAt || Date.parse(merged.reviewRequestedAt) <= new Date(merged.reviewSpawnedAt).getTime())) {\n merged.reviewRequestedAt = undefined;\n }\n\n // Track status transitions in history — preserve raw notes for database storage (PAN-3253)\n // rawHistory starts with the already-hydrated bounded tail and receives one new transition\n // Truncation happens at hydration time and in event payloads, not here at composition.\n const now = new Date().toISOString();\n const rawHistory = [...(status.history || [])];\n if (update.reviewStatus && update.reviewStatus !== status.reviewStatus) {\n rawHistory.push({ type: 'review', status: update.reviewStatus, timestamp: now, ...(update.reviewNotes ? { notes: update.reviewNotes } : {}) });\n }\n if (update.testStatus && update.testStatus !== status.testStatus) {\n rawHistory.push({ type: 'test', status: update.testStatus, timestamp: now, ...(update.testNotes ? { notes: update.testNotes } : {}) });\n }\n if (update.uatStatus && update.uatStatus !== status.uatStatus) {\n rawHistory.push({ type: 'uat', status: update.uatStatus, timestamp: now, ...(update.uatNotes ? { notes: update.uatNotes } : {}) });\n }\n if (update.mergeStatus && update.mergeStatus !== status.mergeStatus) {\n rawHistory.push({ type: 'merge', status: update.mergeStatus, timestamp: now });\n }\n if (update.releaseStatus && update.releaseStatus !== status.releaseStatus) {\n rawHistory.push({ type: 'release', status: update.releaseStatus, timestamp: now, ...(update.releaseNotes ? { notes: update.releaseNotes } : {}) });\n }\n // Hydration bounds raw history before it reaches event payloads.\n\n // readyForMerge is event-driven and derived from gate state on every\n // write, so it flips the instant review+test+verification pass instead of waiting\n // for a deacon patrol or a startup `fixStuckReadyForMerge` reconcile (those become\n // redundant safety nets). This supersedes the PAN-1048 explicit-only model.\n //\n // Deriving from gates here does NOT bypass the \"rebased onto main + verified\"\n // guarantee: `triggerMerge()` performs the authoritative post-rebase quality gate\n // before it actually merges (see verificationSatisfied's note). The gate predicate\n // mirrors `fixStuckReadyForMerge` so behaviour is identical — just immediate.\n //\n // Explicit caller intent still wins (the merge flow sets readyForMerge=false when a\n // merge starts; mergeStatus then leaves pending/queued so the derive agrees).\n // PAN-905/PAN-3365: merge blockers and failed required UAT override explicit readiness.\n const hasBlockers = Boolean(merged.retiredAt) || (merged.blockerReasons?.length ?? 0) > 0 || merged.uatStatus === 'failed';\n const readyForMerge = hasBlockers\n ? false\n : (update.readyForMerge !== undefined\n ? update.readyForMerge\n : reviewGatesPassedSync(merged));\n\n const boundedHistory = rawHistory.slice(-REVIEW_STATUS_HISTORY_LIMIT).map((entry) => ({\n ...entry,\n notes: entry.notes ? truncateReviewStatusNote(entry.notes) : undefined,\n }));\n\n const dbStatus = normalizeReviewStatusSync({\n ...merged,\n issueId,\n updatedAt: now,\n readyForMerge,\n history: rawHistory,\n });\n\n const updated: ReviewStatus = normalizeReviewStatusSync({\n ...merged,\n issueId,\n updatedAt: now,\n readyForMerge,\n history: boundedHistory, // Return bounded (truncated) history in the event payload\n });\n\n // Report commit statuses to GitHub when readyForMerge transitions to true (PAN-536)\n if (readyForMerge && !status.readyForMerge && !updated.retiredAt && updated.prUrl) {\n (async () => {\n try {\n const { isGitHubAppConfigured, reportCommitStatus } = await import('./github-app.js');\n if (!isGitHubAppConfigured()) return;\n const prMatch = updated.prUrl!.match(/github\\.com\\/([^/]+)\\/([^/]+)\\/pull/);\n if (!prMatch) return;\n const [, owner, repo] = prMatch;\n // Get HEAD SHA of the PR branch\n const { exec } = await import('child_process');\n const { promisify } = await import('util');\n const execAsync = promisify(exec);\n const { stdout } = await execAsync(\n `gh pr view ${updated.prUrl!.match(/\\/pull\\/(\\d+)/)?.[1]} --json headRefOid --jq .headRefOid`,\n { encoding: 'utf-8', timeout: 10000 }\n );\n const sha = stdout.trim();\n if (sha) {\n // overdeck/review is honest here — review just transitioned to readyForMerge.\n // The overdeck/tests status is posted separately at the actual test-completion\n // site (verification-runner success, test-agent POST in workspaces routes) so it\n // accurately reflects which commit was tested.\n await reportCommitStatus(owner, repo, sha, 'success', 'overdeck/review', 'Review passed');\n console.log(`[review-status] Reported overdeck/review for ${issueId} (${sha.slice(0, 8)})`);\n }\n } catch (err: any) {\n console.warn(`[review-status] Failed to report commit status: ${err.message}`);\n }\n })();\n }\n\n // PAN-1908 + PAN-1988: the journal record is the SOURCE OF TRUTH for the verdict; the SQLite\n // row is a rebuildable cache. Write the journal FIRST. Since PAN-2541 it lives in\n // ${OVERDECK_HOME}/state/<project>/records/ — unwritable in a sandbox, so the writer falls back\n // to <workspace>/.overdeck/pipeline-verdict.json (PAN-2583). Fire-and-forget: a short-lived CLI\n // MUST drain via flushReviewStatusJournalWrites() before exit (PAN-2689). No xBRIEF mirror (PAN-1124).\n // PAN-3092: a NEW terminal verdict is the write the agent cannot cheaply retry,\n // so it gets the journal writer's backoff instead of an immediate fallback drop.\n const verdictWrite = carriesNewTerminalVerdict(status as unknown as Record<string, unknown>, update);\n updateIssueRecordForReviewStatusSync(issueId, updated, { verdictWrite });\n\n // The DB cache write is best-effort. A sandboxed agent's write throws SQLITE_READONLY, but\n // the verdict is already durable in the journal above, and the host reconciles the cache on\n // read (getReviewStatusSync's journal→DB reconcile). Tolerating this is what removes the\n // sandbox-escalation \"smoke and mirrors\" — the agent never has to break out of its jail to\n // record a verdict.\n // Write the raw (full) history to the database for archival (PAN-3253)\n try {\n dbUpsert(dbStatus);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.warn(`[review-status] DB cache write skipped for ${issueId} (${msg}); journal holds the verdict, host will reconcile on read.`);\n }\n\n notifyPipelineSync({ type: 'status_changed', issueId, status: updated });\n\n // Emit activity log entries for meaningful pipeline state transitions.\n // Each transition produces one entry so the ActivityPanel shows live pipeline progress.\n if (update.verificationStatus && update.verificationStatus !== status.verificationStatus) {\n const vMap: Record<string, { level: 'info' | 'warn' | 'error' | 'success'; msg: string; tts?: string; ttsPriority?: number }> = {\n running: { level: 'info', msg: `${issueId} — verification running`, tts: `${issueId} verification running` },\n passed: { level: 'success', msg: `${issueId} — verification passed`, tts: `${issueId} verification passed` },\n failed: { level: 'error', msg: `${issueId} — verification failed`, tts: `${issueId} verification failed` },\n skipped: { level: 'info', msg: `${issueId} — verification skipped`, tts: `${issueId} verification skipped`, ttsPriority: 2 },\n };\n const entry = vMap[update.verificationStatus];\n if (entry) emitActivityEntrySync({ source: 'cloister', level: entry.level, message: entry.msg, details: update.verificationNotes, issueId });\n if (entry?.tts) emitActivityTtsSync({\n utterance: entry.tts,\n priority: entry.ttsPriority ?? (entry.level === 'error' ? 0 : 1),\n issueId,\n source: 'cloister',\n eventType: `verificationStatus.${update.verificationStatus}`,\n });\n }\n if (update.reviewStatus && update.reviewStatus !== status.reviewStatus) {\n if (update.reviewStatus === 'passed') void capturePipelineStageForIssue(issueId, 'review_passed');\n let reviewMsg = `${issueId} — review started`;\n if (update.reviewStatus === 'reviewing') {\n const retryCount = updated.reviewRetryCount ?? 0;\n reviewMsg = retryCount > 0\n ? `${issueId} — review re-dispatched (retry ${retryCount})`\n : `${issueId} — review started`;\n }\n const rMap: Record<string, { level: 'info' | 'warn' | 'error' | 'success'; msg: string; tts?: string }> = {\n reviewing: { level: 'info', msg: reviewMsg, tts: `${issueId} review started` },\n passed: { level: 'success', msg: `${issueId} — review passed`, tts: `${issueId} review passed` },\n failed: { level: 'error', msg: `${issueId} — review failed`, tts: `${issueId} review failed` },\n blocked: { level: 'warn', msg: `${issueId} — review blocked (changes requested)`, tts: `${issueId} review blocked` },\n };\n const entry = rMap[update.reviewStatus];\n if (entry) emitActivityEntrySync({ source: 'review', level: entry.level, message: entry.msg, details: update.reviewNotes, issueId });\n if (entry?.tts) emitActivityTtsSync({\n utterance: entry.tts,\n priority: entry.level === 'error' ? 0 : 1,\n issueId,\n source: 'review-specialist',\n eventType: `reviewStatus.${update.reviewStatus}`,\n });\n }\n if (update.testStatus && update.testStatus !== status.testStatus) {\n const tMap: Record<string, { level: 'info' | 'warn' | 'error' | 'success'; msg: string; tts?: string; ttsPriority?: number }> = {\n testing: { level: 'info', msg: `${issueId} — tests running`, tts: `${issueId} tests running`, ttsPriority: 2 },\n passed: { level: 'success', msg: `${issueId} — tests passed`, tts: `${issueId} tests passed` },\n failed: { level: 'error', msg: `${issueId} — tests failed`, tts: `${issueId} tests failed` },\n skipped: { level: 'info', msg: `${issueId} — tests skipped`, tts: `${issueId} tests skipped`, ttsPriority: 2 },\n dispatch_failed: { level: 'warn', msg: `${issueId} — test dispatch failed`, tts: `${issueId} test dispatch failed`, ttsPriority: 1 },\n };\n const entry = tMap[update.testStatus];\n if (entry) emitActivityEntrySync({ source: 'test', level: entry.level, message: entry.msg, details: update.testNotes, issueId });\n if (entry?.tts) emitActivityTtsSync({\n utterance: entry.tts,\n priority: entry.ttsPriority ?? (entry.level === 'error' ? 0 : 1),\n issueId,\n source: 'test-specialist',\n eventType: `testStatus.${update.testStatus}`,\n });\n }\n if (update.mergeStatus && update.mergeStatus !== status.mergeStatus) {\n const mMap: Record<string, { level: 'info' | 'warn' | 'error' | 'success'; msg: string; tts?: string; ttsPriority?: number }> = {\n queued: { level: 'info', msg: `${issueId} — queued for merge`, tts: `${issueId} queued for merge`, ttsPriority: 2 },\n merging: { level: 'info', msg: `${issueId} — merge in progress`, tts: `${issueId} merge in progress`, ttsPriority: 2 },\n verifying: { level: 'info', msg: `${issueId} — post-merge verification`, tts: `${issueId} post-merge verification running`, ttsPriority: 2 },\n merged: { level: 'success', msg: `${issueId} — merged`, tts: `${issueId} merged to main` },\n failed: { level: 'error', msg: `${issueId} — merge failed`, tts: `${issueId} merge failed` },\n };\n const entry = mMap[update.mergeStatus];\n if (entry) emitActivityEntrySync({ source: 'ship', level: entry.level, message: entry.msg, details: update.mergeNotes, issueId });\n if (entry?.tts) emitActivityTtsSync({\n utterance: entry.tts,\n priority: entry.ttsPriority ?? (entry.level === 'error' ? 0 : 1),\n issueId,\n source: 'merge-agent',\n eventType: `mergeStatus.${update.mergeStatus}`,\n });\n }\n if (updated.readyForMerge && !status.readyForMerge) {\n emitActivityEntrySync({ source: 'cloister', level: 'success', message: `${issueId} — ready for merge`, issueId });\n emitActivityTtsSync({\n utterance: `${issueId} ready for merge`,\n priority: 1,\n issueId,\n source: 'cloister',\n eventType: 'readyForMerge',\n });\n }\n\n // Reactive Cloister owns review→test and test→ship scheduling. setReviewStatus\n // emits the lifecycle event here so API and direct-import callers share one path.\n // PAN-1862 (FR-14): reviewStatus 'skipped' (review mode none) advances the\n // lifecycle exactly like an approved review — same event, same downstream.\n if (\n (update.reviewStatus === 'passed' || update.reviewStatus === 'skipped') &&\n status.reviewStatus !== 'passed' && status.reviewStatus !== 'skipped' &&\n updated.testStatus === 'pending'\n ) {\n const canSkipTests =\n updated.reviewedAtCommit &&\n updated.lastVerifiedCommit &&\n updated.reviewedAtCommit === updated.lastVerifiedCommit;\n\n if (canSkipTests) {\n console.log(`[review-status] Skipping test role for ${issueId} — no code drift since verification (HEAD=${updated.reviewedAtCommit!.slice(0, 8)})`);\n emitActivityEntrySync({ source: 'cloister', level: 'info', message: `${issueId} — tests skipped (no code change since verification gate)`, issueId });\n setReviewStatusSync(issueId, {\n testStatus: 'passed',\n testNotes: 'Skipped: no code changed since pre-review verification gate',\n verificationStatus: 'passed',\n verificationNotes: 'Pre-review verification already covered the reviewed commit',\n });\n void emitReactiveLifecycleEvent('test.passed', issueId);\n } else {\n void emitReactiveLifecycleEvent('review.approved', issueId);\n }\n }\n\n if (update.testStatus === 'passed' && status.testStatus !== 'passed') {\n void emitReactiveLifecycleEvent('test.passed', issueId);\n }\n\n // PAN-1988: test FAILED → hand it straight back to the work agent (host-side). The dead-end\n // requeue that does this is deacon-only, so without this a failure strands until the (possibly\n // frozen) deacon nudges. Fires once per transition into failed — both the agent's direct POST and\n // the host's .pan/test/result.json recovery flow through this same transition.\n if (\n (update.testStatus === 'failed' || update.testStatus === 'dispatch_failed') &&\n status.testStatus !== 'failed' && status.testStatus !== 'dispatch_failed'\n ) {\n void deliverTestFailureToWorkAgentHostSide(issueId, updated);\n }\n\n // A UAT failure can enter through the REST route, specialist completion, or\n // deacon recovery. Route from this write door so every entry point reaches the\n // same feedback-target resurrection and needs-you escalation path.\n if (update.uatStatus === 'failed') {\n void deliverUatFailureToWorkAgentHostSide(issueId, updated);\n } else if (update.uatStatus) {\n void clearUatFailureAnchorHostSide(issueId);\n }\n\n return updated;\n}\n\nfunction emitReactiveLifecycleEvent(\n type: 'review.approved' | 'test.passed',\n issueId: string,\n): void {\n try {\n notifyPipelineSync({ type, issueId });\n } catch (error) {\n console.warn(`[review-status] Failed to emit ${type} for ${issueId}:`, error);\n }\n}\n\nexport type ReviewVerdictFeedbackDelivery = (\n issueId: string,\n status: ReviewStatus,\n) => Promise<void>;\n\nlet reviewVerdictFeedbackDelivery: ReviewVerdictFeedbackDelivery | null = null;\n\nexport function registerReviewVerdictFeedbackDelivery(\n delivery: ReviewVerdictFeedbackDelivery,\n): void {\n reviewVerdictFeedbackDelivery = delivery;\n}\n\nasync function deliverReviewVerdictFeedbackHostSide(\n issueId: string,\n status: ReviewStatus,\n): Promise<void> {\n if (!reviewVerdictFeedbackDelivery) {\n console.warn(`[review-status] review feedback delivery is not registered for ${issueId}; preserving durable feedback state for a host retry`);\n return;\n }\n try {\n await reviewVerdictFeedbackDelivery(issueId, status);\n } catch (err) {\n console.warn(`[review-status] host-side review feedback delivery for ${issueId} did not complete (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nconst reviewDispatchAttemptAt = new Map<string, number>();\nconst staleReviewRequestClearAttemptedAt = new Map<string, number>();\nconst REVIEW_AUTO_DISPATCH_THROTTLE_MS = 30_000;\nconst STRANDED_REVIEW_SPAWN_AGE_MS = 20 * 60_000;\nconst STRANDED_REDISPATCH_COOLDOWN_MS = 10 * 60_000;\nconst strandedReviewRedispatchAt = new Map<string, number>();\nlet loggedMissingPipelineHandler = false;\n\n/**\n * PAN-3674: a pending review whose dispatch already ran (reviewSpawnedAt set)\n * but produced no live reviewer sessions is stranded by a failed spawn — the\n * 2026-08-13 PAN-3668 incident sat like this for 5h while the dashboard showed\n * a benign 'Pending'. needsReviewDispatch stands down once spawnedAt covers the\n * request, so without this repair nothing ever retries.\n */\nfunction isStrandedPendingReview(status: ReviewStatus, now = Date.now()): boolean {\n if (status.reviewStatus !== 'pending') return false;\n if (status.readyForMerge === true || status.mergeStatus === 'merged') return false;\n // Verification must have passed — a pending row with failed or absent\n // verification waits on the work agent, not on a review re-dispatch.\n if (status.verificationStatus !== 'passed' && status.verificationStatus !== 'skipped') return false;\n const spawned = status.reviewSpawnedAt;\n if (spawned === undefined || spawned === null) return false;\n const spawnedMs = typeof spawned === 'number' ? spawned : Date.parse(spawned);\n if (!Number.isFinite(spawnedMs)) return false;\n return now - spawnedMs >= STRANDED_REVIEW_SPAWN_AGE_MS;\n}\n\n/** @internal Test-only export — the stranded predicate is the safety gate for the repair. */\nexport function _isStrandedPendingReviewForTest(status: ReviewStatus, now?: number): boolean {\n return isStrandedPendingReview(status, now);\n}\n\nfunction maybeRedispatchStrandedReviewHostSide(issueId: string, status: ReviewStatus): void {\n if (!isStrandedPendingReview(status)) return;\n const last = strandedReviewRedispatchAt.get(issueId) ?? 0;\n if (Date.now() - last < STRANDED_REDISPATCH_COOLDOWN_MS) return;\n strandedReviewRedispatchAt.set(issueId, Date.now());\n void redispatchStrandedReviewHostSide(issueId, status);\n}\n\nasync function redispatchStrandedReviewHostSide(issueId: string, status: ReviewStatus): Promise<void> {\n try {\n const { listSessions } = await import('./tmux.js');\n const { isReviewSessionForIssue } = await import('./cloister/specialists-registry.js');\n const sessions = await Effect.runPromise(listSessions()).catch(() => [] as readonly { name: string }[]);\n // A live reviewer session means the row — not the pipeline — is stale;\n // there is nothing to repair.\n if (sessions.some((s) => isReviewSessionForIssue(s.name, undefined, issueId))) return;\n const { resolveProjectFromIssueSync } = await import('./projects.js');\n const resolved = resolveProjectFromIssueSync(issueId);\n if (!resolved) return;\n const { existsSync } = await import('fs');\n const workspace = join(resolved.projectPath, 'workspaces', `feature-${issueId.toLowerCase()}`);\n if (!existsSync(workspace)) return;\n const { dispatchRegisteredReviewHostSide } = await import('./cloister/durable-review-pipeline.js');\n // Dispatch-only: verification already passed at this HEAD (the predicate\n // requires it), so the full pipeline's gate re-run would be pure waste.\n const result = await dispatchRegisteredReviewHostSide({\n issueId,\n workspace,\n branch: `feature/${issueId.toLowerCase()}`,\n ...(status.prUrl ? { prUrl: status.prUrl } : {}),\n });\n if (!result) return; // No dispatcher registered (CLI process) — stay silent.\n const message = result.success\n ? `${issueId} — stranded pending review re-dispatched after a failed spawn (PAN-3674): ${result.message ?? 'ok'}`\n : `${issueId} — stranded pending review re-dispatch failed (PAN-3674): ${result.error ?? result.message ?? 'unknown'}`;\n console.log(`[review-status] ${message}`);\n emitActivityEntrySync({ source: 'review', level: result.success ? 'info' : 'warn', issueId, message });\n } catch (err) {\n console.warn(`[review-status] stranded review re-dispatch for ${issueId} did not complete (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nfunction maybeAutoDispatchReviewHostSide(issueId: string, status: ReviewStatus): void {\n if (!needsReviewDispatch({\n reviewRequestedAt: status.reviewRequestedAt,\n reviewSpawnedAt: status.reviewSpawnedAt,\n reviewStatus: status.reviewStatus,\n mergeStatus: status.mergeStatus,\n readyForMerge: status.readyForMerge,\n })) {\n // PAN-3674: the dispatch gate has nothing to do, but a stale spawn with no\n // live reviewers means the last dispatch died — repair it.\n maybeRedispatchStrandedReviewHostSide(issueId, status);\n if (!isReviewRequestStale({ reviewRequestedAt: status.reviewRequestedAt }) ||\n staleReviewRequestClearAttemptedAt.has(issueId)) return;\n staleReviewRequestClearAttemptedAt.set(issueId, Date.now());\n try {\n setReviewStatusSync(issueId, { reviewRequestedAt: undefined }, status);\n const message = `${issueId} — cleared stale review request older than 7 days`;\n console.warn(`[review-status] ${message}`);\n emitActivityEntrySync({ source: 'cloister', level: 'warn', issueId, message });\n } catch {\n // Sandboxed read-only callers cannot repair durable state; a host process will retry.\n }\n return;\n }\n const last = reviewDispatchAttemptAt.get(issueId) ?? 0;\n if (Date.now() - last < REVIEW_AUTO_DISPATCH_THROTTLE_MS) return;\n reviewDispatchAttemptAt.set(issueId, Date.now());\n void dispatchReviewHostSide(issueId, status.prUrl);\n}\nexport async function dispatchReviewHostSide(issueId: string, prUrl?: string): Promise<void> {\n try {\n const {\n hasDurableReviewPipelineDispatch,\n startRegisteredDurableReviewPipelineHostSide,\n } = await import('./cloister/durable-review-pipeline.js');\n if (!hasDurableReviewPipelineDispatch()) {\n if (!loggedMissingPipelineHandler) {\n loggedMissingPipelineHandler = true;\n console.debug('[review-status] durable review pipeline handler is not registered; skipping host-side review auto-dispatch');\n }\n return;\n }\n const started = await startRegisteredDurableReviewPipelineHostSide({\n issueId,\n ...(prUrl ? { prUrl } : {}),\n setReviewPending: (update) => setReviewStatusSync(issueId, update),\n });\n if (!started) {\n console.log(`[review-status] durable review pipeline unavailable or already in flight for ${issueId} (host-side)`);\n }\n } catch (err) {\n console.warn(`[review-status] host-side review auto-dispatch for ${issueId} did not complete (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nconst testVerdictRecoveryAt = new Map<string, number>();\nconst TEST_VERDICT_RECOVERY_THROTTLE_MS = 60_000;\n\nfunction maybeRecoverTestVerdictHostSide(issueId: string, status: ReviewStatus): void {\n if (status.reviewStatus !== 'passed') return;\n if (status.mergeStatus === 'merged' || status.readyForMerge) return;\n if (status.testStatus !== 'testing' && status.testStatus !== 'pending' && status.testStatus !== 'dispatch_failed') return;\n const last = testVerdictRecoveryAt.get(issueId) ?? 0;\n if (Date.now() - last < TEST_VERDICT_RECOVERY_THROTTLE_MS) return;\n testVerdictRecoveryAt.set(issueId, Date.now());\n void recoverTestVerdictHostSide(issueId);\n}\n\nasync function recoverTestVerdictHostSide(issueId: string): Promise<void> {\n try {\n const { resolveProjectFromIssueSync } = await import('./projects.js');\n const resolved = resolveProjectFromIssueSync(issueId);\n if (!resolved) return;\n const { existsSync } = await import('fs');\n const workspace = join(resolved.projectPath, 'workspaces', `feature-${issueId.toLowerCase()}`);\n if (!existsSync(workspace)) return;\n const { readTestVerdictArtifact } = await import('./cloister/test-verdict.js');\n const artifact = readTestVerdictArtifact(workspace);\n if (!artifact) return;\n setReviewStatusSync(issueId, {\n testStatus: artifact.status,\n testNotes: artifact.notes ??\n `Recovered from .pan/test/result.json (${artifact.status}) — the test agent wrote the verdict but never signaled`,\n });\n console.log(`[review-status] recovered unsignaled test verdict for ${issueId}: ${artifact.status} (host-side, from .pan/test/result.json)`);\n } catch (err) {\n console.warn(`[review-status] host-side test verdict recovery for ${issueId} did not complete (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nexport function resetPipelineVerdictsForWorkStartSync(issueId: string, options: { force?: boolean } = {}): ReviewStatus | null {\n const status = getReviewStatusSync(issueId);\n if (!status) return null;\n const isPending =\n status.reviewStatus === 'pending' &&\n status.testStatus === 'pending' &&\n (status.mergeStatus === undefined || status.mergeStatus === 'pending') &&\n (status.verificationStatus === undefined || status.verificationStatus === 'pending') &&\n !status.readyForMerge &&\n status.autoRequeueCount === 0 &&\n status.verificationCycleCount === 0 &&\n status.reviewRetryCount === 0 &&\n status.testRetryCount === 0 &&\n status.mergeRetryCount === 0 &&\n status.recoveryStartedAt === undefined &&\n status.reviewedAtCommit === undefined &&\n status.lastVerifiedCommit === undefined;\n\n if (isPending && !options.force) return null;\n\n return setReviewStatusSync(issueId, {\n reviewStatus: 'pending',\n testStatus: 'pending',\n mergeStatus: 'pending',\n reviewNotes: undefined,\n testNotes: undefined,\n mergeNotes: undefined,\n readyForMerge: false,\n autoRequeueCount: 0,\n verificationStatus: 'pending',\n verificationNotes: undefined,\n verificationCycleCount: 0,\n stuck: false,\n stuckReason: undefined,\n stuckAt: undefined,\n stuckDetails: undefined,\n reviewRetryCount: 0,\n testRetryCount: 0,\n mergeRetryCount: 0,\n recoveryStartedAt: undefined,\n reviewedAtCommit: undefined,\n lastVerifiedCommit: undefined,\n reviewRequestedAt: undefined, reviewSpawnedAt: undefined,\n conflictResolutionDispatchedAt: undefined, blockerReasons: undefined,\n retiredAt: undefined,\n });\n}\n\nasync function deliverUatFailureToWorkAgentHostSide(issueId: string, status: ReviewStatus): Promise<void> {\n try {\n const { relayUatFailureFeedbackPromise } = await import('./cloister/uat-failure-feedback.js');\n await relayUatFailureFeedbackPromise({\n issueId,\n uatNotes: status.uatNotes,\n anchor: status.reviewedAtCommit,\n });\n } catch (err) {\n console.warn(`[review-status] host-side UAT-failure delivery for ${issueId} did not complete (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nasync function clearUatFailureAnchorHostSide(issueId: string): Promise<void> {\n try {\n const { clearUatFailureFeedbackAnchor } = await import('./cloister/uat-failure-feedback.js');\n clearUatFailureFeedbackAnchor(issueId);\n } catch (err) {\n console.warn(`[review-status] host-side UAT-failure anchor clear for ${issueId} did not complete (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nasync function deliverTestFailureToWorkAgentHostSide(issueId: string, status: ReviewStatus): Promise<void> {\n try {\n const { resolveProjectFromIssueSync } = await import('./projects.js');\n const resolved = resolveProjectFromIssueSync(issueId);\n const workspace = resolved ? join(resolved.projectPath, 'workspaces', `feature-${issueId.toLowerCase()}`) : undefined;\n const notes = status.testNotes; let feedbackPath: string | undefined;\n try {\n const { writeFeedbackFile } = await import('./cloister/feedback-writer.js');\n const r = await Effect.runPromise(writeFeedbackFile({\n issueId, workspacePath: workspace, specialist: 'test-agent', outcome: 'failed', summary: `Tests FAILED for ${issueId}`,\n markdownBody: `# Test failure\\n\\n${notes ?? 'The test gate reported failures. See .pan/test/result.json and re-run the project test suite.'}\\n\\n## Required\\nFix the failing tests, commit and push, then re-run \\`pan done ${issueId}\\`.`,\n }));\n if (r.success) feedbackPath = r.filePath;\n } catch { /* non-fatal — the message below still carries the summary */ }\n\n const message = `SPECIALIST FEEDBACK: test-agent reported FAILED for ${issueId}.\\n\\n${feedbackPath ? `MUST READ: ${feedbackPath}\\n\\n` : ''}${notes ? `${notes.slice(0, 400)}\\n\\n` : ''}Fix the failing tests, commit and push, then re-run pan done ${issueId}. Do NOT stop at the prompt.`;\n const { resolveIssueFeedbackTarget, surfaceIssueFeedbackNeedsYou } = await import('./cloister/feedback-target.js');\n const target = await resolveIssueFeedbackTarget(issueId);\n if ('agentId' in target) {\n const { messageAgent } = await import('./agents.js');\n await messageAgent(target.agentId, message, 'internal', { owesRework: true });\n console.log(`[review-status] delivered test failure to ${target.agentId} for ${issueId} (host-side)`);\n } else {\n await surfaceIssueFeedbackNeedsYou(issueId, target.reason, { specialist: 'test-agent', feedbackPath });\n }\n } catch (err) {\n console.warn(`[review-status] host-side test-failure delivery for ${issueId} did not complete (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nfunction resolveReviewStatusSync(issueId: string, dbStatus: ReviewStatus | null | undefined): ReviewStatus | null {\n return resolveJournalReconciledReviewStatusSync(issueId, dbStatus, {\n deleteStatus: dbDelete,\n notifyStatusChanged: (id, status) => notifyPipelineSync({ type: 'status_changed', issueId: id, status }),\n deliverReviewVerdictFeedbackHostSide,\n emitReactiveLifecycleEvent,\n maybeAutoDispatchReviewHostSide,\n maybeRecoverTestVerdictHostSide,\n });\n}\n\nexport function getReviewStatusSync(issueId: string): ReviewStatus | null {\n return resolveReviewStatusSync(issueId, getReviewStatusFromDbSync(issueId));\n}\n\nexport function getReviewStatusesSync(issueIds: string[]): Record<string, ReviewStatus> {\n const ids = [...new Set(issueIds.map((issueId) => issueId.trim().toUpperCase()).filter(Boolean))];\n const dbStatuses = getReviewStatusesFromDb(ids);\n return Object.fromEntries(ids.flatMap((id) => {\n const status = resolveReviewStatusSync(id, dbStatuses[id]);\n return status ? [[id, status]] : [];\n }));\n}\n\n/**\n * On server startup, clear any mergeStatus stuck at 'merging'.\n * Pending merge operations are in-memory only — they don't survive a restart.\n * Any 'merging' status after boot is definitionally stuck (PAN-490).\n */\nexport function clearStuckMergeStatuses(): void {\n const statuses = loadReviewStatuses();\n // Don't clear 'queued' — the SQLite merge queue handles that (PAN-632).\n // Only clear truly stuck transient states.\n const stuck = Object.values(statuses).filter(s =>\n s.mergeStatus === 'merging' || s.mergeStatus === 'verifying'\n );\n if (stuck.length === 0) return;\n console.log(`[review-status] Clearing ${stuck.length} stuck merge status(es) on startup (merging/verifying)`);\n for (const s of stuck) {\n // Reset to pending so MERGE button reappears — the in-memory queue was lost on restart.\n // Preserve readyForMerge if review+test both passed — the merge just needs to be retried.\n const shouldBeReady =\n s.reviewStatus === 'passed' &&\n (s.testStatus === 'passed' || s.testStatus === 'skipped') &&\n verificationSatisfied(s) &&\n (s.uatStatus === undefined || s.uatStatus === 'passed');\n setReviewStatusSync(s.issueId, {\n mergeStatus: 'pending',\n ...(shouldBeReady ? { readyForMerge: true } : {}),\n });\n }\n}\n\n/**\n * Restore merge eligibility after a restart only when every gate passes and\n * canonical pipeline membership confirms that the issue still has an open PR.\n */\nexport async function fixStuckReadyForMerge(\n gatherEligibility?: typeof import('./cloister/merge-eligibility.js').gatherMergeEligibility,\n): Promise<void> {\n const statuses = loadReviewStatuses();\n const stuck = Object.values(statuses).filter(s =>\n !s.retiredAt &&\n s.readyForMerge === false &&\n s.reviewStatus === 'passed' &&\n (s.testStatus === 'passed' || s.testStatus === 'skipped') &&\n verificationSatisfied(s) &&\n // Failed and merged attempts are terminal; only pending/queued rows are repairable.\n (s.mergeStatus === 'pending' || s.mergeStatus === 'queued' || s.mergeStatus === undefined || s.mergeStatus === null) &&\n (s.uatStatus === undefined || s.uatStatus === 'passed')\n );\n if (stuck.length === 0) return;\n const mergeEligibility = await import('./cloister/merge-eligibility.js');\n const memberships = await (gatherEligibility ?? mergeEligibility.gatherMergeEligibility)(stuck.map((status) => status.issueId));\n console.log(`[review-status] Restoring readyForMerge for ${stuck.length} issue(s) with passed review+test`);\n for (const s of stuck) {\n const membership = memberships.get(s.issueId.toUpperCase());\n if (!membership || !mergeEligibility.isMergeEligible(membership)) {\n if (membership) setReviewStatusSync(s.issueId, { readyForMerge: false, retiredAt: new Date().toISOString() });\n console.log(`[review-status] skipping ${s.issueId} — pipeline membership is ${membership?.bucket ?? 'unavailable'}, not merge-eligible`);\n continue;\n }\n console.log(`[review-status] Restoring readyForMerge=true for ${s.issueId} (verif=${s.verificationStatus}, merge=${s.mergeStatus})`);\n setReviewStatusSync(s.issueId, { readyForMerge: true });\n }\n}\n\n/**\n * PAN-869: On server startup, fix any issues where reviewStatus was incorrectly\n * set to 'failed' due to the old COMMENTED → 'failed' mapping bug.\n *\n * This identifies records where:\n * - reviewStatus = 'failed'\n * - testStatus = 'passed' (CI green, so review wasn't genuinely bad)\n * - mergeStatus is not terminal ('merged', 'failed')\n * - readyForMerge = false\n * - The last review history entry is type='review', status='failed'\n *\n * The old reviewResultToReviewStatus() mapped COMMENTED (regardless of success)\n * to 'failed', so the history stores 'failed' for old COMMENTED reviews.\n * We use testStatus='passed' as the signal that this was a successful review\n * (CI was green), distinguishing it from genuinely failed reviews.\n */\nexport function fixStuckCommentedReviews(): void {\n const statuses = loadReviewStatuses();\n const candidates = Object.values(statuses).filter(s =>\n s.reviewStatus === 'failed' &&\n (s.testStatus === 'passed' || s.testStatus === 'skipped') &&\n s.mergeStatus !== 'merged' &&\n s.mergeStatus !== 'failed' &&\n s.readyForMerge === false &&\n s.verificationStatus !== 'failed'\n );\n\n if (candidates.length === 0) return;\n\n const toFix: string[] = [];\n for (const s of candidates) {\n // Check if the last review history entry is 'failed' (the old COMMENTED mapping\n // stored 'failed' in history). testStatus='passed' signals CI was green,\n // so this was a successful review incorrectly stored as 'failed'.\n const lastReviewEntry = [...(s.history || [])]\n .reverse()\n .find(h => h.type === 'review');\n if (lastReviewEntry?.status === 'failed') {\n toFix.push(s.issueId);\n }\n }\n\n if (toFix.length === 0) return;\n console.log(`[review-status] Restoring reviewStatus='passed' for ${toFix.length} issue(s) with COMMENTED reviews (PAN-869 backfill)`);\n for (const issueId of toFix) {\n console.log(`[review-status] Restoring reviewStatus='passed' for ${issueId}`);\n // reviewStatus='passed' will trigger readyForMerge recomputation in setReviewStatus\n setReviewStatusSync(issueId, { reviewStatus: 'passed' });\n }\n}\n\nexport function clearReviewStatus(issueId: string): void {\n // Terminal lifecycle owns removal of the UAT feedback dedup entry. The relay\n // stays dynamically imported to preserve the Node ESM boot graph.\n void clearUatFailureAnchorHostSide(issueId);\n try {\n dbDelete(issueId);\n } catch (err) {\n console.error('[review-status] SQLite delete failed:', err);\n }\n}\n\n// ============== Stuck state helpers (PAN-653) ==============\n\n/**\n * Mark a workspace as stuck with a reason and optional JSON details.\n * Persists across dashboard restarts. Deacon will skip stuck workspaces.\n *\n * @param issueId - Issue ID (e.g. \"PAN-653\")\n * @param reason - Short reason code (e.g. \"main_diverged\")\n * @param details - Optional structured details (e.g. {localSha, remoteSha})\n */\n// PAN-1988: `stuck` is EPHEMERAL runtime state (set when patrol detects a wedged workspace),\n// NOT a durable verdict — projectPipeline deliberately does not journal it, and it is rebuilt\n// from runtime on a cache rebuild. So markWorkspaceStuck/clearWorkspaceStuck write the DB cache\n// directly and do not go through the journal door. The getReviewStatusSync journal→DB reconcile\n// preserves it (a strict overlay that never clobbers DB-only fields the journal doesn't carry).\nexport function markWorkspaceStuck(\n issueId: string,\n reason: string,\n details?: Record<string, unknown>,\n): void {\n try {\n dbMarkStuck(issueId, reason, details);\n console.log(`[review-status] Marked ${issueId} as stuck: ${reason}`);\n const updated = getReviewStatusSync(issueId);\n if (updated) notifyPipelineSync({ type: 'status_changed', issueId, status: updated });\n } catch (err) {\n console.error(`[review-status] Failed to mark ${issueId} as stuck:`, err);\n }\n}\n\n/**\n * Clear the stuck flag for a workspace.\n * Called when the human clicks \"Unstick\" in the dashboard.\n * Re-enables Deacon patrol for this workspace.\n */\nexport function clearWorkspaceStuck(issueId: string): void {\n try {\n dbClearStuck(issueId);\n console.log(`[review-status] Cleared stuck state for ${issueId}`);\n const updated = getReviewStatusSync(issueId);\n if (updated) notifyPipelineSync({ type: 'status_changed', issueId, status: updated });\n } catch (err) {\n console.error(`[review-status] Failed to clear stuck state for ${issueId}:`, err);\n }\n}\n\n/** PAN-3151: clear stuck and reset review cycle history when unsticking from review-not-converging. */\nexport function clearWorkspaceStuckAndResetHistory(issueId: string): void {\n try {\n dbClearStuckAndResetHistory(issueId);\n console.log(`[review-status] Cleared stuck state and reset cycle history for ${issueId}`);\n const updated = getReviewStatusSync(issueId);\n if (updated) notifyPipelineSync({ type: 'status_changed', issueId, status: updated });\n } catch (err) {\n console.error(`[review-status] Failed to clear stuck state for ${issueId}:`, err);\n }\n}\n\n/** Stuck reason recorded when specialist feedback could not reach a live agent (feedback-target.ts). */\nexport const FEEDBACK_DELIVERY_STUCK_REASON = 'feedback_delivery_needs_you';\n\n/**\n * PAN-3074: clear a feedback-delivery stuck flag once the condition it recorded\n * no longer holds — the feedback reached a live agent, or the agent completed\n * the fix-and-resubmit loop (`pan review request`). Any other stuck reason is\n * operator territory and stays put.\n */\nexport function clearFeedbackDeliveryStuck(issueId: string): void {\n const status = getReviewStatusSync(issueId);\n if (status?.stuck !== true || status.stuckReason !== FEEDBACK_DELIVERY_STUCK_REASON) return;\n clearWorkspaceStuck(issueId);\n}\n\n/**\n * Set or clear the operator-requested deacon-ignore flag. When set, Deacon\n * patrol skips the issue entirely on every cycle. Distinct from `stuck`, which\n * is a system-set failure marker that also suppresses patrol.\n */\nexport function setDeaconIgnored(\n issueId: string,\n ignored: boolean,\n reason?: string,\n): void {\n try {\n // PAN-1988: route through the single write door. deaconIgnored is a DURABLE field that\n // projectPipeline journals — a DB-only write (the old dbSetDeaconIgnored) lands in the\n // cache but not the journal, so it vanishes on a cache rebuild. setReviewStatusSync writes\n // both (and emits the status_changed event), keeping DB and journal in sync.\n setReviewStatusSync(issueId, {\n deaconIgnored: ignored,\n deaconIgnoredAt: ignored ? new Date().toISOString() : undefined,\n deaconIgnoredReason: ignored ? reason : undefined,\n });\n console.log(`[review-status] deaconIgnored=${ignored} for ${issueId}${reason ? ` (${reason})` : ''}`);\n } catch (err) {\n console.error(`[review-status] Failed to set deaconIgnored for ${issueId}:`, err);\n }\n}\n\n/**\n * PAN-1691: set the per-issue auto-merge routing key and broadcast the change.\n * `autoMerge === null` clears it back to the project default. Emits a\n * status_changed pipeline event so open dashboards reflect the toggle live.\n */\nexport function setAutoMerge(issueId: string, autoMerge: boolean | null): void {\n try {\n // PAN-1988: route through the single write door. autoMerge is a DURABLE field journaled by\n // projectPipeline; a DB-only write would be lost on cache rebuild. `null` clears it back to\n // the project default (stored as undefined). setReviewStatusSync writes DB + journal and\n // emits the status_changed event.\n setReviewStatusSync(issueId, { autoMerge: autoMerge === null ? undefined : autoMerge });\n console.log(`[review-status] autoMerge=${autoMerge === null ? 'default' : autoMerge} for ${issueId}`);\n } catch (err) {\n console.error(`[review-status] Failed to set autoMerge for ${issueId}:`, err);\n }\n}\n\n/** Tagged error for review-status Effect variants. */\nexport class ReviewStatusError extends Data.TaggedError('ReviewStatusError')<{\n readonly issueId: string;\n readonly operation: string;\n readonly message: string;\n readonly cause?: unknown;\n}> {}\n\nexport const setReviewStatus = (\n issueId: string,\n update: ReviewStatusUpdate,\n existing?: ReviewStatus,\n): Effect.Effect<ReviewStatus, ReviewStatusError> =>\n Effect.tryPromise({\n try: () => new Promise<ReviewStatus>((resolve, reject) => {\n setImmediate(() => {\n try {\n resolve(setReviewStatusSync(issueId, update, existing));\n } catch (err) {\n reject(err);\n }\n });\n }),\n catch: (cause) =>\n new ReviewStatusError({\n issueId,\n operation: 'setReviewStatus',\n message: cause instanceof Error ? cause.message : String(cause),\n cause,\n }),\n });\n\nexport const getReviewStatus = (\n issueId: string,\n): Effect.Effect<ReviewStatus | null, ReviewStatusError> =>\n Effect.try({\n try: () => getReviewStatusFromDbSync(issueId),\n catch: (cause) =>\n new ReviewStatusError({\n issueId,\n operation: 'getReviewStatus',\n message: cause instanceof Error ? cause.message : String(cause),\n cause,\n }),\n });\n"],"x_google_ignoreList":[9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79],"mappings":";;;;;;;;;;;;;;;;;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;EAAM,CAAC;AAElO,uBAAsBD,OAAK,SAAS,EAAE,aAAa,qBAAqB;AAid1E,iCAAsE;AAuBpE,2CAA0B,IAAI,KAAqB;AACnD,sDAAqC,IAAI,KAAqB;AAC9D,oCAAmC;AACnC,gCAA+B,KAAK;AACpC,mCAAkC,KAAK;AACvC,8CAA6B,IAAI,KAAqB;AACxD,gCAA+B;AA4H7B,yCAAwB,IAAI,KAAqB;AACjD,qCAAoC;AAsV7B,kCAAiC;AA2DjC,qBAAb,cAAuC,KAAK,YAAY,oBAAoB,CAKzE;AAEU,oBACX,SACA,QACA,aAEA,OAAO,WAAW;EAChB,WAAW,IAAI,SAAuB,SAAS,WAAW;AACxD,sBAAmB;AACjB,QAAI;AACF,aAAQ,oBAAoB,SAAS,QAAQ,SAAS,CAAC;aAChD,KAAK;AACZ,YAAO,IAAI;;KAEb;IACF;EACF,QAAQ,UACN,IAAI,kBAAkB;GACpB;GACA,WAAW;GACX,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAC/D;GACD,CAAC;EACL,CAAC;AAES,oBACX,YAEA,OAAO,IAAI;EACT,WAAW,0BAA0B,QAAQ;EAC7C,QAAQ,UACN,IAAI,kBAAkB;GACpB;GACA,WAAW;GACX,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;GAC/D;GACD,CAAC;EACL,CAAC"}
1
+ {"version":3,"file":"review-status-yY5qt7Rl.js","names":["existsSync","fsp","readFileSync","readdirSync","existsSync","join","dirname","sep","posix","PostHogPersistedProperty","createReadStream","ErrorTracking.ReduceableCache","sep","isAbsolute","relative","error_tracking","PostHogPersistedProperty","#_","ErrorTracking.ErrorPropertiesBuilder","ErrorTracking.EventCoercer","ErrorTracking.ErrorCoercer","ErrorTracking.ObjectCoercer","ErrorTracking.StringCoercer","ErrorTracking.PrimitiveCoercer","ErrorTracking.createStackParser","ErrorTracking.nodeStackLineParser","readFileSync","statSync","readFileSync","join","dbDelete"],"sources":["../../src/lib/pan-dir/record-lock.ts","../../src/lib/pan-dir/pipeline-verdict-merge.ts","../../src/lib/pan-dir/records.ts","../../src/lib/overdeck/review-status-record-sync.ts","../../src/lib/review-findings.ts","../../src/lib/cloister/review-convergence.ts","../../src/lib/review-status-reconcile.ts","../../src/lib/review-dispatch-decision.ts","../../src/lib/review-status-read.ts","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/featureFlagUtils.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/types.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/gzip.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/utils/bot-detection.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/utils/string-utils.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/utils/type-utils.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/utils/number-utils.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/utils/bucketed-rate-limiter.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/vendor/uuidv7.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/utils/promise-queue.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/utils/logger.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/utils/user-agent-utils.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/utils/index.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/logs/logs-utils.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/logs/index.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/metrics/metrics-utils.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/metrics/config.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/metrics/index.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/cookie.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/eventemitter.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/chunk-ids.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/error-properties-builder.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/parsers/base.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/parsers/safari.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/parsers/chrome.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/parsers/gecko.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/parsers/winjs.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/parsers/opera.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/parsers/node.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/parsers/index.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/coercers/dom-exception-coercer.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/coercers/error-coercer.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/coercers/error-event-coercer.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/coercers/string-coercer.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/types.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/coercers/utils.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/coercers/event-coercer.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/coercers/primitive-coercer.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/coercers/promise-rejection-event.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/coercers/index.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/utils.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/exception-steps.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/error-tracking/index.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/posthog-core-stateless.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/posthog-core.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/tracing-headers.mjs","../../node_modules/.bun/@posthog+core@1.45.0/node_modules/@posthog/core/dist/index.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/context-lines.node.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/relative-path.node.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/version.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/types.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/feature-flag-evaluations.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/extensions/feature-flags/crypto.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/extensions/feature-flags/feature-flags.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/extensions/error-tracking/autocapture.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/extensions/error-tracking/index.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/storage-memory.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/capture-v1/config.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/capture-v1/routing.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/capture-v1/errors.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/capture-v1/transform.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/capture-v1/sender.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/client.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/extensions/context/context.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/extensions/sentry-integration.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/extensions/url-utils.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/extensions/express.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/exports.mjs","../../node_modules/.bun/posthog-node@5.46.0/node_modules/posthog-node/dist/entrypoints/index.node.mjs","../../src/lib/telemetry/config.ts","../../src/lib/telemetry/install-id.ts","../../src/lib/telemetry/service.ts","../../src/lib/telemetry/pipeline.ts","../../src/lib/review-verdict-guards.ts","../../src/lib/review-status.ts"],"sourcesContent":["const issueRecordLocks = new Map<string, Promise<void>>();\n\n/**\n * Serialize async read-modify-write rebuilds for a single issue record.\n *\n * Synchronous record writers remain synchronous; async flows that read, await,\n * then write the whole record must use this lock so same-issue rebuilds cannot\n * overwrite each other's final re-read.\n */\nexport async function withIssueRecordLock<T>(\n issueId: string,\n fn: () => T | Promise<T>,\n): Promise<T> {\n const key = issueId.toUpperCase();\n const previous = issueRecordLocks.get(key) ?? Promise.resolve();\n let release: () => void = () => {};\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n const chain = previous.catch(() => undefined).then(() => current);\n issueRecordLocks.set(key, chain);\n\n await previous.catch(() => undefined);\n\n try {\n return await fn();\n } finally {\n release();\n if (issueRecordLocks.get(key) === chain) {\n issueRecordLocks.delete(key);\n }\n }\n}\n","/**\n * PAN-3092: verdict-aware pipeline merge.\n *\n * `pipeline.updatedAt` is stamped on EVERY status write (projectPipeline,\n * records.ts), verdict or not, so a plain newer-wins comparison conflates\n * write-recency with verdict-truth: a verdict-free write that lands a second\n * after a reviewer's `passed` makes the passed verdict look like the older\n * truth and silently drops it (observed on MIN-902, where the review verdict\n * ended up in no persisted plane at all).\n *\n * The rule here keeps PAN-2587's newer-wins default for every non-verdict\n * field while refusing to regress a gate that already reached a terminal\n * verdict inside the same review cycle. A strictly newer `reviewSpawnedAt`\n * (a genuinely new review cycle) and a newer terminal verdict both still win.\n */\n\nimport type { PanIssuePipelineRecord } from './record.js';\n\n/**\n * Terminal verdict values per gate. Everything else — pending, reviewing,\n * testing, merging, queued, dispatch_failed, undefined — is a non-verdict\n * state that must never overwrite a terminal one inside the same cycle.\n */\nexport const TERMINAL_GATE_VALUES = {\n reviewStatus: ['passed', 'blocked', 'failed', 'skipped'],\n testStatus: ['passed', 'failed'],\n uatStatus: ['passed', 'failed'],\n verificationStatus: ['passed', 'failed', 'skipped'],\n inspectStatus: ['passed', 'blocked', 'failed'],\n mergeStatus: ['merged', 'failed'],\n} as const satisfies Record<string, readonly string[]>;\n\n/** Fields that carry a gate's evidence and must move with its status as one unit. */\nexport const GATE_COMPANIONS = {\n reviewStatus: ['reviewNotes', 'reviewedAtCommit'],\n testStatus: ['testNotes'],\n uatStatus: ['uatNotes'],\n verificationStatus: ['verificationNotes', 'lastVerifiedCommit'],\n inspectStatus: ['inspectNotes'],\n mergeStatus: ['mergeNotes', 'mergeStep'],\n} as const satisfies Record<keyof typeof TERMINAL_GATE_VALUES, readonly string[]>;\n\ntype GateName = keyof typeof TERMINAL_GATE_VALUES;\n\nconst GATE_NAMES = Object.keys(TERMINAL_GATE_VALUES) as GateName[];\n\n/**\n * Field-level view of a pipeline block. The two callers pass different declared\n * shapes (the record's `PanIssuePipelineRecord`, the fallback's\n * `Partial<ReviewStatus>` subset) and neither declares every gate, so gate\n * access goes through one loose view rather than six casts.\n */\ntype PipelineFields = Record<string, unknown>;\n\nfunction fields(pipeline: unknown): PipelineFields {\n return pipeline as PipelineFields;\n}\n\nfunction isTerminal(gate: GateName, value: unknown): boolean {\n return typeof value === 'string' && (TERMINAL_GATE_VALUES[gate] as readonly string[]).includes(value);\n}\n\n/** Milliseconds for an ISO/epoch cycle marker, or undefined when it does not parse. */\nfunction cycleMs(value: unknown): number | undefined {\n if (typeof value === 'number') return Number.isFinite(value) ? value : undefined;\n if (typeof value !== 'string') return undefined;\n const parsed = Date.parse(value);\n return Number.isNaN(parsed) ? undefined : parsed;\n}\n\nfunction reviewCycleMs(pipeline: PipelineFields): number | undefined {\n const spawned = cycleMs(pipeline.reviewSpawnedAt);\n const requested = cycleMs(pipeline.reviewRequestedAt);\n if (spawned === undefined) return requested;\n if (requested === undefined) return spawned;\n return Math.max(spawned, requested);\n}\n\nfunction carriesTerminalVerdict(pipeline: PipelineFields): boolean {\n return GATE_NAMES.some((gate) => isTerminal(gate, pipeline[gate]));\n}\n\nexport interface StaleVerdictSnapshot {\n liveCycle: number;\n snapshotCycle?: number;\n liveHead?: string;\n snapshotHead?: string;\n}\n\n/**\n * A pending/reviewing row with a newer review obligation owns the current cycle.\n * An older terminal snapshot is historical evidence and must not replace it,\n * regardless of which whole-pipeline `updatedAt` happens to be newer.\n */\nexport function staleVerdictSnapshotAgainstLiveCycle(\n live: PipelineFields,\n snapshot: PipelineFields,\n): StaleVerdictSnapshot | null {\n const liveReviewStatus = live.reviewStatus;\n const liveSpawned = cycleMs(live.reviewSpawnedAt);\n const liveRequested = cycleMs(live.reviewRequestedAt);\n const liveCycle = reviewCycleMs(live);\n const snapshotCycle = reviewCycleMs(snapshot);\n const liveCycleActive = liveReviewStatus === 'reviewing'\n || (liveReviewStatus === 'pending'\n && liveRequested !== undefined\n && (liveSpawned === undefined || liveRequested > liveSpawned));\n\n if (\n !liveCycleActive\n || liveCycle === undefined\n || snapshotCycle === undefined\n || !carriesTerminalVerdict(snapshot)\n || snapshotCycle >= liveCycle\n ) return null;\n\n return {\n liveCycle,\n snapshotCycle,\n liveHead: typeof live.prHeadSha === 'string'\n ? live.prHeadSha\n : typeof live.lastVerifiedCommit === 'string'\n ? live.lastVerifiedCommit\n : typeof live.reviewedAtCommit === 'string'\n ? live.reviewedAtCommit\n : undefined,\n snapshotHead: typeof snapshot.reviewedAtCommit === 'string'\n ? snapshot.reviewedAtCommit\n : typeof snapshot.lastVerifiedCommit === 'string'\n ? snapshot.lastVerifiedCommit\n : typeof snapshot.prHeadSha === 'string'\n ? snapshot.prHeadSha\n : undefined,\n };\n}\n\n/**\n * Merge a freshly-read on-disk pipeline over a rebuilt one without losing a\n * terminal verdict the rebuild carries.\n *\n * Order of rules:\n * 1. Either side lacks `updatedAt` → the rebuilt block wins (PAN-2587 guard).\n * 2. The rebuilt block is at least as new → it wins outright (PAN-2587).\n * 3. Otherwise `fresh` is the base — newer-wins for every non-verdict field.\n * 4. `fresh` belongs to a strictly newer review cycle → it wins wholesale;\n * a new cycle legitimately resets the previous cycle's verdicts.\n * 5. Any gate where `rebuilt` holds a terminal verdict and the base does not\n * keeps the rebuilt status plus its companion fields.\n */\nexport function mergePipelineVerdictAware(\n rebuilt: PanIssuePipelineRecord,\n fresh: PanIssuePipelineRecord | undefined,\n): PanIssuePipelineRecord {\n if (!fresh?.updatedAt || !rebuilt?.updatedAt) return rebuilt;\n if (!(rebuilt.updatedAt < fresh.updatedAt)) return rebuilt;\n\n const rebuiltCycle = reviewCycleMs(fields(rebuilt));\n const freshCycle = reviewCycleMs(fields(fresh));\n if (rebuiltCycle !== undefined && freshCycle !== undefined && freshCycle > rebuiltCycle) {\n return fresh;\n }\n\n // Cloned lazily: when no gate needs preserving the caller gets the identical\n // `fresh` object back, which is exactly PAN-2587's behavior.\n let merged: PanIssuePipelineRecord | undefined;\n for (const gate of GATE_NAMES) {\n if (!isTerminal(gate, fields(rebuilt)[gate]) || isTerminal(gate, fields(fresh)[gate])) continue;\n merged ??= structuredClone(fresh);\n const target = fields(merged);\n const source = fields(rebuilt);\n for (const field of [gate, ...GATE_COMPANIONS[gate]]) {\n if (source[field] === undefined) delete target[field];\n else target[field] = source[field];\n }\n }\n return merged ?? fresh;\n}\n\n/**\n * Does this status update drive some gate to a terminal verdict it was not\n * already at? That is the write an agent cannot cheaply retry — losing it\n * strands the verdict in the agent's pane — so the journal writer waits out lock\n * contention for it instead of dropping to the workspace fallback on the first\n * collision (PAN-3092). Bookkeeping writes stay single-shot; retrying those\n * would only add lock pressure.\n */\nexport function carriesNewTerminalVerdict(\n previous: PipelineFields,\n update: PipelineFields,\n): boolean {\n return GATE_NAMES.some((gate) => {\n const next = update[gate];\n return next !== undefined && next !== previous[gate] && isTerminal(gate, next);\n });\n}\n\n/**\n * Has the journal settled every gate the workspace fallback holds a terminal\n * verdict for? The drain asks this before deleting a fallback as superseded: a\n * newer-but-verdict-free journal write must not consume a verdict that never\n * landed anywhere (PAN-3092; MIN-902 lost its review verdict exactly this way).\n *\n * Coverage is per-gate VALUE equality, not merely \"the journal reached some\n * terminal value\". `pipeline.updatedAt` is restamped by unrelated bookkeeping —\n * the root defect this issue exists for — so a later whole-pipeline timestamp is\n * no evidence that a journal's differing terminal value is the newer one; it may\n * be an older verdict carried forward while the newer specialist result waits in\n * the fallback. When the values differ the fallback is folded instead, and\n * `mergePipelineVerdictAware` decides the winner from per-gate evidence.\n */\nexport function pipelineCoversFallbackVerdicts(\n journal: PanIssuePipelineRecord,\n fallback: { updatedAt: string; pipeline: PipelineFields },\n): boolean {\n const journalCycle = reviewCycleMs(fields(journal));\n const fallbackCycle = reviewCycleMs(fallback.pipeline);\n const fallbackWrittenMs = cycleMs(fallback.updatedAt);\n if (\n journalCycle !== undefined\n && ((fallbackCycle !== undefined && journalCycle > fallbackCycle)\n || (fallbackCycle === undefined && fallbackWrittenMs !== undefined && journalCycle > fallbackWrittenMs))\n ) {\n return true;\n }\n\n const journalFields = fields(journal);\n const fallbackFields = fields(fallback.pipeline);\n for (const gate of GATE_NAMES) {\n const held = fallbackFields[gate];\n if (!isTerminal(gate, held)) continue;\n if (journalFields[gate] !== held) return false;\n }\n return true;\n}\n\n/** One gate holding two different written terminal verdicts. */\nexport interface VerdictConflict {\n gate: string;\n journalValue: string;\n fallbackValue: string;\n}\n\n/**\n * Which gates hold DIFFERENT terminal verdicts in the journal and the fallback,\n * within the same review cycle?\n *\n * This is the one case the drain cannot resolve: two written terminal verdicts\n * for one gate, and no per-gate timestamp to order them by. The whole-pipeline\n * `updatedAt` is restamped by unrelated bookkeeping, so \"the journal's is newer\"\n * is exactly the inference PAN-3092 exists to stop making. Callers preserve the\n * fallback and let the stranded-fallback sweep put the conflict in front of an\n * operator rather than picking a winner.\n */\nexport function findFallbackVerdictConflicts(\n journal: PanIssuePipelineRecord,\n fallback: { updatedAt: string; pipeline: PipelineFields },\n): VerdictConflict[] {\n const journalCycle = reviewCycleMs(fields(journal));\n const fallbackCycle = reviewCycleMs(fallback.pipeline);\n const fallbackWrittenMs = cycleMs(fallback.updatedAt);\n // A newer review cycle legitimately resets the previous cycle's verdicts.\n if (\n journalCycle !== undefined\n && ((fallbackCycle !== undefined && journalCycle > fallbackCycle)\n || (fallbackCycle === undefined && fallbackWrittenMs !== undefined && journalCycle > fallbackWrittenMs))\n ) {\n return [];\n }\n\n const journalFields = fields(journal);\n const fallbackFields = fields(fallback.pipeline);\n const conflicts: VerdictConflict[] = [];\n for (const gate of GATE_NAMES) {\n const held = fallbackFields[gate];\n if (!isTerminal(gate, held)) continue;\n const settled = journalFields[gate];\n if (!isTerminal(gate, settled) || settled === held) continue;\n conflicts.push({ gate, journalValue: String(settled), fallbackValue: String(held) });\n }\n return conflicts;\n}\n\n/** Boolean form of {@link findFallbackVerdictConflicts} for the drain's withhold decision. */\nexport function pipelineConflictsWithFallbackVerdicts(\n journal: PanIssuePipelineRecord,\n fallback: { updatedAt: string; pipeline: PipelineFields },\n): boolean {\n return findFallbackVerdictConflicts(journal, fallback).length > 0;\n}\n","/**\n * PAN-1908 / PAN-1919: per-issue permanent-record builder.\n *\n * Builds a single JSON record per issue from SQLite (pipeline verdicts, usage,\n * merges) plus the legacy project-side continue file. The actual read/write/path\n * helpers live in `record.ts` (PAN-1919 single-writer module) and write the\n * record onto the feature branch at `<workspace>/.pan/records/<issue>.json`.\n */\n\nimport { hostname } from 'node:os';\nimport { join } from 'node:path';\nimport { existsSync, promises as fsp } from 'node:fs';\nimport { PAN_CONTINUES_DIRNAME, PAN_DIRNAME } from './types.js';\n\n// ─── Types ────────────────────────────────────────────────────────────────────\nimport {\n getCostBreakdownByStageAndModelSync,\n getCostForIssueSync,\n} from '../overdeck/cost-sync.js';\nimport { getMergeSetSync } from '../merge-set.js';\nimport {\n findProjectByPathSync,\n getProjectSync,\n resolveProjectFromIssueSync,\n type ProjectConfig,\n} from '../projects.js';\nimport { resolveStateReadHomeSync } from '../state-read-home.js';\nimport type { ReviewStatus } from '../review-status-types.js';\nimport type { RuntimeName } from '../runtimes/types.js';\nimport type {\n ContinueDecision,\n ContinueFeedbackEntry,\n ContinueHazard,\n ContinueResumePoint,\n ContinueSessionEntry,\n ScopeDriftRecord,\n} from '../xbrief/continue-state.js';\nimport {\n LEGACY_VBRIEF_FILENAME_SUFFIX,\n XBRIEF_FILENAME_SUFFIX,\n} from '../xbrief/lifecycle.js';\nimport { listOverdeckAgentStatesSync } from '../overdeck/agent-state-sync.js';\nimport {\n getIssueWorkspacePath,\n RECORD_SCHEMA_VERSION,\n readIssueRecord,\n readIssueRecordSync,\n type PanIssueRecord,\n type PanIssuePipelineRecord,\n type PanIssueUsageRecord,\n} from './record.js';\nimport { updateIssueRecord } from './record-update.js';\nimport { withIssueRecordLock } from './record-lock.js';\nimport { mergePipelineVerdictAware } from './pipeline-verdict-merge.js';\n\nexport type {\n PanIssueRecord,\n PanIssueCloseOutRecord,\n PanIssuePipelineRecord,\n PanIssueUsageRecord,\n} from './record.js';\n\n// ─── Continue projection ──────────────────────────────────────────────────────\n\ninterface ContinueFile {\n issueId?: string;\n gitState?: { branch?: string };\n decisions?: ContinueDecision[];\n hazards?: ContinueHazard[];\n resumePoint?: ContinueResumePoint | null;\n sessionHistory?: ContinueSessionEntry[];\n feedback?: ContinueFeedbackEntry[];\n agentModel?: string;\n scopeDrift?: ScopeDriftRecord;\n}\n\nfunction projectContinue(raw: ContinueFile | null): Pick<PanIssueRecord, 'decisions' | 'hazards' | 'resumePoint' | 'sessionHistory' | 'feedback' | 'scopeDrift'> {\n return {\n decisions: raw?.decisions,\n hazards: raw?.hazards,\n resumePoint: raw?.resumePoint,\n sessionHistory: raw?.sessionHistory,\n feedback: raw?.feedback ?? [],\n scopeDrift: raw?.scopeDrift,\n };\n}\n\n// ─── Pipeline projection ──────────────────────────────────────────────────────\n\nexport function projectPipeline(\n issueId: string,\n status: ReviewStatus | null,\n existing?: PanIssuePipelineRecord,\n): PanIssuePipelineRecord {\n const base: PanIssuePipelineRecord = {\n issueId,\n reviewStatus: status?.reviewStatus ?? 'pending',\n testStatus: status?.testStatus ?? 'pending',\n // PAN-3092: no 'pending' default — an absent uatStatus means \"UAT not\n // required\", which the merge-eligibility predicates treat as satisfied.\n uatStatus: status?.uatStatus,\n verificationStatus: status?.verificationStatus,\n inspectStatus: status?.inspectStatus,\n mergeStatus: status?.mergeStatus,\n mergeStep: status?.mergeStep,\n releaseStatus: status?.releaseStatus ?? 'pending',\n ship: existing?.ship,\n readyForMerge: status?.readyForMerge ?? false,\n closedOut: existing?.closedOut,\n closedOutAt: existing?.closedOutAt,\n reopenedAt: existing?.reopenedAt,\n // PAN-2587: the tombstone lives only in the record — a rebuild that projects\n // from ReviewStatus (which has no such field) must not erase it, or the\n // orphaned-completions patrol re-arms the same issue forever (36x on PAN-399).\n panDoneRecoveredAt: existing?.panDoneRecoveredAt,\n updatedAt: status?.updatedAt ?? new Date().toISOString(),\n };\n\n if (!status) return base;\n\n return {\n ...base,\n reviewNotes: status.reviewNotes,\n testNotes: status.testNotes,\n uatNotes: status.uatNotes,\n verificationNotes: status.verificationNotes,\n inspectNotes: status.inspectNotes,\n mergeNotes: status.mergeNotes,\n blockerReasons: status.blockerReasons,\n prUrl: status.prUrl,\n prNumber: status.prNumber,\n prHeadSha: status.prHeadSha,\n reviewedAtCommit: status.reviewedAtCommit,\n lastVerifiedCommit: status.lastVerifiedCommit,\n reviewRequestedAt: status.reviewRequestedAt,\n reviewSpawnedAt: typeof status.reviewSpawnedAt === 'number'\n ? new Date(status.reviewSpawnedAt).toISOString()\n : status.reviewSpawnedAt,\n scopeDrift: status.scopeDrift,\n autoMerge: status.autoMerge,\n deaconIgnored: status.deaconIgnored,\n deaconIgnoredAt: status.deaconIgnoredAt,\n deaconIgnoredReason: status.deaconIgnoredReason,\n reviewCycleHistory: (status as { reviewCycleHistory?: unknown }).reviewCycleHistory,\n strikeReadyHead: status.strikeReadyHead,\n strikeReadyAt: status.strikeReadyAt,\n strikeLandingState: status.strikeLandingState,\n strikeRecoveryCount: status.strikeRecoveryCount,\n strikeTransportRetryCount: status.strikeTransportRetryCount,\n strikeNextAttemptAt: status.strikeNextAttemptAt,\n strikeLandingAttempts: status.strikeLandingAttempts,\n };\n}\n\n// ─── Usage projection ─────────────────────────────────────────────────────────\n\nfunction projectUsage(issueId: string): PanIssueUsageRecord {\n const { byStage, totals } = getCostBreakdownByStageAndModelSync(issueId);\n const aggregate = getCostForIssueSync(issueId);\n\n return {\n byStage,\n totals,\n costAtCloseOut: {\n usd: aggregate?.totalCost ?? 0,\n pricingAsOf: new Date().toISOString(),\n },\n };\n}\n\n// ─── Merge projection ─────────────────────────────────────────────────────────\n\nfunction projectMerges(issueId: string): string[] {\n const mergeSet = getMergeSetSync(issueId);\n if (!mergeSet) return [];\n return mergeSet.repos\n .map(r => r.artifactUrl)\n .filter((url): url is string => typeof url === 'string' && url.length > 0);\n}\n\n// ─── Record builder ───────────────────────────────────────────────────────────\n\nexport function resolveContinuePath(projectRoot: string, issueId: string): string {\n const project: ProjectConfig = findProjectByPathSync(projectRoot) ?? {\n name: projectRoot,\n path: projectRoot,\n };\n const stateHome = resolveStateReadHomeSync(project);\n const continuesDir = stateHome.migrated\n ? join(stateHome.root, PAN_CONTINUES_DIRNAME)\n : join(stateHome.root, PAN_DIRNAME, PAN_CONTINUES_DIRNAME);\n const basePath = join(continuesDir, issueId.toLowerCase());\n const canonicalPath = `${basePath}${XBRIEF_FILENAME_SUFFIX}`;\n const legacyPath = `${basePath}${LEGACY_VBRIEF_FILENAME_SUFFIX}`;\n if (existsSync(canonicalPath)) return canonicalPath;\n if (existsSync(legacyPath)) return legacyPath;\n return canonicalPath;\n}\n\nasync function readLegacyContinueText(projectRoot: string, issueId: string): Promise<string | null> {\n try {\n return await fsp.readFile(resolveContinuePath(projectRoot, issueId), 'utf-8');\n } catch {\n return null;\n }\n}\n\n/** Read workspace continue.json and return its statusOverrides (if any). */\nasync function readWorkspaceContinueStatusOverrides(issueId: string): Promise<Record<string, string> | undefined> {\n const workspacePath = getIssueWorkspacePath(issueId);\n if (!workspacePath || !existsSync(workspacePath)) return undefined;\n const continuePath = join(workspacePath, '.pan', 'continue.json');\n try {\n const text = await fsp.readFile(continuePath, 'utf-8');\n const parsed = JSON.parse(text) as { statusOverrides?: Record<string, string> };\n return parsed.statusOverrides ?? undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Read harness/model for an issue from the overdeck agents table (most recent work agent). */\nfunction projectAgentHarnessModel(issueId: string): { harness?: RuntimeName; model?: string } {\n try {\n const agents = listOverdeckAgentStatesSync().filter(\n (a) => a.issueId?.toUpperCase() === issueId.toUpperCase(),\n );\n const workAgent =\n agents\n .filter((a) => a.role === 'work')\n .sort((a, b) => (b.startedAt ?? '').localeCompare(a.startedAt ?? ''))[0]\n ?? agents[agents.length - 1];\n // Mid-spawn placeholder row (spawn routes write model 'pending-work-spawn'\n // with a defaulted harness) — not authoritative yet.\n if (workAgent?.model === 'pending-work-spawn') return {};\n return {\n harness: workAgent?.harness,\n model: workAgent?.model ?? undefined,\n };\n } catch {\n return {};\n }\n}\n\nexport interface BuildIssueRecordOptions {\n closedAt?: string;\n owner?: string;\n reviewStatus?: ReviewStatus | null;\n}\n\nexport async function buildIssueRecord(\n project: ProjectConfig,\n issueId: string,\n opts: BuildIssueRecordOptions = {},\n): Promise<PanIssueRecord> {\n const existing = await readIssueRecord(project, issueId);\n const legacyContinueText = await readLegacyContinueText(project.path, issueId);\n const continueSubset = projectContinue(legacyContinueText ? (JSON.parse(legacyContinueText) as ContinueFile) : null);\n const pipelineRecord = projectPipeline(issueId, opts.reviewStatus ?? null, existing?.pipeline);\n const usageRecord = projectUsage(issueId);\n const merges = projectMerges(issueId);\n\n // PAN-1919: fold workspace continue statusOverrides; fall back to existing.\n const workspaceStatusOverrides = await readWorkspaceContinueStatusOverrides(issueId);\n const mergedStatusOverrides = workspaceStatusOverrides\n ? { ...(existing?.statusOverrides ?? {}), ...workspaceStatusOverrides }\n : existing?.statusOverrides;\n\n // PAN-2686: live agents-table harness/model wins so a restart-fresh with a\n // new model refreshes the record; the existing record survives as fallback\n // when no agent row remains (PAN-1919's rebuild idempotency).\n const liveHM = projectAgentHarnessModel(issueId);\n const agentHM = {\n harness: liveHM.harness ?? existing?.harness,\n model: liveHM.model ?? existing?.model,\n };\n\n return {\n issueId: issueId.toUpperCase(),\n schemaVersion: RECORD_SCHEMA_VERSION,\n ...continueSubset,\n ...existing,\n harness: agentHM.harness,\n model: agentHM.model,\n statusOverrides: mergedStatusOverrides,\n pipeline: pipelineRecord,\n closeOut: {\n usage: usageRecord,\n merges,\n ranOn: hostname(),\n closedAt: opts.closedAt,\n },\n owner: opts.owner ?? existing?.owner,\n };\n}\n\n// Re-export core record I/O from the PAN-1919 single-writer module.\nexport {\n getIssueRecordPath,\n markRecordPipelineClosedOutSync,\n readIssueRecord,\n queueIssueRecordCommit,\n} from './record.js';\n\n// ─── Owner-URI lease (PAN-1908, CP-3) ─────────────────────────────────────────\n\nexport {\n buildOwnUri,\n claimIssueOwner,\n clearIssueOwner,\n type ClaimResult,\n} from './record.js';\n\n/**\n * PAN-2587: never regress the pipeline block during a whole-record rebuild. A\n * concurrent writer (e.g. a reviewer's verdict landing between the rebuild's\n * `existing` snapshot and its write) may have put a NEWER pipeline on disk than\n * the status the rebuild projects — observed clobbering PAN-399's passed\n * verdict back to a pre-verdict snapshot. Same newer-wins rule (ISO `updatedAt`\n * comparison) the journal readers use.\n *\n * PAN-3092: newer-wins alone conflates write-recency with verdict-truth, because\n * `projectPipeline` stamps `updatedAt` on every write, verdict or not. The\n * comparison now runs through `mergePipelineVerdictAware`, which keeps\n * newer-wins for every non-verdict field but refuses to drop a terminal verdict\n * in favour of a same-cycle verdict-free write.\n */\nexport function pickNewerPipeline(\n rebuilt: PanIssuePipelineRecord,\n fresh: PanIssuePipelineRecord | undefined,\n): PanIssuePipelineRecord {\n return mergePipelineVerdictAware(rebuilt, fresh);\n}\n\n/**\n * PAN-1908 / PAN-1919: rebuild and queue the per-issue permanent record for a\n * given issue. Fire-and-forget: failures are logged, never thrown, so\n * review-status writes stay synchronous and fast.\n *\n * PAN-2583: returns whether the durable write actually landed, so the caller\n * can fall back to a sandbox-writable verdict drop when it did not (a sandboxed\n * reviewer cannot write ${OVERDECK_HOME}/state, and swallowing that here was\n * how blocked review verdicts silently vanished).\n */\nexport async function updateIssueRecordForIssue(\n issueId: string,\n reviewStatus?: ReviewStatus | null,\n): Promise<boolean> {\n try {\n const resolved = resolveProjectFromIssueSync(issueId);\n if (!resolved) return false;\n const project = getProjectSync(resolved.projectKey);\n if (!project) return false;\n\n await withIssueRecordLock(issueId, async () => {\n const record = await buildIssueRecord(project, issueId, { reviewStatus });\n await updateIssueRecord(project, issueId, (fresh) => {\n // buildIssueRecord's `existing` snapshot is read at the top of several awaits;\n // anything written to the record during that window would be erased by this\n // whole-record write (lost update). Observed twice on PAN-1791: wiped swarm\n // slot assignments during the runaway, then wiped item statusOverrides right\n // after `pan done` — which made every completed item dispatchable again and\n // re-spawned slots for finished work. Re-read both blocks synchronously\n // immediately before writing so the freshest values survive the rebuild.\n if (fresh?.swarm) record.swarm = fresh.swarm;\n if (fresh?.statusOverrides && Object.keys(fresh.statusOverrides).length > 0) {\n record.statusOverrides = { ...record.statusOverrides, ...fresh.statusOverrides };\n }\n record.pipeline = pickNewerPipeline(record.pipeline, fresh?.pipeline);\n return record;\n });\n });\n return true;\n } catch (err) {\n console.warn(`[pan-dir/records] Failed to update record for ${issueId}: ${(err as Error).message}`);\n return false;\n }\n}\n","import { existsSync, linkSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';\nimport { readFile, readdir } from 'node:fs/promises';\nimport { basename, dirname, join } from 'node:path';\nimport type { ReviewStatus } from '../review-status-types.js';\nimport { updateIssueRecordForIssue, type PanIssuePipelineRecord } from '../pan-dir/records.js';\nimport { readIssueRecord, readIssueRecordSync } from '../pan-dir/record.js';\nimport {\n findFallbackVerdictConflicts,\n pipelineConflictsWithFallbackVerdicts,\n pipelineCoversFallbackVerdicts,\n staleVerdictSnapshotAgainstLiveCycle,\n type VerdictConflict,\n} from '../pan-dir/pipeline-verdict-merge.js';\nimport { resolveProjectFromIssueSync, getProjectSync } from '../projects.js';\n\n// PAN-2689: fire-and-forget journal writes die with the process in a short-lived\n// CLI (pan admin specialists done exits in <1s; the record write + fallback chain\n// takes seconds). Track every in-flight write so CLI entry points can drain them\n// before process.exit — the long-lived server never needs to await these.\nconst pendingJournalWrites = new Set<Promise<void>>();\n\n/**\n * PAN-3092: a journal write carrying a NEW terminal verdict retries under lock\n * contention instead of dropping straight to the workspace fallback. MIN-902's\n * reviewer re-ran `pan admin specialists done` for an hour at LLM-turn cost\n * (~$5/hr) because the only retry available to it was another agent turn; this\n * schedule (~2.6 min total) does the same waiting in-process for free. The long\n * tail belongs to the deacon sweep, not to the agent.\n */\nconst DEFAULT_VERDICT_BACKOFF_DELAYS_MS = [2_000, 5_000, 10_000, 20_000, 40_000, 80_000] as const;\n\nfunction verdictWriteBackoffDelaysMs(): readonly number[] {\n const raw = process.env.OVERDECK_VERDICT_BACKOFF_DELAYS_MS;\n if (!raw) return DEFAULT_VERDICT_BACKOFF_DELAYS_MS;\n const parsed = raw\n .split(',')\n .map((part) => Number(part.trim()))\n .filter((ms) => Number.isFinite(ms) && ms >= 0);\n return parsed.length > 0 ? parsed : DEFAULT_VERDICT_BACKOFF_DELAYS_MS;\n}\n\n/**\n * One journal-write attempt. `false` means the durable write definitively\n * failed; `undefined` (a test double, say) is \"unknown\", not \"failed\", and only\n * a definite `true` is safe to treat as a landed write.\n */\nasync function attemptJournalWrite(\n issueId: string,\n status: ReviewStatus,\n): Promise<boolean | undefined> {\n try {\n return await updateIssueRecordForIssue(issueId, status);\n } catch {\n return false;\n }\n}\n\nexport function updateIssueRecordForReviewStatusSync(\n issueId: string,\n status: ReviewStatus,\n options?: { verdictWrite?: boolean },\n): void {\n // PAN-2583: the state-dir journal is the durable home, but a sandboxed reviewer\n // (codex workspace-write) cannot write ${OVERDECK_HOME}/state — and swallowing that\n // failure here is how blocked review verdicts silently vanished for hours. When the\n // journal write does not land, drop the durable verdict into the workspace runtime\n // dir (the one place a sandboxed agent can always write); readJournalStatusSync\n // overlays it on the next host-side read.\n const delays = options?.verdictWrite ? verdictWriteBackoffDelaysMs() : [];\n const write = (async () => {\n for (let attempt = 0; ; attempt += 1) {\n const landed = await attemptJournalWrite(issueId, status);\n if (landed !== false) {\n // PAN-2989: a landed journal write is the earliest safe moment to fold any\n // pending workspace fallback back into the canonical record.\n if (landed === true) trackVerdictFallbackDrain(issueId);\n return;\n }\n const delay = delays[attempt];\n if (delay === undefined) break;\n await new Promise<void>((resolve) => { setTimeout(resolve, delay); });\n }\n writeWorkspaceVerdictFallbackSync(issueId, status);\n scheduleVerdictFallbackDrain(issueId);\n })();\n pendingJournalWrites.add(write);\n void write.finally(() => pendingJournalWrites.delete(write));\n}\n\n/**\n * PAN-2689: await every in-flight journal write. A short-lived CLI process MUST\n * call this before process.exit or the verdict written by setReviewStatusSync is\n * silently lost (the DB write already fails readonly in a sandbox, so the dying\n * journal write was the only durable copy).\n */\nexport async function flushReviewStatusJournalWrites(): Promise<void> {\n while (pendingJournalWrites.size > 0) {\n await Promise.allSettled([...pendingJournalWrites]);\n }\n}\n\n/** Resolve and read the per-issue journal record's pipeline block, or null. Best-effort. */\nfunction readPipelineSync(issueId: string): PanIssuePipelineRecord | null {\n try {\n const resolved = resolveProjectFromIssueSync(issueId);\n if (!resolved) return null;\n const project = getProjectSync(resolved.projectKey);\n if (!project) return null;\n const record = readIssueRecordSync(project, issueId);\n return record?.pipeline ?? null;\n } catch {\n return null;\n }\n}\n\nasync function readPipeline(issueId: string): Promise<PanIssuePipelineRecord | null> {\n try {\n const resolved = resolveProjectFromIssueSync(issueId);\n if (!resolved) return null;\n const project = getProjectSync(resolved.projectKey);\n if (!project) return null;\n const record = await readIssueRecord(project, issueId);\n return record?.pipeline ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * PAN-1988: feedback TEXT (review / test / merge / inspect / verification notes) is durable\n * JOURNAL state, not DB-cache state. The SQLite row holds only the queryable status flags;\n * the human-readable notes live in the per-issue git record (`<workspace>/.pan/records/<issue>.json`,\n * PAN-1908). This overlays those notes onto a DB-sourced status so every reader (deacon\n * CI-failure detection, dashboard panels) stays transparent while the DB stops storing them.\n */\nexport function enrichReviewNotesFromRecordSync(issueId: string, status: ReviewStatus): ReviewStatus {\n const pipeline = readPipelineSync(issueId);\n if (!pipeline) return status;\n return {\n ...status,\n reviewNotes: pipeline.reviewNotes ?? status.reviewNotes,\n testNotes: pipeline.testNotes ?? status.testNotes,\n uatNotes: pipeline.uatNotes ?? status.uatNotes,\n mergeNotes: pipeline.mergeNotes ?? status.mergeNotes,\n inspectNotes: pipeline.inspectNotes ?? status.inspectNotes,\n verificationNotes: pipeline.verificationNotes ?? status.verificationNotes,\n scopeDrift: pipeline.scopeDrift ?? status.scopeDrift,\n // PAN-1988 auto-heal: the durable review-request intent is journal-only — overlay it on every\n // read so the merge base preserves it through partial updates and the dispatch reconcile sees it.\n reviewRequestedAt: pipeline.reviewRequestedAt ?? status.reviewRequestedAt,\n };\n}\n\ntype DurableStatusFields = Partial<ReviewStatus> & { closedOut?: boolean; closedOutAt?: string };\n\nconst FALLBACK_CLEARABLE_FIELDS = [\n 'strikeTransportRetryCount',\n 'strikeNextAttemptAt',\n 'reviewRequestedAt',\n] as const;\ntype FallbackClearableField = typeof FALLBACK_CLEARABLE_FIELDS[number];\n\n/**\n * The durable field subset shared by the journal record's pipeline block and the\n * workspace verdict fallback (PAN-2583). Derived/live columns (readyForMerge,\n * blockerReasons) are intentionally omitted — the reader recomputes them.\n */\nfunction durableSubset(p: PanIssuePipelineRecord): DurableStatusFields {\n return {\n reviewStatus: p.reviewStatus as ReviewStatus['reviewStatus'],\n testStatus: p.testStatus as ReviewStatus['testStatus'],\n // PAN-3092: UAT gates merge eligibility, so a contended UAT verdict must\n // survive in the fallback like every other gate's.\n uatStatus: (p.uatStatus as ReviewStatus['uatStatus']) ?? undefined,\n uatNotes: p.uatNotes,\n mergeStatus: (p.mergeStatus as ReviewStatus['mergeStatus']) ?? undefined,\n mergeStep: p.mergeStep,\n inspectStatus: (p.inspectStatus as ReviewStatus['inspectStatus']) ?? undefined,\n verificationStatus: (p.verificationStatus as ReviewStatus['verificationStatus']) ?? undefined,\n reviewNotes: p.reviewNotes,\n testNotes: p.testNotes,\n mergeNotes: p.mergeNotes,\n inspectNotes: p.inspectNotes,\n verificationNotes: p.verificationNotes,\n scopeDrift: p.scopeDrift,\n prUrl: p.prUrl,\n prNumber: p.prNumber,\n prHeadSha: p.prHeadSha,\n reviewedAtCommit: p.reviewedAtCommit,\n lastVerifiedCommit: p.lastVerifiedCommit,\n reviewRequestedAt: p.reviewRequestedAt,\n reviewSpawnedAt: p.reviewSpawnedAt,\n reviewCycleHistory: p.reviewCycleHistory as ReviewStatus['reviewCycleHistory'],\n autoMerge: p.autoMerge,\n deaconIgnored: p.deaconIgnored,\n deaconIgnoredAt: p.deaconIgnoredAt,\n deaconIgnoredReason: p.deaconIgnoredReason,\n strikeReadyHead: p.strikeReadyHead,\n strikeReadyAt: p.strikeReadyAt,\n strikeLandingState: p.strikeLandingState,\n strikeRecoveryCount: p.strikeRecoveryCount,\n strikeTransportRetryCount: p.strikeTransportRetryCount,\n strikeNextAttemptAt: p.strikeNextAttemptAt,\n strikeLandingAttempts: p.strikeLandingAttempts,\n closedOut: p.closedOut,\n closedOutAt: p.closedOutAt,\n };\n}\n\n/**\n * PAN-2583: sandbox-writable emergency drop for a verdict whose state-dir journal\n * write failed. Lives in the workspace runtime dir (gitignored), swept by\n * readJournalStatusSync on the next host-side read.\n */\nexport interface WorkspaceVerdictFallback {\n issueId: string;\n updatedAt: string;\n pipeline: DurableStatusFields;\n clearedFields?: FallbackClearableField[];\n}\n\nexport function workspaceVerdictFallbackPath(issueId: string): string | null {\n try {\n const resolved = resolveProjectFromIssueSync(issueId);\n if (!resolved) return null;\n return join(\n resolved.projectPath,\n 'workspaces',\n `feature-${issueId.toLowerCase()}`,\n '.overdeck',\n 'pipeline-verdict.json',\n );\n } catch {\n return null;\n }\n}\n\nfunction writeWorkspaceVerdictFallbackSync(issueId: string, status: ReviewStatus): void {\n try {\n const path = workspaceVerdictFallbackPath(issueId);\n if (!path) {\n console.error(\n `[review-status] PAN-2583: journal write failed for ${issueId} and no workspace could be resolved — the verdict is NOT durable`,\n );\n return;\n }\n mkdirSync(dirname(path), { recursive: true });\n const clearedFields = FALLBACK_CLEARABLE_FIELDS.filter(\n (field) => status[field] === undefined,\n );\n const payload: WorkspaceVerdictFallback = {\n issueId: issueId.toUpperCase(),\n updatedAt: status.updatedAt ?? new Date().toISOString(),\n pipeline: durableSubset(status as unknown as PanIssuePipelineRecord),\n ...(clearedFields.length > 0 ? { clearedFields } : {}),\n };\n // Atomic replace: a drain may claim the live path by rename at any moment,\n // and a plain writeFileSync could be renamed aside mid-write and fold a\n // torn payload into the canonical record.\n const tmpPath = `${path}.tmp-${process.pid}`;\n writeFileSync(tmpPath, JSON.stringify(payload, null, 2));\n renameSync(tmpPath, path);\n console.warn(\n `[review-status] journal write failed for ${issueId} — durable verdict written to workspace fallback ${path}; the host sweeps it on the next status read (PAN-2583)`,\n );\n } catch (err) {\n console.error(\n `[review-status] PAN-2583: could not persist verdict for ${issueId} anywhere durable: ${(err as Error).message}`,\n );\n }\n}\n\nfunction decodeWorkspaceVerdictFallback(raw: string): WorkspaceVerdictFallback | null {\n try {\n const parsed = JSON.parse(raw) as WorkspaceVerdictFallback;\n if (!parsed?.updatedAt || !parsed.pipeline) return null;\n const clearedFields = Array.isArray(parsed.clearedFields)\n ? parsed.clearedFields.filter((field): field is FallbackClearableField =>\n typeof field === 'string' && (FALLBACK_CLEARABLE_FIELDS as readonly string[]).includes(field))\n : [];\n return { ...parsed, clearedFields };\n } catch {\n return null;\n }\n}\n\nfunction parseWorkspaceVerdictFallback(path: string): WorkspaceVerdictFallback | null {\n try {\n return decodeWorkspaceVerdictFallback(readFileSync(path, 'utf-8'));\n } catch {\n return null;\n }\n}\n\nasync function parseWorkspaceVerdictFallbackAsync(path: string): Promise<WorkspaceVerdictFallback | null> {\n try {\n return decodeWorkspaceVerdictFallback(await readFile(path, 'utf-8'));\n } catch {\n return null;\n }\n}\n\nfunction isPidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction drainClaimPid(entry: string, prefix: string): number | null {\n const pid = Number(entry.slice(prefix.length).split('-')[0]);\n return Number.isInteger(pid) && pid > 0 ? pid : null;\n}\n\nlet drainClaimCounter = 0;\n\ninterface ClaimedFallbackGeneration {\n claimPath: string;\n fallback: WorkspaceVerdictFallback;\n}\n\n/**\n * Claim every drainable fallback generation — the live path plus any claims\n * whose owning process is dead — by renaming each onto a unique path owned by\n * this drain. Live-pid claims belong to in-flight drains and are left alone.\n *\n * Race safety: every rename target is a fresh, unique path, so no concurrent\n * verdict writer's file is ever replaced (POSIX rename onto an existing path\n * overwrites it — that is exactly the loss this protocol avoids). The payload\n * is parsed only AFTER the claim, so the generation compared and folded is\n * precisely the one this drain owns, never a stale pre-check snapshot.\n */\nfunction claimWorkspaceVerdictFallbackSync(\n issueId: string,\n): ClaimedFallbackGeneration[] | null {\n const path = workspaceVerdictFallbackPath(issueId);\n if (!path) return null;\n const dir = dirname(path);\n const prefix = `${basename(path)}.drain-`;\n let entries: string[];\n try {\n entries = readdirSync(dir);\n } catch {\n return null;\n }\n const candidates: string[] = [];\n if (entries.includes(basename(path))) candidates.push(path);\n for (const entry of entries) {\n if (!entry.startsWith(prefix)) continue;\n const pid = drainClaimPid(entry, prefix);\n if (pid !== null && isPidAlive(pid)) continue; // an in-flight drain owns it\n candidates.push(join(dir, entry));\n }\n const claims: ClaimedFallbackGeneration[] = [];\n for (const candidate of candidates) {\n drainClaimCounter += 1;\n const claimPath = `${path}.drain-${process.pid}-${drainClaimCounter}`;\n try {\n renameSync(candidate, claimPath);\n } catch {\n continue; // raced another drain; that drain owns the generation\n }\n const fallback = parseWorkspaceVerdictFallback(claimPath);\n if (!fallback) {\n rmSync(claimPath, { force: true });\n continue;\n }\n claims.push({ claimPath, fallback });\n }\n return claims.length > 0 ? claims : null;\n}\n\nexport function readWorkspaceVerdictFallbackSync(issueId: string): WorkspaceVerdictFallback | null {\n try {\n const path = workspaceVerdictFallbackPath(issueId);\n if (!path) return null;\n // Read-only newest-wins overlay across the live path AND all drain\n // claims: a drain holds its generations at claim paths for the full\n // duration of the record write, and every verdict must stay visible to\n // readers throughout — otherwise status reads fall back to the older\n // journal for up to the entire durability budget. Reads never mutate;\n // folding and cleanup are the drain's job alone.\n let newest: WorkspaceVerdictFallback | null = null;\n const consider = (candidate: WorkspaceVerdictFallback | null): void => {\n if (candidate && (!newest || newest.updatedAt < candidate.updatedAt)) newest = candidate;\n };\n if (existsSync(path)) consider(parseWorkspaceVerdictFallback(path));\n const prefix = `${basename(path)}.drain-`;\n for (const entry of readdirSync(dirname(path))) {\n if (!entry.startsWith(prefix)) continue;\n consider(parseWorkspaceVerdictFallback(join(dirname(path), entry)));\n }\n return newest;\n } catch {\n return null;\n }\n}\n\nexport async function readWorkspaceVerdictFallback(issueId: string): Promise<WorkspaceVerdictFallback | null> {\n try {\n const path = workspaceVerdictFallbackPath(issueId);\n if (!path) return null;\n const dir = dirname(path);\n const prefix = `${basename(path)}.drain-`;\n const entries = await readdir(dir);\n const candidates = [path, ...entries\n .filter((entry) => entry.startsWith(prefix))\n .map((entry) => join(dir, entry))];\n const fallbacks = await Promise.all(candidates.map(parseWorkspaceVerdictFallbackAsync));\n return fallbacks.reduce<WorkspaceVerdictFallback | null>((newest, candidate) => (\n candidate && (!newest || newest.updatedAt < candidate.updatedAt) ? candidate : newest\n ), null);\n } catch {\n return null;\n }\n}\n\n// PAN-2989: proactive drain of the workspace verdict fallback. Before this, nothing\n// ever folded a fallback back into the canonical record — observed 2026-07-21 on\n// PAN-806: the canonical journal lagged the truth for ~an hour after a stalled lock\n// forced verdict writes to the fallback. The drain runs after every landed journal\n// write for the issue, and on unref'd scheduled retries after a fallback write.\nconst DRAIN_RETRY_DELAYS_MS = [5_000, 30_000, 120_000] as const;\nconst drainTimers = new Map<string, NodeJS.Timeout>();\n\n/**\n * Fold a pending workspace verdict fallback into the canonical record and delete\n * it, without waiting for the next status read. Newer-wins on ISO `updatedAt` —\n * the same rule readJournalStatusSync uses — so a journal that already moved past\n * the fallback just cleans up the file. Returns true when no fallback remains\n * pending (drained, superseded, or never written).\n *\n * Generation-aware: the drain claims every drainable generation (the live\n * path plus stranded claims) onto unique paths it owns, folds the newest, and\n * deletes only its own claims. A newer fallback written while the record\n * write was in flight stays at the live path for its own drain schedule, and\n * no step ever renames onto a path another process may have just created.\n */\n/**\n * PAN-3092: why is a fallback still pending? A failed drain returns `false` for\n * two materially different reasons — the record write lost to a contended lock,\n * or the fold was deliberately withheld because the journal and the fallback\n * hold different terminal verdicts for one gate. Only the first clears on its\n * own; the second is permanent until an operator picks a verdict, so the sweep\n * must be able to tell them apart before it tells anyone to wait.\n *\n * Read-only and lock-free: the caller is already reporting lock contention.\n */\nexport async function findWorkspaceVerdictConflicts(\n issueId: string,\n fallback: { updatedAt: string; pipeline: DurableStatusFields },\n): Promise<VerdictConflict[]> {\n const journal = await readPipeline(issueId);\n if (!journal?.updatedAt || journal.updatedAt < fallback.updatedAt) return [];\n return findFallbackVerdictConflicts(journal, fallback);\n}\n\nexport async function drainWorkspaceVerdictFallback(issueId: string): Promise<boolean> {\n const claims = claimWorkspaceVerdictFallbackSync(issueId);\n if (!claims) return true;\n // Newest-wins across every claimed generation — the same rule the read\n // overlay uses. Older claims are superseded by the winner and are removed\n // once the winner's outcome is known.\n let winner = claims[0]!;\n for (const claim of claims) {\n if (winner.fallback.updatedAt < claim.fallback.updatedAt) winner = claim;\n }\n const losers = claims.filter((claim) => claim !== winner);\n const { fallback } = winner;\n const journal = readPipelineSync(issueId);\n const staleFallback = journal\n ? staleVerdictSnapshotAgainstLiveCycle(\n journal as unknown as Record<string, unknown>,\n fallback.pipeline as unknown as Record<string, unknown>,\n )\n : null;\n if (staleFallback) {\n console.warn(\n `[review-status] Refusing stale fallback fold for ${issueId}: `\n + `live cycle ${new Date(staleFallback.liveCycle).toISOString()} at HEAD ${staleFallback.liveHead ?? 'unknown'} `\n + `supersedes fallback cycle ${staleFallback.snapshotCycle ? new Date(staleFallback.snapshotCycle).toISOString() : 'unknown'} `\n + `at HEAD ${staleFallback.snapshotHead ?? 'unknown'}.`,\n );\n for (const claim of claims) rmSync(claim.claimPath, { force: true });\n return true;\n }\n // PAN-3092: a newer `updatedAt` alone is not evidence the journal carries the\n // verdict — `projectPipeline` stamps it on every write, verdict or not, so a\n // bookkeeping write landing after a contended verdict used to make the drain\n // delete the only surviving copy (MIN-902). Supersede only when the journal\n // has actually settled the gates the fallback holds, or has moved to a newer\n // review cycle.\n const journalAtLeastAsNew = !!journal?.updatedAt && !(journal.updatedAt < fallback.updatedAt);\n if (journalAtLeastAsNew && pipelineCoversFallbackVerdicts(journal!, fallback)) {\n for (const claim of claims) rmSync(claim.claimPath, { force: true });\n return true;\n }\n // PAN-3092: the journal and the fallback hold different terminal verdicts for\n // the same gate and nothing can order them — the whole-pipeline `updatedAt`\n // is restamped by bookkeeping, so it is not evidence either way. Folding would\n // be declined by the verdict-aware merge and deleting would destroy the only\n // written copy of one verdict, so preserve the fallback and let the sweep put\n // the conflict in front of an operator.\n const conflicted = journalAtLeastAsNew && pipelineConflictsWithFallbackVerdicts(journal!, fallback);\n // projectPipeline projects only from the ReviewStatus, so fields the fallback\n // cleared (clearedFields) stay absent and do not resurrect from the record.\n const status = {\n issueId: fallback.issueId,\n ...fallback.pipeline,\n updatedAt: fallback.updatedAt,\n readyForMerge: false, // derived on read; the stored value is never consulted\n } as ReviewStatus;\n const landed = conflicted ? false : await updateIssueRecordForIssue(issueId, status);\n if (landed) {\n for (const claim of claims) rmSync(claim.claimPath, { force: true });\n return true;\n }\n // The fold failed or was withheld as conflicting: superseded generations are\n // dropped, and the winner is\n // published back to the live path with ATOMIC no-replace semantics —\n // linkSync fails with EEXIST when a concurrent writer already created a\n // live file, so a newer verdict that arrived during the await can never be\n // overwritten. If the live generation is somehow the older one, the winner\n // stays as a stranded (non-pid) claim: the read overlay still surfaces it\n // and the next drain folds it.\n for (const claim of losers) rmSync(claim.claimPath, { force: true });\n const livePath = workspaceVerdictFallbackPath(issueId);\n if (livePath) {\n let published = false;\n try {\n linkSync(winner.claimPath, livePath);\n published = true;\n } catch {\n // A live generation already exists (or the fs rejected the link).\n }\n if (published) {\n rmSync(winner.claimPath, { force: true });\n return false;\n }\n const live = existsSync(livePath) ? parseWorkspaceVerdictFallback(livePath) : null;\n if (live && !(live.updatedAt < fallback.updatedAt)) {\n // The live generation is newer-or-equal: it carries the winning verdict.\n rmSync(winner.claimPath, { force: true });\n return false;\n }\n }\n // Keep the winner claim, but mark it stranded so a later drain reclaims it\n // (a live-pid claim would look owned by this process forever).\n drainClaimCounter += 1;\n try {\n renameSync(winner.claimPath, `${winner.claimPath.split('.drain-')[0]}.drain-republish-${drainClaimCounter}`);\n } catch {\n // Leave the claim as-is; it remains readable and recoverable.\n }\n return false;\n}\n\n/** Track a fire-and-forget drain so short-lived CLIs await it before exit. */\nfunction trackVerdictFallbackDrain(issueId: string): void {\n const drain = drainWorkspaceVerdictFallback(issueId)\n .then(() => undefined)\n .catch(() => undefined);\n pendingJournalWrites.add(drain);\n void drain.finally(() => pendingJournalWrites.delete(drain));\n}\n\n/**\n * Schedule unref'd drain retries after a fallback write. One timer per issue —\n * a new fallback write resets the schedule. Retries stop on success, on\n * exhaustion, or when the fallback file is gone.\n */\nfunction scheduleVerdictFallbackDrain(issueId: string): void {\n const key = issueId.toUpperCase();\n const existing = drainTimers.get(key);\n if (existing) clearTimeout(existing);\n\n const attempt = (index: number): void => {\n const delay = DRAIN_RETRY_DELAYS_MS[index];\n if (delay === undefined) {\n drainTimers.delete(key);\n return;\n }\n const timer = setTimeout(() => {\n drainTimers.delete(key);\n void drainWorkspaceVerdictFallback(key)\n .catch(() => false)\n .then((drained) => {\n if (!drained) attempt(index + 1);\n });\n }, delay);\n timer.unref?.();\n drainTimers.set(key, timer);\n };\n attempt(0);\n}\n\n/**\n * PAN-1988: read the journal record's durable verdict for an issue — the SOURCE OF TRUTH.\n * Returns the record `updatedAt` (used to decide whether the journal is newer than the DB\n * cache) plus the durable status fields (flags + feedback notes). Derived/live columns\n * (readyForMerge, blockerReasons) are intentionally omitted — the reader recomputes them.\n *\n * This is what makes verdict writes host-owned: a sandboxed agent can always write the journal\n * (workspace-local) even when it cannot write `~/.overdeck/overdeck.db`. The host reconciles\n * the cache from this on read, so no agent has to escalate out of its sandbox to record a verdict.\n *\n * PAN-2583: since the records migration (PAN-2541) the journal itself lives in\n * ${OVERDECK_HOME}/state, which a sandboxed reviewer cannot write either. When such a\n * writer dropped its verdict into the workspace fallback instead, overlay it here —\n * a strictly newer fallback wins over the record, and the host's own next journal\n * write folds it back into the canonical record.\n */\ntype JournalStatus = {\n updatedAt: string;\n durable: DurableStatusFields;\n clearedFields?: FallbackClearableField[];\n};\n\nfunction projectJournalStatus(\n pipeline: PanIssuePipelineRecord | null,\n fallback: WorkspaceVerdictFallback | null,\n): JournalStatus | null {\n const staleFallback = pipeline && fallback\n ? staleVerdictSnapshotAgainstLiveCycle(\n pipeline as unknown as Record<string, unknown>,\n fallback.pipeline as unknown as Record<string, unknown>,\n )\n : null;\n if (staleFallback) {\n console.warn(\n `[review-status] Refusing stale workspace fallback for ${pipeline!.issueId}: `\n + `live cycle ${new Date(staleFallback.liveCycle).toISOString()} at HEAD ${staleFallback.liveHead ?? 'unknown'} `\n + `supersedes fallback cycle ${staleFallback.snapshotCycle ? new Date(staleFallback.snapshotCycle).toISOString() : 'unknown'} `\n + `at HEAD ${staleFallback.snapshotHead ?? 'unknown'}.`,\n );\n }\n const fallbackNewer = !!fallback\n && !staleFallback\n && (!pipeline || (pipeline.updatedAt ?? '') < fallback.updatedAt);\n if (fallback && fallbackNewer) {\n const base = pipeline ? durableSubset(pipeline) : {};\n const overlay = Object.fromEntries(\n Object.entries(fallback.pipeline).filter(([, value]) => value !== undefined),\n ) as DurableStatusFields;\n const durable = { ...base, ...overlay };\n for (const field of fallback.clearedFields ?? []) delete durable[field];\n return {\n updatedAt: fallback.updatedAt,\n durable,\n ...(fallback.clearedFields?.length ? { clearedFields: fallback.clearedFields } : {}),\n };\n }\n if (!pipeline) return null;\n return { updatedAt: pipeline.updatedAt, durable: durableSubset(pipeline) };\n}\n\nexport function readJournalStatusSync(issueId: string): JournalStatus | null {\n return projectJournalStatus(\n readPipelineSync(issueId),\n readWorkspaceVerdictFallbackSync(issueId),\n );\n}\n\n/** Async journal reader for patrols that must not block the dashboard event loop. */\nexport async function readJournalStatus(issueId: string): Promise<JournalStatus | null> {\n const [pipeline, fallback] = await Promise.all([\n readPipeline(issueId),\n readWorkspaceVerdictFallback(issueId),\n ]);\n return projectJournalStatus(pipeline, fallback);\n}\n","/**\n * Review findings parsing and analysis.\n * Shared utilities for extracting and counting blocking findings from report and synthesis formats.\n */\n\nexport interface ReviewCycleEntry {\n cycle: number;\n runId: string;\n atCommit?: string;\n blockingCount: number;\n recordedAt: string;\n}\n\n/**\n * Extract a markdown section by heading.\n * Returns the content between a heading (e.g., \"## Findings\") and the next heading or EOF.\n */\nexport function extractMarkdownSection(markdown: string, heading: string): string {\n const pattern = new RegExp(`^##\\\\s+${heading}\\\\s*\\\\r?\\\\n([\\\\s\\\\S]*?)(?=^##\\\\s+|(?![\\\\s\\\\S]))`, 'im');\n return markdown.match(pattern)?.[1]?.trim() ?? '';\n}\n\n/**\n * Find blocking findings in a report markdown section.\n * Returns titles of findings marked with '!' or '⊗'.\n */\nexport function findBlockingFindings(markdown: string): string[] {\n const findings = extractMarkdownSection(markdown, 'Findings');\n if (!findings || /^none\\.?$/i.test(findings)) return [];\n\n const blockers: string[] = [];\n const headingPattern = /^###\\s*(?:!|⊗)\\s+(.+)$/gm;\n let match: RegExpExecArray | null;\n while ((match = headingPattern.exec(findings)) !== null) {\n blockers.push(match[1]!.trim());\n }\n return blockers;\n}\n\n/**\n * Count blocking findings in a synthesis body.\n * Returns the count of '## Blocking Findings' section headings (### markers),\n * or 0 if the section is absent, empty, or contains only 'None'.\n */\nexport function countSynthesisBlockingFindings(body: string): number {\n const findings = extractMarkdownSection(body, 'Blocking Findings');\n if (!findings || /^none\\.?$/i.test(findings)) return 0;\n\n const headingPattern = /^###\\s+/gm;\n let count = 0;\n let match: RegExpExecArray | null;\n while ((match = headingPattern.exec(findings)) !== null) {\n count++;\n }\n return count;\n}\n","/**\n * Review convergence detection and cycle tracking.\n * Detects when a review loop is not making progress and should be gated.\n */\n\nimport { existsSync, readdirSync, readFileSync, statSync } from 'fs';\nimport { join } from 'path';\nimport { PAN_DIRNAME, WORKSPACE_RUNTIME_DIRNAME } from '../pan-dir/types.js';\nimport { countSynthesisBlockingFindings, findBlockingFindings } from '../review-findings.js';\n\nexport interface ReviewCycleEntry {\n cycle: number;\n runId: string;\n atCommit?: string;\n blockingCount: number;\n recordedAt: string;\n}\n\nexport const REVIEW_CONVERGENCE_MIN_CYCLES = 3;\n\n/**\n * Find the latest review run directory in a workspace.\n * Looks for 'agent-*-review-*' directories under .pan/review, falling back to .overdeck/review.\n * Returns null if no run directory is found.\n */\nexport function findLatestReviewRunDir(workspacePath: string): string | null {\n const paths = [\n join(workspacePath, PAN_DIRNAME, 'review'),\n join(workspacePath, WORKSPACE_RUNTIME_DIRNAME, 'review'),\n ];\n\n for (const reviewDir of paths) {\n if (!existsSync(reviewDir)) continue;\n\n try {\n const entries = readdirSync(reviewDir);\n const reviewDirs = entries.filter(name => /^agent-.*-review-/.test(name));\n if (reviewDirs.length === 0) continue;\n\n // Sort by mtime descending (newest first)\n const sorted = reviewDirs\n .map(name => ({ name, mtime: statSync(join(reviewDir, name)).mtime.getTime() }))\n .sort((a, b) => b.mtime - a.mtime);\n\n return join(reviewDir, sorted[0].name);\n } catch {\n continue;\n }\n }\n\n return null;\n}\n\n/**\n * Count blocking findings for a specific review run.\n * First tries synthesis.md '## Blocking Findings' heading count,\n * falls back to summing findBlockingFindings across .md report files,\n * returns null if no artifacts exist.\n */\nexport function countBlockingFindingsForRun(runDir: string): number | null {\n const synthesisPath = join(runDir, 'synthesis.md');\n\n // Try synthesis first\n if (existsSync(synthesisPath)) {\n try {\n const synthBody = readFileSync(synthesisPath, 'utf8');\n const count = countSynthesisBlockingFindings(synthBody);\n if (count > 0 || synthBody.includes('## Blocking Findings')) {\n return count;\n }\n } catch {\n // Fall through to report sum\n }\n }\n\n // Fall back to report sum\n try {\n const entries = readdirSync(runDir);\n const reportFiles = entries.filter(name => name.endsWith('.md') && name !== 'synthesis.md');\n\n if (reportFiles.length === 0) return null;\n\n let totalCount = 0;\n for (const file of reportFiles) {\n const content = readFileSync(join(runDir, file), 'utf8');\n const findings = findBlockingFindings(content);\n totalCount += findings.length;\n }\n\n return totalCount;\n } catch {\n return null;\n }\n}\n\n/**\n * Evaluate whether a review cycle series is converging.\n * Returns 'not-converging' when:\n * - counts.length >= 3 AND the series shows a reversal (count[n-1] > count[n-2]), OR\n * - the last two transitions are both non-decreases (going backwards)\n * Otherwise returns 'converging'.\n */\nexport function evaluateReviewConvergence(counts: number[]): 'converging' | 'not-converging' {\n if (counts.length < REVIEW_CONVERGENCE_MIN_CYCLES) {\n return 'converging';\n }\n\n const n = counts.length;\n\n // Check for reversal: the latest value > previous value (an increase after decreases)\n const hasReversal = counts[n - 1] > counts[n - 2];\n if (hasReversal) {\n return 'not-converging';\n }\n\n // Check for two consecutive non-decreases (stall):\n // counts[n-3] <= counts[n-2] AND counts[n-2] <= counts[n-1]\n const isFirstNonDecreasing = counts[n - 2] >= counts[n - 3];\n const isSecondNonDecreasing = counts[n - 1] >= counts[n - 2];\n if (isFirstNonDecreasing && isSecondNonDecreasing) {\n return 'not-converging';\n }\n\n return 'converging';\n}\n","import { normalizeReviewStatusSync } from './review-status-normalize.js';\nimport { upsertReviewStatusSync as dbUpsert, markWorkspaceStuck } from './overdeck/review-status-sync.js';\nimport type {\n BlockerReason,\n ReviewStatus,\n StatusHistoryEntry,\n} from './review-status-types.js';\nimport {\n countBlockingFindingsForRun,\n evaluateReviewConvergence,\n findLatestReviewRunDir,\n type ReviewCycleEntry,\n} from './cloister/review-convergence.js';\nimport { resolveProjectFromIssueSync } from './projects.js';\nimport { REVIEW_STATUS_HISTORY_LIMIT } from './review-status-limits.js';\n\nexport type { BlockerReason, ReviewStatus, StatusHistoryEntry } from './review-status-types.js';\n\nexport { REVIEW_STATUS_HISTORY_LIMIT };\n\ntype ReviewStatusJournal = {\n updatedAt: string;\n durable: Record<string, unknown>;\n clearedFields?: string[];\n};\n\nexport interface ReviewStatusReconcileHooks {\n notifyStatusChanged(issueId: string, status: ReviewStatus): void;\n deliverReviewVerdictFeedbackHostSide(issueId: string, status: ReviewStatus): Promise<void>;\n emitReactiveLifecycleEvent(type: 'review.approved' | 'test.passed', issueId: string): void;\n maybeAutoDispatchReviewHostSide(issueId: string, status: ReviewStatus): void;\n maybeRecoverTestVerdictHostSide(issueId: string, status: ReviewStatus): void;\n}\n\nexport function verificationSatisfied(\n status: Pick<ReviewStatus, 'verificationStatus'>,\n): boolean {\n return status.verificationStatus !== 'failed';\n}\n\n/**\n * The one reason a merged issue's verification is `skipped`. Every verification\n * run for a merged issue already returns this (`skipMergedVerification` in\n * cloister/verification-runner.ts).\n */\nexport const MERGED_VERIFICATION_REASON =\n 'Merge already landed; verify-on-main owns post-merge validation.';\n\n/**\n * PAN-3339: `pending` verification on a merged issue is a state with no owner.\n * Verification is dispatched only from inside the review pipeline, and that\n * pipeline never runs again once the issue merges — so the verdict recorded as\n * `pending` at finalization can never advance, and DoD row 3 blocks close-out\n * forever (observed on PAN-3296 with verificationCycleCount 0). The write door\n * settles it at the write that makes it unownable, using the same policy every\n * merged-issue verification run already applies. A merge lifecycle reset writes\n * mergeStatus 'pending' in the same update, so it never trips this.\n */\nexport function settleMergedVerification<\n T extends Pick<ReviewStatus, 'mergeStatus' | 'verificationStatus' | 'verificationNotes'>,\n>(status: T): T {\n if (status.mergeStatus !== 'merged' || status.verificationStatus !== 'pending') return status;\n return { ...status, verificationStatus: 'skipped', verificationNotes: MERGED_VERIFICATION_REASON };\n}\n\n/** PAN-1988: merge-gate predicate shared by direct writes and journal reconciliation. */\nexport function reviewGatesPassedSync(\n status: Pick<\n ReviewStatus,\n 'reviewStatus' | 'testStatus' | 'verificationStatus' | 'uatStatus' | 'mergeStatus'\n >,\n): boolean {\n return (\n (status.reviewStatus === 'passed' || status.reviewStatus === 'skipped') &&\n (status.testStatus === 'passed' || status.testStatus === 'skipped') &&\n verificationSatisfied(status) &&\n (status.uatStatus === undefined || status.uatStatus === 'passed') &&\n (status.mergeStatus === 'pending' ||\n status.mergeStatus === 'queued' ||\n status.mergeStatus === undefined ||\n status.mergeStatus === null)\n );\n}\n\n/** Reconcile a newer canonical journal verdict into the SQLite cache. */\nexport function reconcileJournalIntoCacheSync(\n issueId: string,\n dbStatus: ReviewStatus | null,\n journal: ReviewStatusJournal,\n hooks: ReviewStatusReconcileHooks,\n): ReviewStatus {\n const merged: ReviewStatus = {\n ...(dbStatus ?? {\n issueId,\n reviewStatus: 'pending' as const,\n testStatus: 'pending' as const,\n updatedAt: journal.updatedAt,\n readyForMerge: false,\n }),\n };\n for (const [key, value] of Object.entries(journal.durable)) {\n if (value !== undefined) (merged as unknown as Record<string, unknown>)[key] = value;\n }\n for (const key of journal.clearedFields ?? []) {\n delete (merged as unknown as Record<string, unknown>)[key];\n }\n merged.issueId = issueId;\n merged.updatedAt = journal.updatedAt;\n const hasBlockers = (merged.blockerReasons?.length ?? 0) > 0;\n merged.readyForMerge = hasBlockers ? false : reviewGatesPassedSync(merged);\n // PAN-3339: same settlement as the write door, so a journal record still\n // carrying the ownerless `pending` cannot reinstate it in the cache on read.\n const reconciled = normalizeReviewStatusSync(settleMergedVerification(merged));\n try {\n dbUpsert(reconciled);\n // PAN-2988 — the reconcile changed the effective status; the read model only\n // advances via events, so emit the transition the lost write never produced.\n hooks.notifyStatusChanged(issueId, reconciled);\n } catch {\n // Read-only DB (a sandboxed reader) — the host reconciles when it reads. Non-fatal.\n }\n\n const wasBlocked = dbStatus?.reviewStatus === 'blocked' || dbStatus?.reviewStatus === 'failed';\n const nowBlocked = reconciled.reviewStatus === 'blocked' || reconciled.reviewStatus === 'failed';\n if (nowBlocked && !wasBlocked) {\n // PAN-3151: record blocking-finding count and gate on convergence\n try {\n const project = resolveProjectFromIssueSync(issueId);\n if (!project) {\n console.warn(`[review-status] reconcile: cannot resolve project for ${issueId}, skipping cycle recording`);\n void hooks.deliverReviewVerdictFeedbackHostSide(issueId, reconciled);\n } else {\n const issueLower = issueId.toLowerCase();\n const workspacePath = `${project.projectPath}/workspaces/feature-${issueLower}`;\n const reviewRunDir = findLatestReviewRunDir(workspacePath);\n\n if (!reviewRunDir) {\n console.warn(`[review-status] reconcile: no review run dir found for ${issueId}, skipping cycle recording`);\n void hooks.deliverReviewVerdictFeedbackHostSide(issueId, reconciled);\n } else {\n const blockingCount = countBlockingFindingsForRun(reviewRunDir);\n if (blockingCount === null) {\n console.warn(`[review-status] reconcile: cannot count findings for ${issueId}, skipping cycle recording`);\n void hooks.deliverReviewVerdictFeedbackHostSide(issueId, reconciled);\n } else {\n // Use full directory basename as runId (format: agent-*-review-*)\n const runDirName = reviewRunDir.split('/').pop() ?? '';\n const runId = runDirName;\n\n // Ensure reviewCycleHistory is initialized\n if (!reconciled.reviewCycleHistory) {\n reconciled.reviewCycleHistory = [];\n }\n\n // Deduplicate by runId: if already recorded, skip appending\n const cycleNumber = reconciled.reviewCycleHistory.length + 1;\n const alreadyRecorded = reconciled.reviewCycleHistory.some(e => e.runId === runId);\n\n if (!alreadyRecorded) {\n const entry: ReviewCycleEntry = {\n cycle: cycleNumber,\n runId,\n atCommit: reconciled.reviewedAtCommit,\n blockingCount,\n recordedAt: new Date().toISOString(),\n };\n reconciled.reviewCycleHistory.push(entry);\n\n // Persist the appended cycle\n try {\n dbUpsert(reconciled);\n } catch {\n // Non-fatal: read-only DB\n }\n }\n\n // Evaluate convergence\n const counts = reconciled.reviewCycleHistory.map(e => e.blockingCount);\n const convergence = evaluateReviewConvergence(counts);\n\n if (convergence === 'not-converging') {\n // Gate engaged: mark stuck and emit error activity, skip feedback hook\n markWorkspaceStuck(issueId, 'review-not-converging', { counts });\n reconciled.stuck = true;\n reconciled.stuckReason = 'review-not-converging';\n reconciled.stuckAt = new Date().toISOString();\n reconciled.stuckDetails = JSON.stringify({ counts });\n\n // Persist stuck state\n try {\n dbUpsert(reconciled);\n } catch {\n // Non-fatal: read-only DB\n }\n\n // Emit error-level activity\n const countSeries = counts.join(' → ');\n console.error(\n `[review-status] reconcile: review loop not converging for ${issueId}: ${countSeries}. ` +\n `Consider decomposition (split the remaining work), or unstick to continue rework.`,\n );\n // TODO: emit activity entry to pipeline when activity recording is ready\n } else {\n // Converging: invoke feedback hook as normal\n void hooks.deliverReviewVerdictFeedbackHostSide(issueId, reconciled);\n }\n }\n }\n }\n } catch (error) {\n console.error(`[review-status] reconcile: cycle recording error for ${issueId}:`, error);\n // On any error, still deliver feedback (don't gate on an exception)\n void hooks.deliverReviewVerdictFeedbackHostSide(issueId, reconciled);\n }\n }\n\n const wasReviewPassed = dbStatus?.reviewStatus === 'passed';\n const nowReviewPassed = reconciled.reviewStatus === 'passed';\n if (nowReviewPassed && !wasReviewPassed && reconciled.testStatus === 'pending') {\n console.log(`[review-status] reconcile: review.approved for ${issueId} (host-owned handoff — sandboxed agent verdict from journal)`);\n hooks.emitReactiveLifecycleEvent('review.approved', issueId);\n }\n const wasTestPassed = dbStatus?.testStatus === 'passed';\n const nowTestPassed = reconciled.testStatus === 'passed';\n if (nowTestPassed && !wasTestPassed) {\n console.log(`[review-status] reconcile: test.passed for ${issueId} (host-owned handoff — sandboxed agent verdict from journal)`);\n hooks.emitReactiveLifecycleEvent('test.passed', issueId);\n }\n\n hooks.maybeAutoDispatchReviewHostSide(issueId, reconciled);\n hooks.maybeRecoverTestVerdictHostSide(issueId, reconciled);\n return reconciled;\n}\n","/**\n * PAN-1988 auto-heal — decide whether a review needs to be (re-)dispatched from the durable\n * journal intent, as a PURE function so it is locked by tests.\n *\n * The work agent's `pan done` writes a durable `reviewRequestedAt` into the journal/record (always\n * writable, even sandboxed) BEFORE it tries to reach the dashboard. If that reactive trigger is\n * dropped — the dashboard was mid-reload, the network blipped, the deacon is frozen — the intent\n * survives in the journal. The host reconciles on read: when a request is newer than the last\n * dispatch and nothing is currently reviewing, it dispatches review. This heals with NO deacon and\n * NO live dashboard event, on the next status read.\n *\n * Returns true when a review dispatch is owed:\n * - a request exists (`reviewRequestedAt` set), AND\n * - the request is no more than seven days old, AND\n * - it is newer than the last spawn (or there was never a spawn) — i.e. a genuinely un-serviced\n * request, not the request that produced the current review, AND\n * - review is pending rather than already reviewing or terminal, AND\n * - the issue is not already ready to merge or merged.\n *\n * Genuine re-review paths reset `reviewStatus` to `pending` before recording a fresh request: `pan\n * done` does this for a new commit, and the operator force-review route does it explicitly.\n */\nexport const REVIEW_REQUEST_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;\n\nexport function isReviewRequestStale(params: {\n reviewRequestedAt?: string;\n now?: number;\n maxAgeMs?: number;\n}): boolean {\n if (!params.reviewRequestedAt) return false;\n const now = params.now ?? Date.now();\n const maxAgeMs = params.maxAgeMs ?? REVIEW_REQUEST_MAX_AGE_MS;\n return now - Date.parse(params.reviewRequestedAt) > maxAgeMs;\n}\n\nexport function needsReviewDispatch(params: {\n reviewRequestedAt?: string;\n reviewSpawnedAt?: string | number;\n reviewStatus?: string;\n mergeStatus?: string;\n readyForMerge?: boolean;\n now?: number;\n maxRequestAgeMs?: number;\n}): boolean {\n if (!params.reviewRequestedAt) return false;\n if (isReviewRequestStale({\n reviewRequestedAt: params.reviewRequestedAt,\n now: params.now,\n maxAgeMs: params.maxRequestAgeMs,\n })) return false;\n if (params.reviewStatus === 'reviewing') return false;\n if (params.reviewStatus === 'passed' || params.reviewStatus === 'skipped') return false;\n if (params.readyForMerge) return false;\n if (params.mergeStatus === 'merged') return false;\n return !params.reviewSpawnedAt || Date.parse(params.reviewRequestedAt) > new Date(params.reviewSpawnedAt).getTime();\n}\n","import { readActiveReviewArtifactContext } from './agents/agent-state-source.js';\nimport { readMemoizedArtifactVerdict } from './cloister/synthesis-verdict.js';\nimport { enrichReviewNotesFromRecordSync, readJournalStatusSync } from './overdeck/review-status-record-sync.js';\nimport {\n reconcileJournalIntoCacheSync,\n type ReviewStatus,\n type ReviewStatusReconcileHooks,\n} from './review-status-reconcile.js';\nimport { staleVerdictSnapshotAgainstLiveCycle } from './pan-dir/pipeline-verdict-merge.js';\n\nexport interface ReviewStatusReadHooks extends ReviewStatusReconcileHooks {\n deleteStatus(issueId: string): void;\n}\n\nexport function resolveJournalReconciledReviewStatusSync(\n issueId: string,\n dbStatus: ReviewStatus | null | undefined,\n hooks: ReviewStatusReadHooks,\n): ReviewStatus | null {\n const journal = readJournalStatusSync(issueId);\n if (!journal) return dbStatus ?? null;\n\n if ((journal.durable as { closedOut?: boolean }).closedOut === true) {\n try {\n hooks.deleteStatus(issueId);\n } catch {\n // Read-only DB (a sandboxed reader) — the host clears residue when it reads. Non-fatal.\n }\n return null;\n }\n\n const journalNewer = !dbStatus || (dbStatus.updatedAt ?? '') < journal.updatedAt;\n if (journalNewer) {\n const staleSnapshot = dbStatus\n ? staleVerdictSnapshotAgainstLiveCycle(\n dbStatus as unknown as Record<string, unknown>,\n journal.durable as unknown as Record<string, unknown>,\n )\n : null;\n if (staleSnapshot) {\n const liveStatus = dbStatus!;\n // PAN-3511: the normal status-read path stays filesystem-free. Only after\n // the existing stale-refusal predicate matches do we consult the bounded\n // active-run memo, and only to corroborate a terminal journal verdict.\n const journalVerdict = (journal.durable as { reviewStatus?: unknown }).reviewStatus;\n const review = readActiveReviewArtifactContext(issueId);\n const artifact = typeof journalVerdict === 'string' && review\n ? readMemoizedArtifactVerdict(issueId, review)\n : null;\n const hostRunHeadMatchesLive = Boolean(\n review?.roleRunHead\n && liveStatus.lastVerifiedCommit\n && review.roleRunHead === liveStatus.lastVerifiedCommit,\n );\n const artifactHeadMatchesHostRun = Boolean(\n !artifact?.headSha || artifact.headSha === review?.roleRunHead,\n );\n if (\n artifact\n && artifact.verdict === journalVerdict\n && hostRunHeadMatchesLive\n && artifactHeadMatchesHostRun\n ) {\n console.log(\n `[review-status] Active-run artifact corroborated the stale journal verdict with a live review-head binding for ${issueId}; replaying the terminal journal result.`,\n );\n return reconcileJournalIntoCacheSync(issueId, dbStatus ?? null, journal, hooks);\n }\n console.warn(\n `[review-status] Refusing stale journal verdict replay for ${issueId}: `\n + `live cycle ${new Date(staleSnapshot.liveCycle).toISOString()} at HEAD ${staleSnapshot.liveHead ?? 'unknown'} `\n + `supersedes snapshot cycle ${staleSnapshot.snapshotCycle ? new Date(staleSnapshot.snapshotCycle).toISOString() : 'unknown'} `\n + `at HEAD ${staleSnapshot.snapshotHead ?? 'unknown'}.`,\n );\n return dbStatus ?? null;\n }\n return reconcileJournalIntoCacheSync(issueId, dbStatus ?? null, journal, hooks);\n }\n\n const enriched = enrichReviewNotesFromRecordSync(issueId, dbStatus!);\n hooks.maybeAutoDispatchReviewHostSide(issueId, enriched);\n hooks.maybeRecoverTestVerdictHostSide(issueId, enriched);\n return enriched;\n}\n","import { dirname, posix, sep } from \"path\";\nfunction createModulerModifier() {\n const getModuleFromFileName = createGetModuleFromFilename();\n return async (frames)=>{\n for (const frame of frames)frame.module = getModuleFromFileName(frame.filename);\n return frames;\n };\n}\nfunction createGetModuleFromFilename(basePath = process.argv[1] ? dirname(process.argv[1]) : process.cwd(), isWindows = '\\\\' === sep) {\n const normalizedBase = isWindows ? normalizeWindowsPath(basePath) : basePath;\n return (filename)=>{\n if (!filename) return;\n const normalizedFilename = isWindows ? normalizeWindowsPath(filename) : filename;\n let { dir, base: file, ext } = posix.parse(normalizedFilename);\n if ('.js' === ext || '.mjs' === ext || '.cjs' === ext) file = file.slice(0, -1 * ext.length);\n const decodedFile = decodeURIComponent(file);\n if (!dir) dir = '.';\n const n = dir.lastIndexOf('/node_modules');\n if (n > -1) return `${dir.slice(n + 14).replace(/\\//g, '.')}:${decodedFile}`;\n if (dir.startsWith(normalizedBase)) {\n const moduleName = dir.slice(normalizedBase.length + 1).replace(/\\//g, '.');\n return moduleName ? `${moduleName}:${decodedFile}` : decodedFile;\n }\n return decodedFile;\n };\n}\nfunction normalizeWindowsPath(path) {\n return path.replace(/^[A-Z]:/, '').replace(/\\\\/g, '/');\n}\nexport { createModulerModifier };\n","const normalizeFlagsResponse = (flagsResponse)=>{\n if ('flags' in flagsResponse) {\n const featureFlags = getFlagValuesFromFlags(flagsResponse.flags);\n const featureFlagPayloads = getPayloadsFromFlags(flagsResponse.flags);\n return {\n ...flagsResponse,\n featureFlags,\n featureFlagPayloads\n };\n }\n {\n const featureFlags = flagsResponse.featureFlags ?? {};\n const featureFlagPayloads = Object.fromEntries(Object.entries(flagsResponse.featureFlagPayloads || {}).map(([k, v])=>[\n k,\n parsePayload(v)\n ]));\n const flags = Object.fromEntries(Object.entries(featureFlags).map(([key, value])=>[\n key,\n getFlagDetailFromFlagAndPayload(key, value, featureFlagPayloads[key])\n ]));\n return {\n ...flagsResponse,\n featureFlags,\n featureFlagPayloads,\n flags\n };\n }\n};\nfunction getFlagDetailFromFlagAndPayload(key, value, payload) {\n return {\n key: key,\n enabled: 'string' == typeof value ? true : value,\n variant: 'string' == typeof value ? value : void 0,\n reason: void 0,\n metadata: {\n id: void 0,\n version: void 0,\n payload: payload ? JSON.stringify(payload) : void 0,\n description: void 0\n }\n };\n}\nconst getFlagValuesFromFlags = (flags)=>Object.fromEntries(Object.entries(flags ?? {}).map(([key, detail])=>[\n key,\n getFeatureFlagValue(detail)\n ]).filter(([, value])=>void 0 !== value));\nconst getPayloadsFromFlags = (flags)=>{\n const safeFlags = flags ?? {};\n return Object.fromEntries(Object.keys(safeFlags).filter((flag)=>{\n const details = safeFlags[flag];\n return details.enabled && details.metadata && void 0 !== details.metadata.payload;\n }).map((flag)=>{\n const payload = safeFlags[flag].metadata?.payload;\n return [\n flag,\n payload ? parsePayload(payload) : void 0\n ];\n }));\n};\nconst getFeatureFlagValue = (detail)=>void 0 === detail ? void 0 : detail.variant ?? detail.enabled;\nconst parsePayload = (response)=>{\n if ('string' != typeof response) return response;\n try {\n return JSON.parse(response);\n } catch {\n return response;\n }\n};\nconst createFlagsResponseFromFlagsAndPayloads = (featureFlags, featureFlagPayloads)=>{\n const allKeys = [\n ...new Set([\n ...Object.keys(featureFlags ?? {}),\n ...Object.keys(featureFlagPayloads ?? {})\n ])\n ];\n const enabledFlags = allKeys.filter((flag)=>!!featureFlags[flag] || !!featureFlagPayloads[flag]).reduce((res, key)=>(res[key] = featureFlags[key] ?? true, res), {});\n const flagDetails = {\n featureFlags: enabledFlags,\n featureFlagPayloads: featureFlagPayloads ?? {}\n };\n return normalizeFlagsResponse(flagDetails);\n};\nconst updateFlagValue = (flag, value)=>({\n ...flag,\n enabled: getEnabledFromValue(value),\n variant: getVariantFromValue(value)\n });\nfunction getEnabledFromValue(value) {\n return 'string' == typeof value ? true : value;\n}\nfunction getVariantFromValue(value) {\n return 'string' == typeof value ? value : void 0;\n}\nconst flagDetailsToResults = (flagDetails)=>Object.values(flagDetails).map((detail)=>{\n const value = detail.variant ?? detail.enabled;\n const rawPayload = detail.metadata?.payload;\n return {\n key: detail.key,\n enabled: getEnabledFromValue(value),\n variant: getVariantFromValue(value),\n payload: void 0 !== rawPayload ? parsePayload(rawPayload) : null\n };\n });\nconst MINIMAL_FLAG_CALLED_EVENT_PROPERTIES = [\n '$feature_flag',\n '$feature_flag_response',\n '$feature_flag_has_experiment',\n '$feature_flag_id',\n '$feature_flag_version',\n '$feature_flag_reason',\n '$feature_flag_request_id',\n '$feature_flag_evaluated_at',\n '$feature_flag_error',\n 'locally_evaluated',\n '$groups',\n '$process_person_profile',\n '$geoip_disable',\n '$current_url',\n '$pathname',\n '$session_id',\n '$window_id',\n '$lib',\n '$lib_version',\n '$device_id',\n '$is_server'\n];\nconst minimizeFlagCalledEventProperties = (properties, transportKeys = [])=>{\n const minimal = {};\n const copyKey = (key)=>{\n if (void 0 !== properties[key]) minimal[key] = properties[key];\n };\n MINIMAL_FLAG_CALLED_EVENT_PROPERTIES.forEach(copyKey);\n transportKeys.forEach(copyKey);\n return minimal;\n};\nexport { MINIMAL_FLAG_CALLED_EVENT_PROPERTIES, createFlagsResponseFromFlagsAndPayloads, flagDetailsToResults, getEnabledFromValue, getFeatureFlagValue, getFlagValuesFromFlags, getPayloadsFromFlags, getVariantFromValue, minimizeFlagCalledEventProperties, normalizeFlagsResponse, parsePayload, updateFlagValue };\n","var types_PostHogPersistedProperty = /*#__PURE__*/ function(PostHogPersistedProperty) {\n PostHogPersistedProperty[\"AnonymousId\"] = \"anonymous_id\";\n PostHogPersistedProperty[\"DistinctId\"] = \"distinct_id\";\n PostHogPersistedProperty[\"Props\"] = \"props\";\n PostHogPersistedProperty[\"EnablePersonProcessing\"] = \"enable_person_processing\";\n PostHogPersistedProperty[\"PersonMode\"] = \"person_mode\";\n PostHogPersistedProperty[\"FeatureFlagDetails\"] = \"feature_flag_details\";\n PostHogPersistedProperty[\"FeatureFlags\"] = \"feature_flags\";\n PostHogPersistedProperty[\"FeatureFlagPayloads\"] = \"feature_flag_payloads\";\n PostHogPersistedProperty[\"BootstrapFeatureFlagDetails\"] = \"bootstrap_feature_flag_details\";\n PostHogPersistedProperty[\"BootstrapFeatureFlags\"] = \"bootstrap_feature_flags\";\n PostHogPersistedProperty[\"BootstrapFeatureFlagPayloads\"] = \"bootstrap_feature_flag_payloads\";\n PostHogPersistedProperty[\"OverrideFeatureFlags\"] = \"override_feature_flags\";\n PostHogPersistedProperty[\"Queue\"] = \"queue\";\n PostHogPersistedProperty[\"AiQueue\"] = \"ai_queue\";\n PostHogPersistedProperty[\"LogsQueue\"] = \"logs_queue\";\n PostHogPersistedProperty[\"OptedOut\"] = \"opted_out\";\n PostHogPersistedProperty[\"SessionId\"] = \"session_id\";\n PostHogPersistedProperty[\"SessionStartTimestamp\"] = \"session_start_timestamp\";\n PostHogPersistedProperty[\"SessionLastTimestamp\"] = \"session_timestamp\";\n PostHogPersistedProperty[\"PersonProperties\"] = \"person_properties\";\n PostHogPersistedProperty[\"GroupProperties\"] = \"group_properties\";\n PostHogPersistedProperty[\"InstalledAppBuild\"] = \"installed_app_build\";\n PostHogPersistedProperty[\"InstalledAppVersion\"] = \"installed_app_version\";\n PostHogPersistedProperty[\"SessionReplay\"] = \"session_replay\";\n PostHogPersistedProperty[\"SessionReplayEventTriggerActivatedSession\"] = \"session_replay_event_trigger_activated_session\";\n PostHogPersistedProperty[\"SurveyLastSeenDate\"] = \"survey_last_seen_date\";\n PostHogPersistedProperty[\"SurveysSeen\"] = \"surveys_seen\";\n PostHogPersistedProperty[\"Surveys\"] = \"surveys\";\n PostHogPersistedProperty[\"RemoteConfig\"] = \"remote_config\";\n PostHogPersistedProperty[\"FlagsEndpointWasHit\"] = \"flags_endpoint_was_hit\";\n PostHogPersistedProperty[\"DeviceId\"] = \"device_id\";\n return PostHogPersistedProperty;\n}({});\nvar types_Compression = /*#__PURE__*/ function(Compression) {\n Compression[\"GZipJS\"] = \"gzip-js\";\n Compression[\"Base64\"] = \"base64\";\n return Compression;\n}({});\nconst FeatureFlagError = {\n ERRORS_WHILE_COMPUTING: 'errors_while_computing_flags',\n FLAG_MISSING: 'flag_missing',\n QUOTA_LIMITED: 'quota_limited',\n TIMEOUT: 'timeout',\n CONNECTION_ERROR: 'connection_error',\n UNKNOWN_ERROR: 'unknown_error',\n apiError: (status)=>`api_error_${status}`\n};\nconst SurveyPosition = {\n TopLeft: 'top_left',\n TopCenter: 'top_center',\n TopRight: 'top_right',\n MiddleLeft: 'middle_left',\n MiddleCenter: 'middle_center',\n MiddleRight: 'middle_right',\n Left: 'left',\n Right: 'right',\n Center: 'center'\n};\nconst SurveyWidgetType = {\n Button: 'button',\n Tab: 'tab',\n Selector: 'selector'\n};\nconst SurveyType = {\n Popover: 'popover',\n API: 'api',\n Widget: 'widget',\n ExternalSurvey: 'external_survey'\n};\nconst SurveyQuestionDescriptionContentType = {\n Html: 'html',\n Text: 'text'\n};\nconst SurveyValidationType = {\n MinLength: 'min_length',\n MaxLength: 'max_length'\n};\nconst SurveyRatingDisplay = {\n Number: 'number',\n Emoji: 'emoji'\n};\nconst SurveyQuestionType = {\n Open: 'open',\n MultipleChoice: 'multiple_choice',\n SingleChoice: 'single_choice',\n Rating: 'rating',\n Link: 'link'\n};\nconst SurveyQuestionBranchingType = {\n NextQuestion: 'next_question',\n End: 'end',\n ResponseBased: 'response_based',\n SpecificQuestion: 'specific_question'\n};\nconst SurveyMatchType = {\n Regex: 'regex',\n NotRegex: 'not_regex',\n Exact: 'exact',\n IsNot: 'is_not',\n Icontains: 'icontains',\n NotIcontains: 'not_icontains'\n};\nconst SurveySchedule = {\n Once: 'once',\n Recurring: 'recurring',\n Always: 'always'\n};\nconst ActionStepStringMatching = {\n Contains: 'contains',\n Exact: 'exact',\n Regex: 'regex'\n};\nconst knownUnsafeEditableEvent = [\n '$snapshot',\n '$pageview',\n '$pageleave',\n '$set',\n 'survey dismissed',\n 'survey sent',\n 'survey shown',\n '$identify',\n '$groupidentify',\n '$create_alias',\n '$$client_ingestion_warning',\n '$web_experiment_applied',\n '$feature_enrollment_update',\n '$feature_flag_called'\n];\nconst knownUnsafeEditableEventProperty = [\n 'token'\n];\nexport { ActionStepStringMatching, types_Compression as Compression, FeatureFlagError, types_PostHogPersistedProperty as PostHogPersistedProperty, SurveyMatchType, SurveyPosition, SurveyQuestionBranchingType, SurveyQuestionDescriptionContentType, SurveyQuestionType, SurveyRatingDisplay, SurveySchedule, SurveyType, SurveyValidationType, SurveyWidgetType, knownUnsafeEditableEvent, knownUnsafeEditableEventProperty };\n","import { Compression } from \"./types.mjs\";\nfunction isGzipSupported() {\n return 'CompressionStream' in globalThis && 'TextEncoder' in globalThis && 'Response' in globalThis && 'function' == typeof Response.prototype.blob;\n}\nconst NATIVE_GZIP_VALIDATION_ERROR = 'NativeGzipValidationError';\nconst GZIP_MAGIC_FIRST_BYTE = 0x1f;\nconst GZIP_MAGIC_SECOND_BYTE = 0x8b;\nconst GZIP_DEFLATE_METHOD = 0x08;\nconst hasGzipMagic = (bytes)=>bytes.length >= 2 && bytes[0] === GZIP_MAGIC_FIRST_BYTE && bytes[1] === GZIP_MAGIC_SECOND_BYTE;\nconst isGzipData = (body)=>{\n if (body instanceof ArrayBuffer) return hasGzipMagic(new Uint8Array(body));\n if (ArrayBuffer.isView(body)) return hasGzipMagic(new Uint8Array(body.buffer, body.byteOffset, body.byteLength));\n return false;\n};\nconst isGzipRequest = (compression, urlCompression)=>compression === Compression.GZipJS || urlCompression === Compression.GZipJS || 'gzip' === urlCompression;\nconst isNativeAsyncGzipReadError = (error)=>{\n if (!error || 'object' != typeof error) return false;\n const name = 'name' in error ? String(error.name) : '';\n return 'NotReadableError' === name;\n};\nconst isNativeAsyncGzipError = (error)=>{\n if (!error || 'object' != typeof error) return false;\n const name = 'name' in error ? String(error.name) : '';\n return isNativeAsyncGzipReadError(error) || name === NATIVE_GZIP_VALIDATION_ERROR;\n};\nlet crc32Table;\nconst getCrc32Table = ()=>{\n if (crc32Table) return crc32Table;\n crc32Table = [];\n for(let i = 0; i < 256; i++){\n let crc = i;\n for(let j = 0; j < 8; j++)crc = 1 & crc ? 0xedb88320 ^ crc >>> 1 : crc >>> 1;\n crc32Table[i] = crc >>> 0;\n }\n return crc32Table;\n};\nconst crc32 = (bytes)=>{\n const table = getCrc32Table();\n let crc = 0xffffffff;\n for(let i = 0; i < bytes.length; i++)crc = table[(crc ^ bytes[i]) & 0xff] ^ crc >>> 8;\n return (0xffffffff ^ crc) >>> 0;\n};\nconst throwNativeGzipValidationError = (reason)=>{\n const error = new Error(`Native gzip produced invalid output: ${reason}`);\n error.name = NATIVE_GZIP_VALIDATION_ERROR;\n throw error;\n};\nconst validateNativeGzip = async (compressed, inputBytes)=>{\n if (compressed.size < 18) throwNativeGzipValidationError('too-short');\n const header = new Uint8Array(await compressed.slice(0, 10).arrayBuffer());\n if (!hasGzipMagic(header) || header[2] !== GZIP_DEFLATE_METHOD) throwNativeGzipValidationError('invalid-header');\n const trailer = new DataView(await compressed.slice(compressed.size - 8).arrayBuffer());\n if (trailer.getUint32(0, true) !== crc32(inputBytes)) throwNativeGzipValidationError('invalid-crc');\n const inputSize = inputBytes.length >>> 0;\n if (trailer.getUint32(4, true) !== inputSize) throwNativeGzipValidationError('invalid-size');\n};\nasync function gzipCompress(input, isDebug = true, options) {\n try {\n const inputBytes = new TextEncoder().encode(input);\n const compressedStream = new globalThis.CompressionStream('gzip');\n const writer = compressedStream.writable.getWriter();\n const writePromise = writer.write(inputBytes).then(()=>writer.close()).catch(async (err)=>{\n try {\n await writer.abort(err);\n } catch {}\n throw err;\n });\n const responsePromise = new Response(compressedStream.readable).blob();\n const [compressed] = await Promise.all([\n responsePromise,\n writePromise\n ]);\n await validateNativeGzip(compressed, inputBytes);\n return compressed;\n } catch (error) {\n if (options?.rethrow) throw error;\n if (isDebug) console.error('Failed to gzip compress data', error);\n return null;\n }\n}\nexport { gzipCompress, isGzipData, isGzipRequest, isGzipSupported, isNativeAsyncGzipError, isNativeAsyncGzipReadError };\n","const DEFAULT_BLOCKED_UA_STRS = [\n 'amazonbot',\n 'amazonproductbot',\n 'app.hypefactors.com',\n 'applebot',\n 'archive.org_bot',\n 'awariobot',\n 'backlinksextendedbot',\n 'baiduspider',\n 'bingbot',\n 'bingpreview',\n 'chrome-lighthouse',\n 'dataforseobot',\n 'deepscan',\n 'duckduckbot',\n 'facebookexternal',\n 'facebookcatalog',\n 'http://yandex.com/bots',\n 'hubspot',\n 'ia_archiver',\n 'leikibot',\n 'linkedinbot',\n 'meta-externalagent',\n 'mj12bot',\n 'msnbot',\n 'nessus',\n 'petalbot',\n 'pinterest',\n 'prerender',\n 'rogerbot',\n 'screaming frog',\n 'sebot-wa',\n 'sitebulb',\n 'slackbot',\n 'slurp',\n 'trendictionbot',\n 'turnitin',\n 'twitterbot',\n 'vercel-screenshot',\n 'vercelbot',\n 'yahoo! slurp',\n 'yandexbot',\n 'zoombot',\n 'bot.htm',\n 'bot.php',\n '(bot;',\n 'bot/',\n 'crawler',\n 'ahrefsbot',\n 'ahrefssiteaudit',\n 'semrushbot',\n 'siteauditbot',\n 'splitsignalbot',\n 'gptbot',\n 'oai-searchbot',\n 'chatgpt-user',\n 'perplexitybot',\n 'better uptime bot',\n 'sentryuptimebot',\n 'uptimerobot',\n 'headlesschrome',\n 'cypress',\n 'google-hoteladsverifier',\n 'adsbot-google',\n 'apis-google',\n 'duplexweb-google',\n 'feedfetcher-google',\n 'google favicon',\n 'google web preview',\n 'google-read-aloud',\n 'googlebot',\n 'googleother',\n 'google-cloudvertexbot',\n 'googleweblight',\n 'mediapartners-google',\n 'storebot-google',\n 'google-inspectiontool',\n 'bytespider'\n];\nconst isBlockedUA = function(ua, customBlockedUserAgents = []) {\n if (!ua) return false;\n const uaLower = ua.toLowerCase();\n return DEFAULT_BLOCKED_UA_STRS.concat(customBlockedUserAgents).some((blockedUA)=>{\n const blockedUaLower = blockedUA.toLowerCase();\n return -1 !== uaLower.indexOf(blockedUaLower);\n });\n};\nexport { DEFAULT_BLOCKED_UA_STRS, isBlockedUA };\n","function includes(str, needle) {\n return -1 !== str.indexOf(needle);\n}\nconst trim = function(str) {\n return str.trim();\n};\nconst stripLeadingDollar = function(s) {\n return s.replace(/^\\$/, '');\n};\nfunction isDistinctIdStringLike(value) {\n return [\n 'distinct_id',\n 'distinctid'\n ].includes(value.toLowerCase());\n}\nfunction safeJsonStringify(value) {\n const ancestors = [];\n return JSON.stringify(value, function(_key, replacementValue) {\n if ('bigint' == typeof replacementValue) return replacementValue.toString();\n if ('function' == typeof replacementValue || 'symbol' == typeof replacementValue) return;\n if (replacementValue instanceof Error) return {\n name: replacementValue.name,\n message: replacementValue.message,\n stack: replacementValue.stack\n };\n if (replacementValue && 'object' == typeof replacementValue) {\n while(ancestors.length > 0 && ancestors[ancestors.length - 1] !== this)ancestors.pop();\n if (ancestors.includes(replacementValue)) return '[Circular]';\n ancestors.push(replacementValue);\n }\n return replacementValue;\n }) ?? 'null';\n}\nfunction deepSortKeys(value) {\n if (null === value || 'object' != typeof value) return value;\n if (Array.isArray(value)) return value.map(deepSortKeys);\n return Object.keys(value).sort().reduce((acc, key)=>{\n acc[key] = deepSortKeys(value[key]);\n return acc;\n }, {});\n}\nfunction getPersonPropertiesHash(distinct_id, userPropertiesToSet, userPropertiesToSetOnce) {\n return JSON.stringify({\n distinct_id,\n userPropertiesToSet: userPropertiesToSet ? deepSortKeys(userPropertiesToSet) : void 0,\n userPropertiesToSetOnce: userPropertiesToSetOnce ? deepSortKeys(userPropertiesToSetOnce) : void 0\n });\n}\nexport { getPersonPropertiesHash, includes, isDistinctIdStringLike, safeJsonStringify, stripLeadingDollar, trim };\n","import { knownUnsafeEditableEvent, knownUnsafeEditableEventProperty } from \"../types.mjs\";\nimport { includes } from \"./string-utils.mjs\";\nconst nativeIsArray = Array.isArray;\nconst ObjProto = Object.prototype;\nconst type_utils_hasOwnProperty = ObjProto.hasOwnProperty;\nconst type_utils_toString = ObjProto.toString;\nconst isArray = nativeIsArray || function(obj) {\n return '[object Array]' === type_utils_toString.call(obj);\n};\nconst isFunction = (x)=>'function' == typeof x;\nconst isNativeFunction = (x)=>isFunction(x) && -1 !== x.toString().indexOf('[native code]');\nconst isObject = (x)=>x === Object(x) && !isArray(x);\nconst isEmptyObject = (x)=>{\n if (isObject(x)) {\n for(const key in x)if (type_utils_hasOwnProperty.call(x, key)) return false;\n return true;\n }\n return false;\n};\nconst isUndefined = (x)=>void 0 === x;\nconst isString = (x)=>'[object String]' == type_utils_toString.call(x);\nconst isEmptyString = (x)=>isString(x) && 0 === x.trim().length;\nconst isNull = (x)=>null === x;\nconst isNullish = (x)=>isUndefined(x) || isNull(x);\nconst isNumber = (x)=>'[object Number]' == type_utils_toString.call(x) && x === x;\nconst isPositiveNumber = (value)=>isNumber(value) && value > 0;\nconst isBoolean = (x)=>'[object Boolean]' === type_utils_toString.call(x);\nconst isFormData = (x)=>x instanceof FormData;\nconst isFile = (x)=>x instanceof File;\nconst isPlainError = (x)=>x instanceof Error;\nconst isKnownUnsafeEditableEvent = (x)=>includes(knownUnsafeEditableEvent, x);\nconst isKnownUnsafeEditableEventProperty = (x)=>includes(knownUnsafeEditableEventProperty, x);\nfunction isPrimitive(value) {\n return null === value || 'object' != typeof value;\n}\nfunction isBuiltin(candidate, className) {\n return Object.prototype.toString.call(candidate) === `[object ${className}]`;\n}\nfunction isError(candidate) {\n switch(Object.prototype.toString.call(candidate)){\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n case '[object DOMError]':\n case '[object WebAssembly.Exception]':\n return true;\n default:\n return isInstanceOf(candidate, Error);\n }\n}\nfunction isErrorEvent(event) {\n return isBuiltin(event, 'ErrorEvent');\n}\nfunction isEvent(candidate) {\n return 'undefined' != typeof Event && isInstanceOf(candidate, Event);\n}\nfunction isPlainObject(candidate) {\n return isBuiltin(candidate, 'Object');\n}\nfunction isInstanceOf(candidate, base) {\n try {\n return candidate instanceof base;\n } catch {\n return false;\n }\n}\nconst yesLikeValues = [\n true,\n 'true',\n 1,\n '1',\n 'yes'\n];\nconst isYesLike = (val)=>includes(yesLikeValues, val);\nconst noLikeValues = [\n false,\n 'false',\n 0,\n '0',\n 'no'\n];\nconst isNoLike = (val)=>includes(noLikeValues, val);\nexport { type_utils_hasOwnProperty as hasOwnProperty, isArray, isBoolean, isBuiltin, isEmptyObject, isEmptyString, isError, isErrorEvent, isEvent, isFile, isFormData, isFunction, isKnownUnsafeEditableEvent, isKnownUnsafeEditableEventProperty, isNativeFunction, isNoLike, isNull, isNullish, isNumber, isObject, isPlainError, isPlainObject, isPositiveNumber, isPrimitive, isString, isUndefined, isYesLike, noLikeValues, yesLikeValues };\n","import { isNumber } from \"./type-utils.mjs\";\nfunction clampToRange(value, min, max, logger, fallbackValue) {\n if (min > max) {\n logger.warn('min cannot be greater than max.');\n min = max;\n }\n if (isNumber(value)) if (value > max) {\n logger.warn(' cannot be greater than max: ' + max + '. Using max value instead.');\n return max;\n } else {\n if (!(value < min)) return value;\n logger.warn(' cannot be less than min: ' + min + '. Using min value instead.');\n return min;\n }\n logger.warn(' must be a number. using max or fallback. max: ' + max + ', fallback: ' + fallbackValue);\n return clampToRange(fallbackValue || max, min, max, logger);\n}\nfunction getRemoteConfigBool(field, key, defaultValue = true) {\n if (null == field) return defaultValue;\n if ('boolean' == typeof field) return field;\n if ('object' == typeof field) {\n const value = field[key];\n return 'boolean' == typeof value ? value : defaultValue;\n }\n return defaultValue;\n}\nfunction getRemoteConfigNumber(field, key) {\n if (null == field || 'object' != typeof field) return;\n const value = field[key];\n if ('number' == typeof value && Number.isFinite(value)) return value;\n if ('string' == typeof value) {\n const trimmed = value.trim();\n if ('' === trimmed) return;\n const parsed = Number(trimmed);\n return Number.isFinite(parsed) ? parsed : void 0;\n }\n}\nfunction isValidSampleRate(value) {\n return 'number' == typeof value && Number.isFinite(value) && value >= 0 && value <= 1;\n}\nexport { clampToRange, getRemoteConfigBool, getRemoteConfigNumber, isValidSampleRate };\n","import { clampToRange } from \"./number-utils.mjs\";\nconst ONE_DAY_IN_MS = 86400000;\nconst DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE = 1;\nconst DEFAULT_EXCEPTION_RATE_LIMITER_BUCKET_SIZE = 10;\nfunction resolveExceptionRateLimiterConfig(config = {}) {\n return {\n refillRate: config.exceptionRateLimiterRefillRate ?? config.__exceptionRateLimiterRefillRate ?? DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE,\n bucketSize: config.exceptionRateLimiterBucketSize ?? config.__exceptionRateLimiterBucketSize ?? DEFAULT_EXCEPTION_RATE_LIMITER_BUCKET_SIZE\n };\n}\nclass BucketedRateLimiter {\n constructor(options){\n this._buckets = {};\n this._onBucketRateLimited = options._onBucketRateLimited;\n this._bucketSize = clampToRange(options.bucketSize, 0, 100, options._logger);\n this._refillRate = clampToRange(options.refillRate, 0, this._bucketSize, options._logger);\n this._refillInterval = clampToRange(options.refillInterval, 0, ONE_DAY_IN_MS, options._logger);\n }\n _applyRefill(bucket, now) {\n const elapsedMs = now - bucket.lastAccess;\n const refillIntervals = Math.floor(elapsedMs / this._refillInterval);\n if (refillIntervals > 0) {\n const tokensToAdd = refillIntervals * this._refillRate;\n bucket.tokens = Math.min(bucket.tokens + tokensToAdd, this._bucketSize);\n bucket.lastAccess = bucket.lastAccess + refillIntervals * this._refillInterval;\n }\n }\n consumeRateLimit(key) {\n const now = Date.now();\n const keyStr = String(key);\n let bucket = this._buckets[keyStr];\n if (bucket) this._applyRefill(bucket, now);\n else {\n bucket = {\n tokens: this._bucketSize,\n lastAccess: now\n };\n this._buckets[keyStr] = bucket;\n }\n if (0 === bucket.tokens) return true;\n bucket.tokens--;\n if (0 === bucket.tokens) this._onBucketRateLimited?.(key);\n return 0 === bucket.tokens;\n }\n stop() {\n this._buckets = {};\n }\n}\nexport { BucketedRateLimiter, DEFAULT_EXCEPTION_RATE_LIMITER_BUCKET_SIZE, DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE, resolveExceptionRateLimiterConfig };\n","/*! For license information please see uuidv7.mjs.LICENSE.txt */\n/**\n * uuidv7: An experimental implementation of the proposed UUID Version 7\n *\n * @license Apache-2.0\n * @copyright 2021-2023 LiosK\n * @packageDocumentation\n */ const DIGITS = \"0123456789abcdef\";\nclass UUID {\n constructor(bytes){\n this.bytes = bytes;\n }\n static ofInner(bytes) {\n if (16 === bytes.length) return new UUID(bytes);\n throw new TypeError(\"not 128-bit length\");\n }\n static fromFieldsV7(unixTsMs, randA, randBHi, randBLo) {\n if (!Number.isInteger(unixTsMs) || !Number.isInteger(randA) || !Number.isInteger(randBHi) || !Number.isInteger(randBLo) || unixTsMs < 0 || randA < 0 || randBHi < 0 || randBLo < 0 || unixTsMs > 0xffffffffffff || randA > 0xfff || randBHi > 0x3fffffff || randBLo > 0xffffffff) throw new RangeError(\"invalid field value\");\n const bytes = new Uint8Array(16);\n bytes[0] = unixTsMs / 2 ** 40;\n bytes[1] = unixTsMs / 2 ** 32;\n bytes[2] = unixTsMs / 2 ** 24;\n bytes[3] = unixTsMs / 2 ** 16;\n bytes[4] = unixTsMs / 256;\n bytes[5] = unixTsMs;\n bytes[6] = 0x70 | randA >>> 8;\n bytes[7] = randA;\n bytes[8] = 0x80 | randBHi >>> 24;\n bytes[9] = randBHi >>> 16;\n bytes[10] = randBHi >>> 8;\n bytes[11] = randBHi;\n bytes[12] = randBLo >>> 24;\n bytes[13] = randBLo >>> 16;\n bytes[14] = randBLo >>> 8;\n bytes[15] = randBLo;\n return new UUID(bytes);\n }\n static parse(uuid) {\n let hex;\n switch(uuid.length){\n case 32:\n hex = /^[0-9a-f]{32}$/i.exec(uuid)?.[0];\n break;\n case 36:\n hex = /^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(uuid)?.slice(1, 6).join(\"\");\n break;\n case 38:\n hex = /^\\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\\}$/i.exec(uuid)?.slice(1, 6).join(\"\");\n break;\n case 45:\n hex = /^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(uuid)?.slice(1, 6).join(\"\");\n break;\n default:\n break;\n }\n if (hex) {\n const inner = new Uint8Array(16);\n for(let i = 0; i < 16; i += 4){\n const n = parseInt(hex.substring(2 * i, 2 * i + 8), 16);\n inner[i + 0] = n >>> 24;\n inner[i + 1] = n >>> 16;\n inner[i + 2] = n >>> 8;\n inner[i + 3] = n;\n }\n return new UUID(inner);\n }\n throw new SyntaxError(\"could not parse UUID string\");\n }\n toString() {\n let text = \"\";\n for(let i = 0; i < this.bytes.length; i++){\n text += DIGITS.charAt(this.bytes[i] >>> 4);\n text += DIGITS.charAt(0xf & this.bytes[i]);\n if (3 === i || 5 === i || 7 === i || 9 === i) text += \"-\";\n }\n return text;\n }\n toHex() {\n let text = \"\";\n for(let i = 0; i < this.bytes.length; i++){\n text += DIGITS.charAt(this.bytes[i] >>> 4);\n text += DIGITS.charAt(0xf & this.bytes[i]);\n }\n return text;\n }\n toJSON() {\n return this.toString();\n }\n getVariant() {\n const n = this.bytes[8] >>> 4;\n if (n < 0) throw new Error(\"unreachable\");\n if (n <= 7) return this.bytes.every((e)=>0 === e) ? \"NIL\" : \"VAR_0\";\n if (n <= 11) return \"VAR_10\";\n if (n <= 13) return \"VAR_110\";\n if (n <= 15) return this.bytes.every((e)=>0xff === e) ? \"MAX\" : \"VAR_RESERVED\";\n else throw new Error(\"unreachable\");\n }\n getVersion() {\n return \"VAR_10\" === this.getVariant() ? this.bytes[6] >>> 4 : void 0;\n }\n clone() {\n return new UUID(this.bytes.slice(0));\n }\n equals(other) {\n return 0 === this.compareTo(other);\n }\n compareTo(other) {\n for(let i = 0; i < 16; i++){\n const diff = this.bytes[i] - other.bytes[i];\n if (0 !== diff) return Math.sign(diff);\n }\n return 0;\n }\n}\nclass V7Generator {\n constructor(randomNumberGenerator){\n this.timestamp = 0;\n this.counter = 0;\n this.random = randomNumberGenerator ?? getDefaultRandom();\n }\n generate() {\n return this.generateOrResetCore(Date.now(), 10000);\n }\n generateOrAbort() {\n return this.generateOrAbortCore(Date.now(), 10000);\n }\n generateOrResetCore(unixTsMs, rollbackAllowance) {\n let value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);\n if (void 0 === value) {\n this.timestamp = 0;\n value = this.generateOrAbortCore(unixTsMs, rollbackAllowance);\n }\n return value;\n }\n generateOrAbortCore(unixTsMs, rollbackAllowance) {\n const MAX_COUNTER = 0x3ffffffffff;\n if (!Number.isInteger(unixTsMs) || unixTsMs < 1 || unixTsMs > 0xffffffffffff) throw new RangeError(\"`unixTsMs` must be a 48-bit positive integer\");\n if (rollbackAllowance < 0 || rollbackAllowance > 0xffffffffffff) throw new RangeError(\"`rollbackAllowance` out of reasonable range\");\n if (unixTsMs > this.timestamp) {\n this.timestamp = unixTsMs;\n this.resetCounter();\n } else {\n if (!(unixTsMs + rollbackAllowance >= this.timestamp)) return;\n this.counter++;\n if (this.counter > MAX_COUNTER) {\n this.timestamp++;\n this.resetCounter();\n }\n }\n return UUID.fromFieldsV7(this.timestamp, Math.trunc(this.counter / 2 ** 30), this.counter & 2 ** 30 - 1, this.random.nextUint32());\n }\n resetCounter() {\n this.counter = 0x400 * this.random.nextUint32() + (0x3ff & this.random.nextUint32());\n }\n generateV4() {\n const bytes = new Uint8Array(Uint32Array.of(this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32(), this.random.nextUint32()).buffer);\n bytes[6] = 0x40 | bytes[6] >>> 4;\n bytes[8] = 0x80 | bytes[8] >>> 2;\n return UUID.ofInner(bytes);\n }\n}\nconst getDefaultRandom = ()=>({\n nextUint32: ()=>0x10000 * Math.trunc(0x10000 * Math.random()) + Math.trunc(0x10000 * Math.random())\n });\nlet defaultGenerator;\nconst uuidv7 = ()=>uuidv7obj().toString();\nconst uuidv7obj = ()=>(defaultGenerator || (defaultGenerator = new V7Generator())).generate();\nconst uuidv4 = ()=>uuidv4obj().toString();\nconst uuidv4obj = ()=>(defaultGenerator || (defaultGenerator = new V7Generator())).generateV4();\nexport { UUID, V7Generator, uuidv4, uuidv4obj, uuidv7, uuidv7obj };\n","import { uuidv7 } from \"../vendor/uuidv7.mjs\";\nclass PromiseQueue {\n add(promise) {\n const promiseUUID = uuidv7();\n const id = ++this.nextId;\n this.promiseByIds[promiseUUID] = {\n id,\n promise\n };\n promise.catch(()=>{}).finally(()=>{\n delete this.promiseByIds[promiseUUID];\n });\n return promise;\n }\n async join() {\n let promises = Object.values(this.promiseByIds).map((item)=>item.promise);\n let length = promises.length;\n while(length > 0){\n await Promise.all(promises);\n promises = Object.values(this.promiseByIds).map((item)=>item.promise);\n length = promises.length;\n }\n }\n getPromises(ignoredPromises = [], maxId = this.nextId) {\n const ignoredPromiseSet = new Set(ignoredPromises);\n return Object.values(this.promiseByIds).filter((item)=>item.id <= maxId && !ignoredPromiseSet.has(item.promise)).map((item)=>item.promise);\n }\n get maxId() {\n return this.nextId;\n }\n get length() {\n return Object.keys(this.promiseByIds).length;\n }\n constructor(){\n this.promiseByIds = {};\n this.nextId = 0;\n }\n}\nexport { PromiseQueue };\n","function createConsole(consoleLike = console) {\n const lockedMethods = {\n log: consoleLike.log.bind(consoleLike),\n warn: consoleLike.warn.bind(consoleLike),\n error: consoleLike.error.bind(consoleLike),\n debug: consoleLike.debug.bind(consoleLike)\n };\n return lockedMethods;\n}\nconst _createLogger = (prefix, maybeCall, consoleLike)=>{\n function _log(level, ...args) {\n maybeCall(()=>{\n const consoleMethod = consoleLike[level];\n consoleMethod(prefix, ...args);\n });\n }\n const logger = {\n debug: (...args)=>{\n _log('debug', ...args);\n },\n info: (...args)=>{\n _log('log', ...args);\n },\n warn: (...args)=>{\n _log('warn', ...args);\n },\n error: (...args)=>{\n _log('error', ...args);\n },\n critical: (...args)=>{\n consoleLike['error'](prefix, ...args);\n },\n createLogger: (additionalPrefix)=>_createLogger(`${prefix} ${additionalPrefix}`, maybeCall, consoleLike)\n };\n return logger;\n};\nconst passThrough = (fn)=>fn();\nfunction createLogger(prefix, maybeCall = passThrough) {\n return _createLogger(prefix, maybeCall, createConsole());\n}\nexport { _createLogger, createLogger };\n","import { includes } from \"./string-utils.mjs\";\nimport { isFunction, isUndefined } from \"./type-utils.mjs\";\nconst FACEBOOK = 'Facebook';\nconst MOBILE = 'Mobile';\nconst IOS = 'iOS';\nconst ANDROID = 'Android';\nconst TABLET = 'Tablet';\nconst ANDROID_TABLET = ANDROID + ' ' + TABLET;\nconst IPAD = 'iPad';\nconst APPLE = 'Apple';\nconst APPLE_WATCH = APPLE + ' Watch';\nconst SAFARI = 'Safari';\nconst BLACKBERRY = 'BlackBerry';\nconst SAMSUNG = 'Samsung';\nconst SAMSUNG_BROWSER = SAMSUNG + 'Browser';\nconst SAMSUNG_INTERNET = SAMSUNG + ' Internet';\nconst CHROME = 'Chrome';\nconst CHROME_OS = CHROME + ' OS';\nconst CHROME_IOS = CHROME + ' ' + IOS;\nconst INTERNET_EXPLORER = 'Internet Explorer';\nconst INTERNET_EXPLORER_MOBILE = INTERNET_EXPLORER + ' ' + MOBILE;\nconst OPERA = 'Opera';\nconst OPERA_MINI = OPERA + ' Mini';\nconst EDGE = 'Edge';\nconst MICROSOFT_EDGE = 'Microsoft ' + EDGE;\nconst FIREFOX = 'Firefox';\nconst FIREFOX_IOS = FIREFOX + ' ' + IOS;\nconst NINTENDO = 'Nintendo';\nconst PLAYSTATION = 'PlayStation';\nconst XBOX = 'Xbox';\nconst ANDROID_MOBILE = ANDROID + ' ' + MOBILE;\nconst MOBILE_SAFARI = MOBILE + ' ' + SAFARI;\nconst WINDOWS = 'Windows';\nconst WINDOWS_PHONE = WINDOWS + ' Phone';\nconst NOKIA = 'Nokia';\nconst OUYA = 'Ouya';\nconst GENERIC = 'Generic';\nconst GENERIC_MOBILE = GENERIC + ' ' + MOBILE.toLowerCase();\nconst GENERIC_TABLET = GENERIC + ' ' + TABLET.toLowerCase();\nconst KONQUEROR = 'Konqueror';\nconst OCULUS_BROWSER = 'Oculus Browser';\nconst VIVALDI = 'Vivaldi';\nconst YANDEX = 'Yandex';\nconst WHALE = 'Whale';\nconst DUCKDUCKGO = 'DuckDuckGo';\nconst PALE_MOON = 'Pale Moon';\nconst WATERFOX = 'Waterfox';\nconst BRAVE = 'Brave';\nconst GOOGLE_SEARCH_APP = 'Google Search App';\nconst BROWSER_VERSION_REGEX_SUFFIX = '(\\\\d+(\\\\.\\\\d+)?)';\nconst DEFAULT_BROWSER_VERSION_REGEX = new RegExp('Version/' + BROWSER_VERSION_REGEX_SUFFIX);\nfunction browserFromHints(hints) {\n if (hints?.brave) return BRAVE;\n return null;\n}\nconst XBOX_REGEX = new RegExp(XBOX, 'i');\nconst PLAYSTATION_REGEX = new RegExp(PLAYSTATION + ' \\\\w+', 'i');\nconst NINTENDO_REGEX = new RegExp(NINTENDO + ' \\\\w+', 'i');\nconst BLACKBERRY_REGEX = new RegExp(BLACKBERRY + '|PlayBook|BB10', 'i');\nconst windowsVersionMap = {\n 'NT3.51': 'NT 3.11',\n 'NT4.0': 'NT 4.0',\n '5.0': '2000',\n '5.1': 'XP',\n '5.2': 'XP',\n '6.0': 'Vista',\n '6.1': '7',\n '6.2': '8',\n '6.3': '8.1',\n '6.4': '10',\n '10.0': '10'\n};\nfunction isSafari(userAgent) {\n return includes(userAgent, SAFARI) && !includes(userAgent, CHROME) && !includes(userAgent, ANDROID);\n}\nconst safariCheck = (ua, vendor)=>vendor && includes(vendor, APPLE) || isSafari(ua);\nconst detectBrowser = function(user_agent, vendor, hints, options) {\n vendor = vendor || '';\n const fromHints = browserFromHints(hints);\n if (fromHints) return fromHints;\n if (options?.detectGoogleSearchApp && includes(user_agent, 'GSA/')) return GOOGLE_SEARCH_APP;\n if (includes(user_agent, ' OPR/') && includes(user_agent, 'Mini')) return OPERA_MINI;\n if (includes(user_agent, ' OPR/')) return OPERA;\n if (BLACKBERRY_REGEX.test(user_agent)) return BLACKBERRY;\n if (includes(user_agent, 'IE' + MOBILE) || includes(user_agent, 'WPDesktop')) return INTERNET_EXPLORER_MOBILE;\n if (includes(user_agent, 'OculusBrowser')) return OCULUS_BROWSER;\n else if (includes(user_agent, SAMSUNG_BROWSER)) return SAMSUNG_INTERNET;\n else if (includes(user_agent, EDGE) || includes(user_agent, 'Edg/')) return MICROSOFT_EDGE;\n else if (includes(user_agent, VIVALDI + '/')) return VIVALDI;\n else if (includes(user_agent, 'YaBrowser/')) return YANDEX;\n else if (includes(user_agent, WHALE + '/')) return WHALE;\n else if (includes(user_agent, DUCKDUCKGO + '/') || includes(user_agent, 'Ddg/')) return DUCKDUCKGO;\n else if (includes(user_agent, 'FBIOS')) return FACEBOOK + ' ' + MOBILE;\n else if (includes(user_agent, 'UCWEB') || includes(user_agent, 'UCBrowser')) return 'UC Browser';\n else if (includes(user_agent, 'CriOS')) return CHROME_IOS;\n else if (includes(user_agent, 'CrMo')) return CHROME;\n else if (includes(user_agent, CHROME)) return CHROME;\n else if (includes(user_agent, ANDROID) && includes(user_agent, SAFARI)) return ANDROID_MOBILE;\n else if (includes(user_agent, 'FxiOS')) return FIREFOX_IOS;\n else if (includes(user_agent.toLowerCase(), KONQUEROR.toLowerCase())) return KONQUEROR;\n else if (includes(user_agent, BRAVE + '/')) return BRAVE;\n else if (safariCheck(user_agent, vendor)) return includes(user_agent, MOBILE) ? MOBILE_SAFARI : SAFARI;\n else if (includes(user_agent, 'PaleMoon/')) return PALE_MOON;\n else if (includes(user_agent, WATERFOX + '/')) return WATERFOX;\n else if (includes(user_agent, FIREFOX)) return FIREFOX;\n else if (includes(user_agent, 'MSIE') || includes(user_agent, 'Trident/')) return INTERNET_EXPLORER;\n else if (includes(user_agent, 'Gecko')) return FIREFOX;\n return '';\n};\nconst versionRegexes = {\n [INTERNET_EXPLORER_MOBILE]: [\n new RegExp('rv:' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [MICROSOFT_EDGE]: [\n new RegExp(EDGE + '?\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [CHROME]: [\n new RegExp('(' + CHROME + '|CrMo)\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [CHROME_IOS]: [\n new RegExp('CriOS\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n 'UC Browser': [\n new RegExp('(UCBrowser|UCWEB)\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [SAFARI]: [\n DEFAULT_BROWSER_VERSION_REGEX\n ],\n [MOBILE_SAFARI]: [\n DEFAULT_BROWSER_VERSION_REGEX\n ],\n [OPERA]: [\n new RegExp('(' + OPERA + '|OPR)\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [FIREFOX]: [\n new RegExp(FIREFOX + '\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [FIREFOX_IOS]: [\n new RegExp('FxiOS\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [KONQUEROR]: [\n new RegExp('Konqueror[:/]?' + BROWSER_VERSION_REGEX_SUFFIX, 'i')\n ],\n [BLACKBERRY]: [\n new RegExp(BLACKBERRY + ' ' + BROWSER_VERSION_REGEX_SUFFIX),\n DEFAULT_BROWSER_VERSION_REGEX\n ],\n [ANDROID_MOBILE]: [\n new RegExp('android\\\\s' + BROWSER_VERSION_REGEX_SUFFIX, 'i')\n ],\n [SAMSUNG_INTERNET]: [\n new RegExp(SAMSUNG_BROWSER + '\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [OCULUS_BROWSER]: [\n new RegExp('OculusBrowser\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [VIVALDI]: [\n new RegExp(VIVALDI + '\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [YANDEX]: [\n new RegExp('YaBrowser\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [WHALE]: [\n new RegExp(WHALE + '\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [BRAVE]: [\n new RegExp(BRAVE + '\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [DUCKDUCKGO]: [\n new RegExp('(DuckDuckGo|Ddg)\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [PALE_MOON]: [\n new RegExp('PaleMoon\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [WATERFOX]: [\n new RegExp(WATERFOX + '\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [GOOGLE_SEARCH_APP]: [\n new RegExp('GSA\\\\/' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n [INTERNET_EXPLORER]: [\n new RegExp('(rv:|MSIE )' + BROWSER_VERSION_REGEX_SUFFIX)\n ],\n Mozilla: [\n new RegExp('rv:' + BROWSER_VERSION_REGEX_SUFFIX)\n ]\n};\nconst detectBrowserVersion = function(userAgent, vendor, hints, options) {\n const browser = detectBrowser(userAgent, vendor, hints, options);\n const regexes = versionRegexes[browser];\n if (isUndefined(regexes)) return null;\n for(let i = 0; i < regexes.length; i++){\n const regex = regexes[i];\n const matches = userAgent.match(regex);\n if (matches) return parseFloat(matches[matches.length - 2]);\n }\n return null;\n};\nconst osMatchers = [\n [\n new RegExp(XBOX + '; ' + XBOX + ' (.*?)[);]', 'i'),\n (match)=>[\n XBOX,\n match && match[1] || ''\n ]\n ],\n [\n new RegExp(NINTENDO, 'i'),\n [\n NINTENDO,\n ''\n ]\n ],\n [\n new RegExp(PLAYSTATION, 'i'),\n [\n PLAYSTATION,\n ''\n ]\n ],\n [\n BLACKBERRY_REGEX,\n [\n BLACKBERRY,\n ''\n ]\n ],\n [\n new RegExp(WINDOWS, 'i'),\n (_, user_agent)=>{\n if (/Phone/.test(user_agent) || /WPDesktop/.test(user_agent)) return [\n WINDOWS_PHONE,\n ''\n ];\n if (new RegExp(MOBILE).test(user_agent) && !/IEMobile\\b/.test(user_agent)) return [\n WINDOWS + ' ' + MOBILE,\n ''\n ];\n const match = /Windows NT ([0-9.]+)/i.exec(user_agent);\n if (match && match[1]) {\n const version = match[1];\n let osVersion = windowsVersionMap[version] || '';\n if (/arm/i.test(user_agent)) osVersion = 'RT';\n return [\n WINDOWS,\n osVersion\n ];\n }\n return [\n WINDOWS,\n ''\n ];\n }\n ],\n [\n /((iPhone|iPad|iPod).*?OS (\\d+)_(\\d+)_?(\\d+)?|iPhone)/,\n (match)=>{\n if (match && match[3]) {\n const versionParts = [\n match[3],\n match[4],\n match[5] || '0'\n ];\n return [\n IOS,\n versionParts.join('.')\n ];\n }\n return [\n IOS,\n ''\n ];\n }\n ],\n [\n /(watch.*\\/(\\d+\\.\\d+\\.\\d+)|watch os,(\\d+\\.\\d+),)/i,\n (match)=>{\n let version = '';\n if (match && match.length >= 3) version = isUndefined(match[2]) ? match[3] : match[2];\n return [\n 'watchOS',\n version\n ];\n }\n ],\n [\n new RegExp('(' + ANDROID + ' (\\\\d+)\\\\.(\\\\d+)\\\\.?(\\\\d+)?|' + ANDROID + ')', 'i'),\n (match)=>{\n if (match && match[2]) {\n const versionParts = [\n match[2],\n match[3],\n match[4] || '0'\n ];\n return [\n ANDROID,\n versionParts.join('.')\n ];\n }\n return [\n ANDROID,\n ''\n ];\n }\n ],\n [\n /Mac OS X (\\d+)[_.](\\d+)[_.]?(\\d+)?/i,\n (match)=>{\n const result = [\n 'Mac OS X',\n ''\n ];\n if (match && match[1]) {\n const versionParts = [\n match[1],\n match[2],\n match[3] || '0'\n ];\n result[1] = versionParts.join('.');\n }\n return result;\n }\n ],\n [\n /Mac/i,\n [\n 'Mac OS X',\n ''\n ]\n ],\n [\n /CrOS/,\n [\n CHROME_OS,\n ''\n ]\n ],\n [\n /Linux|debian/i,\n [\n 'Linux',\n ''\n ]\n ]\n];\nconst detectOS = function(user_agent) {\n for(let i = 0; i < osMatchers.length; i++){\n const [rgex, resultOrFn] = osMatchers[i];\n const match = rgex.exec(user_agent);\n const result = match && (isFunction(resultOrFn) ? resultOrFn(match, user_agent) : resultOrFn);\n if (result) return result;\n }\n return [\n '',\n ''\n ];\n};\nconst detectDevice = function(user_agent) {\n if (NINTENDO_REGEX.test(user_agent)) return NINTENDO;\n if (PLAYSTATION_REGEX.test(user_agent)) return PLAYSTATION;\n if (XBOX_REGEX.test(user_agent)) return XBOX;\n if (new RegExp(OUYA, 'i').test(user_agent)) return OUYA;\n if (new RegExp('(' + WINDOWS_PHONE + '|WPDesktop)', 'i').test(user_agent)) return WINDOWS_PHONE;\n else if (/iPad/.test(user_agent)) return IPAD;\n else if (/iPod/.test(user_agent)) return 'iPod Touch';\n else if (/iPhone/.test(user_agent)) return 'iPhone';\n else if (/(watch)(?: ?os[,/]|\\d,\\d\\/)[\\d.]+/i.test(user_agent)) return APPLE_WATCH;\n else if (BLACKBERRY_REGEX.test(user_agent)) return BLACKBERRY;\n else if (/(kobo)\\s(ereader|touch)/i.test(user_agent)) return 'Kobo';\n else if (new RegExp(NOKIA, 'i').test(user_agent)) return NOKIA;\n else if (/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\\))/i.test(user_agent) || /(kf[a-z]+)( bui|\\)).+silk\\//i.test(user_agent)) return 'Kindle Fire';\n else if (/(Android|ZTE)/i.test(user_agent)) if (!(!new RegExp(MOBILE).test(user_agent) || /(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(user_agent))) return ANDROID;\n else {\n if (/pixel[\\daxl ]{1,6}/i.test(user_agent) && !/pixel c/i.test(user_agent) || /(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(user_agent) || /lmy47v/i.test(user_agent) && !/QTAQZ3/i.test(user_agent)) return ANDROID;\n return ANDROID_TABLET;\n }\n else if (new RegExp('(pda|' + MOBILE + ')', 'i').test(user_agent)) return GENERIC_MOBILE;\n else if (new RegExp(TABLET, 'i').test(user_agent) && !new RegExp(TABLET + ' pc', 'i').test(user_agent)) return GENERIC_TABLET;\n else return '';\n};\nconst detectDeviceType = function(user_agent, options) {\n const device = detectDevice(user_agent);\n if (device === IPAD || device === ANDROID_TABLET || 'Kobo' === device || 'Kindle Fire' === device || device === GENERIC_TABLET) return TABLET;\n if (device === NINTENDO || device === XBOX || device === PLAYSTATION || device === OUYA) return 'Console';\n if (device === APPLE_WATCH) return 'Wearable';\n if (device) return MOBILE;\n if (options?.userAgentDataPlatform === 'Android' && (options?.maxTouchPoints ?? 0) > 0) {\n const shortSide = Math.min(options?.screenWidth ?? 0, options?.screenHeight ?? 0);\n const shortSideDp = shortSide / (options?.devicePixelRatio ?? 1);\n return shortSideDp >= 600 ? TABLET : MOBILE;\n }\n return 'Desktop';\n};\nexport { detectBrowser, detectBrowserVersion, detectDevice, detectDeviceType, detectOS };\n","export * from \"./bot-detection.mjs\";\nexport * from \"./bucketed-rate-limiter.mjs\";\nexport * from \"./number-utils.mjs\";\nexport * from \"./string-utils.mjs\";\nexport * from \"./type-utils.mjs\";\nexport * from \"./promise-queue.mjs\";\nexport * from \"./logger.mjs\";\nexport * from \"./user-agent-utils.mjs\";\nconst STRING_FORMAT = 'utf8';\nconst UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nfunction isValidUUID(value) {\n return 'string' == typeof value && UUID_REGEX.test(value);\n}\nfunction getEventUuid(uuid, generateUuid) {\n return isValidUUID(uuid) ? uuid : generateUuid();\n}\nfunction assert(truthyValue, message) {\n if (!truthyValue || 'string' != typeof truthyValue || isEmpty(truthyValue)) throw new Error(message);\n}\nfunction isEmpty(truthyValue) {\n if (0 === truthyValue.trim().length) return true;\n return false;\n}\nfunction removeTrailingSlash(url) {\n return url?.replace(/\\/+$/, '');\n}\nfunction stripUrlHash(url) {\n if (!url) return url;\n return url.split('#')[0];\n}\nasync function retriable(fn, props) {\n let lastError = null;\n for(let i = 0; i < props.retryCount + 1; i++){\n if (i > 0) await new Promise((r)=>setTimeout(r, props.retryDelay));\n try {\n const res = await fn();\n return res;\n } catch (e) {\n lastError = e;\n if (!props.retryCheck(e)) throw e;\n }\n }\n throw lastError;\n}\nfunction currentTimestamp() {\n return new Date().getTime();\n}\nfunction currentISOTime() {\n return new Date().toISOString();\n}\nfunction safeSetTimeout(fn, timeout) {\n const t = setTimeout(fn, timeout);\n t?.unref && t?.unref();\n return t;\n}\nconst isPromise = (obj)=>obj && 'function' == typeof obj.then;\nconst isError = (x)=>x instanceof Error;\nfunction getFetch() {\n return 'undefined' != typeof fetch ? fetch : void 0 !== globalThis.fetch ? globalThis.fetch : void 0;\n}\nfunction allSettled(promises) {\n return Promise.all(promises.map((p)=>(p ?? Promise.resolve()).then((value)=>({\n status: 'fulfilled',\n value\n }), (reason)=>({\n status: 'rejected',\n reason\n }))));\n}\nexport { STRING_FORMAT, UUID_REGEX, allSettled, assert, currentISOTime, currentTimestamp, getEventUuid, getFetch, isError, isPromise, isValidUUID, removeTrailingSlash, retriable, safeSetTimeout, stripUrlHash };\n","import { isArray, isBoolean, isNull, isNullish, isUndefined } from \"../utils/index.mjs\";\nconst OTLP_SEVERITY_MAP = {\n trace: {\n text: 'TRACE',\n number: 1\n },\n debug: {\n text: 'DEBUG',\n number: 5\n },\n info: {\n text: 'INFO',\n number: 9\n },\n warn: {\n text: 'WARN',\n number: 13\n },\n error: {\n text: 'ERROR',\n number: 17\n },\n fatal: {\n text: 'FATAL',\n number: 21\n }\n};\nconst DEFAULT_OTLP_SEVERITY = OTLP_SEVERITY_MAP.info;\nfunction getOtlpSeverityText(level) {\n return (OTLP_SEVERITY_MAP[level] || DEFAULT_OTLP_SEVERITY).text;\n}\nfunction getOtlpSeverityNumber(level) {\n return (OTLP_SEVERITY_MAP[level] || DEFAULT_OTLP_SEVERITY).number;\n}\nfunction toOtlpAnyValue(value) {\n if (isBoolean(value)) return {\n boolValue: value\n };\n if ('number' == typeof value) {\n if (!Number.isFinite(value)) return {\n stringValue: String(value)\n };\n if (Number.isInteger(value)) return {\n intValue: value\n };\n return {\n doubleValue: value\n };\n }\n if ('string' == typeof value) return {\n stringValue: value\n };\n if (isArray(value)) return {\n arrayValue: {\n values: value.map((v)=>toOtlpAnyValue(v))\n }\n };\n try {\n return {\n stringValue: JSON.stringify(value)\n };\n } catch {\n return {\n stringValue: String(value)\n };\n }\n}\nfunction toOtlpKeyValueList(attrs) {\n const result = [];\n for(const key in attrs){\n const value = attrs[key];\n if (!(isNull(value) || isUndefined(value))) result.push({\n key,\n value: toOtlpAnyValue(value)\n });\n }\n return result;\n}\nfunction timestampToUnixNano() {\n return String(Date.now()) + '000000';\n}\nfunction buildOtlpLogRecord(options, sdkContext) {\n const level = options.level || 'info';\n const { text: severityText, number: severityNumber } = OTLP_SEVERITY_MAP[level] || DEFAULT_OTLP_SEVERITY;\n const now = timestampToUnixNano();\n const autoAttributes = {};\n if (sdkContext.distinctId) autoAttributes.posthogDistinctId = sdkContext.distinctId;\n if (sdkContext.sessionId) autoAttributes.sessionId = sdkContext.sessionId;\n if (sdkContext.windowId) autoAttributes['window.id'] = sdkContext.windowId;\n if (!isNullish(sdkContext.sessionStartTimestamp)) autoAttributes.sessionStartTimestamp = String(sdkContext.sessionStartTimestamp);\n if (!isNullish(sdkContext.lastActivityTimestamp)) autoAttributes.lastActivityTimestamp = String(sdkContext.lastActivityTimestamp);\n if (sdkContext.currentUrl) autoAttributes['url.full'] = sdkContext.currentUrl;\n if (sdkContext.screenName) autoAttributes['screen.name'] = sdkContext.screenName;\n if (sdkContext.appState) autoAttributes['app.state'] = sdkContext.appState;\n if (sdkContext.activeFeatureFlags && sdkContext.activeFeatureFlags.length > 0) autoAttributes.feature_flags = sdkContext.activeFeatureFlags;\n const mergedAttributes = {\n ...autoAttributes,\n ...options.attributes || {}\n };\n const record = {\n timeUnixNano: now,\n observedTimeUnixNano: now,\n severityNumber,\n severityText,\n body: {\n stringValue: options.body\n },\n attributes: toOtlpKeyValueList(mergedAttributes)\n };\n if (options.trace_id) record.traceId = options.trace_id;\n if (options.span_id) record.spanId = options.span_id;\n if (!isUndefined(options.trace_flags)) record.flags = options.trace_flags;\n return record;\n}\nfunction buildResourceAttributes(config, sdkName, sdkVersion) {\n return {\n ...config.resourceAttributes,\n 'service.name': config.serviceName || 'unknown_service',\n ...config.environment && {\n 'deployment.environment': config.environment\n },\n ...config.serviceVersion && {\n 'service.version': config.serviceVersion\n },\n 'telemetry.sdk.name': sdkName,\n 'telemetry.sdk.version': sdkVersion\n };\n}\nfunction buildOtlpLogsPayload(logRecords, resourceAttributes, scopeName, scopeVersion) {\n return {\n resourceLogs: [\n {\n resource: {\n attributes: toOtlpKeyValueList(resourceAttributes)\n },\n scopeLogs: [\n {\n scope: {\n name: scopeName,\n version: scopeVersion\n },\n logRecords\n }\n ]\n }\n ]\n };\n}\nexport { buildOtlpLogRecord, buildOtlpLogsPayload, buildResourceAttributes, getOtlpSeverityNumber, getOtlpSeverityText, toOtlpAnyValue, toOtlpKeyValueList };\n","import { buildOtlpLogRecord, buildOtlpLogsPayload, buildResourceAttributes } from \"./logs-utils.mjs\";\nimport { PostHogPersistedProperty } from \"../types.mjs\";\nimport { isArray, safeSetTimeout } from \"../utils/index.mjs\";\nconst MAX_FLUSH_BACKOFF_EXPONENT = 6;\nclass PostHogLogs {\n constructor(_instance, _config, _logger, _getContext, _onReady, _waitForStoragePersist = ()=>Promise.resolve(), _scopeName){\n this._instance = _instance;\n this._config = _config;\n this._logger = _logger;\n this._getContext = _getContext;\n this._onReady = _onReady;\n this._waitForStoragePersist = _waitForStoragePersist;\n this._scopeName = _scopeName;\n this._flushPromise = null;\n this._evictedSinceAdvance = 0;\n this._consecutiveFlushFailures = 0;\n this._intervalWindowStart = 0;\n this._intervalLogCount = 0;\n this._droppedWarned = false;\n this._maxBufferSize = _config.maxBufferSize;\n this._maxQueueSize = Math.max(_config.maxQueueSize ?? _config.maxBufferSize, _config.maxBufferSize);\n this._flushIntervalMs = _config.flushIntervalMs;\n this._maxBatchRecordsPerPost = _config.maxBatchRecordsPerPost;\n this._rateCapWindowMs = _config.rateCapWindowMs;\n this._maxLogsPerInterval = _config.maxLogsPerInterval;\n }\n reset() {\n this._clearFlushTimer();\n this._flushPromise = null;\n this._intervalWindowStart = 0;\n this._intervalLogCount = 0;\n this._droppedWarned = false;\n this._evictedSinceAdvance = 0;\n this._consecutiveFlushFailures = 0;\n this._maxBatchRecordsPerPost = this._config.maxBatchRecordsPerPost;\n }\n onReconnect() {\n this._consecutiveFlushFailures = 0;\n this._flushInBackground();\n }\n captureLog(options) {\n if (this._instance.isDisabled) return;\n if (this._instance.optedOut) return;\n if (!options?.body) return;\n const filtered = this._runBeforeSend(options);\n if (null === filtered) return;\n if (!filtered.body) return void this._logger.info(\"Log was rejected in beforeSend function\");\n if (!this._checkRateLimit()) return;\n const record = buildOtlpLogRecord(filtered, this._getContext());\n const entry = {\n record\n };\n this._onReady(()=>this._enqueue(entry));\n }\n _runBeforeSend(options) {\n const beforeSend = this._config.beforeSend;\n if (!beforeSend) return options;\n const fns = isArray(beforeSend) ? beforeSend : [\n beforeSend\n ];\n let result = options;\n for (const fn of fns)try {\n const next = fn(result);\n if (!next) {\n this._logger.info(\"Log was rejected in beforeSend function\");\n return null;\n }\n result = next;\n } catch (e) {\n this._logger.error(\"Error in beforeSend function for log:\", e);\n return null;\n }\n return result;\n }\n _checkRateLimit() {\n if (void 0 === this._maxLogsPerInterval) return true;\n const now = Date.now();\n const elapsed = now - this._intervalWindowStart;\n if (elapsed >= this._rateCapWindowMs || elapsed < 0) {\n this._intervalWindowStart = now;\n this._intervalLogCount = 0;\n this._droppedWarned = false;\n }\n if (this._intervalLogCount >= this._maxLogsPerInterval) {\n if (!this._droppedWarned) {\n this._logger.warn(`captureLog dropping logs: exceeded ${this._maxLogsPerInterval} logs per ${this._rateCapWindowMs}ms`);\n this._droppedWarned = true;\n }\n return false;\n }\n this._intervalLogCount++;\n return true;\n }\n async flush() {\n if (this._instance.isDisabled) return;\n if (this._flushPromise) return this._flushPromise;\n this._flushPromise = this._flushInner().finally(()=>{\n this._flushPromise = null;\n });\n return this._flushPromise;\n }\n async _flushInner() {\n this._clearFlushTimer();\n let queue = this._instance.getPersistedProperty(PostHogPersistedProperty.LogsQueue) ?? [];\n if (0 === queue.length) return;\n const originalQueueLength = queue.length;\n let sentCount = 0;\n while(queue.length > 0 && sentCount < originalQueueLength){\n this._evictedSinceAdvance = 0;\n const batchSize = Math.min(queue.length, this._maxBatchRecordsPerPost);\n const batch = queue.slice(0, batchSize);\n const records = batch.map((e)=>e.record);\n const payload = buildOtlpLogsPayload(records, this._buildResourceAttributes(), this._scopeName ?? this._instance.getLibraryId(), this._instance.getLibraryVersion());\n const outcome = await this._instance._sendLogsBatch(payload);\n if ('too-large' === outcome.kind && batch.length > 1) {\n this._maxBatchRecordsPerPost = Math.max(1, Math.floor(batch.length / 2));\n this._logger.warn(`Received 413 when sending logs batch of size ${batch.length}, reducing batch size to ${this._maxBatchRecordsPerPost}`);\n continue;\n }\n if ('retry-later' === outcome.kind) throw outcome.error;\n if ('too-large' === outcome.kind) this._logger.warn(\"Dropping a single log record after 413 with batch size 1 \\u2014 the record is larger than the server cap and cannot be split further.\");\n else if ('ok' === outcome.kind && this._maxBatchRecordsPerPost < this._config.maxBatchRecordsPerPost) this._maxBatchRecordsPerPost = Math.min(this._config.maxBatchRecordsPerPost, this._maxBatchRecordsPerPost + 1);\n await this._persistQueueAdvance(batch.length);\n queue = this._instance.getPersistedProperty(PostHogPersistedProperty.LogsQueue) ?? [];\n sentCount += batch.length;\n if ('fatal' === outcome.kind) throw outcome.error;\n }\n }\n async _persistQueueAdvance(consumed) {\n const evicted = this._evictedSinceAdvance;\n const drop = Math.max(0, consumed - evicted);\n const refreshed = this._instance.getPersistedProperty(PostHogPersistedProperty.LogsQueue) ?? [];\n this._instance.setPersistedProperty(PostHogPersistedProperty.LogsQueue, refreshed.slice(drop));\n await this._waitForStoragePersist();\n }\n _buildResourceAttributes() {\n return buildResourceAttributes(this._config, this._instance.getLibraryId(), this._instance.getLibraryVersion());\n }\n _enqueue(entry) {\n if (this._instance.optedOut) return;\n const queue = this._instance.getPersistedProperty(PostHogPersistedProperty.LogsQueue) ?? [];\n if (queue.length >= this._maxQueueSize) {\n queue.shift();\n this._evictedSinceAdvance++;\n this._logger.info('Logs queue is full, dropping oldest record.');\n }\n queue.push(entry);\n this._instance.setPersistedProperty(PostHogPersistedProperty.LogsQueue, queue);\n if (queue.length >= this._maxBufferSize) return void this._flushInBackground();\n this._armFlushTimer();\n }\n _armFlushTimer(delayMs = this._flushIntervalMs) {\n if (this._flushTimer) return;\n this._flushTimer = safeSetTimeout(()=>{\n this._flushTimer = void 0;\n this._flushInBackground();\n }, delayMs);\n }\n _nextFlushDelay() {\n const exponent = Math.min(Math.max(0, this._consecutiveFlushFailures - 1), MAX_FLUSH_BACKOFF_EXPONENT);\n return this._flushIntervalMs * 2 ** exponent;\n }\n _hasQueuedRecords() {\n const queue = this._instance.getPersistedProperty(PostHogPersistedProperty.LogsQueue);\n return !!queue && queue.length > 0;\n }\n async shutdown(timeoutMs) {\n this._clearFlushTimer();\n const flushPromise = this.flush().catch(()=>{});\n if (void 0 === timeoutMs) return void await flushPromise;\n await Promise.race([\n flushPromise,\n new Promise((resolve)=>safeSetTimeout(resolve, timeoutMs))\n ]);\n }\n async flushWithTimeout(timeoutMs) {\n let timedOut = false;\n const flushPromise = this.flush();\n const timerPromise = new Promise((resolve)=>safeSetTimeout(()=>{\n timedOut = true;\n resolve();\n }, timeoutMs));\n try {\n await Promise.race([\n flushPromise,\n timerPromise\n ]);\n } finally{\n if (timedOut) flushPromise.catch(()=>{});\n }\n }\n _flushInBackground() {\n this.flush().then(()=>{\n this._consecutiveFlushFailures = 0;\n }, (err)=>{\n this._consecutiveFlushFailures++;\n this._logger.error('PostHog logs flush failed:', err);\n }).finally(()=>{\n if (!this._instance.isDisabled && this._hasQueuedRecords()) this._armFlushTimer(this._nextFlushDelay());\n });\n }\n _clearFlushTimer() {\n if (this._flushTimer) {\n clearTimeout(this._flushTimer);\n this._flushTimer = void 0;\n }\n }\n}\nexport { PostHogLogs };\n","import { toOtlpKeyValueList } from \"../logs/logs-utils.mjs\";\nconst DEFAULT_HISTOGRAM_BOUNDS = [\n 0,\n 5,\n 10,\n 25,\n 50,\n 75,\n 100,\n 250,\n 500,\n 750,\n 1000,\n 2500,\n 5000,\n 7500,\n 10000\n];\nfunction msToUnixNano(ms) {\n return String(ms) + '000000';\n}\nfunction seriesKey(type, name, unit, attributes) {\n let attrsKey = '';\n if (attributes) {\n const keys = Object.keys(attributes).sort();\n attrsKey = keys.map((k)=>`${JSON.stringify(k)}:${JSON.stringify(attributes[k])}`).join(',');\n }\n return `${type}\\u0000${name}\\u0000${unit ?? ''}\\u0000${attrsKey}`;\n}\nfunction bucketIndexFor(value, bounds) {\n for(let i = 0; i < bounds.length; i++)if (value <= bounds[i]) return i;\n return bounds.length;\n}\nfunction buildMetricsResourceAttributes(config, scopeName, scopeVersion) {\n return {\n ...config.resourceAttributes,\n 'service.name': config.serviceName || 'unknown_service',\n ...config.environment && {\n 'deployment.environment': config.environment\n },\n ...config.serviceVersion && {\n 'service.version': config.serviceVersion\n },\n 'telemetry.sdk.name': scopeName,\n 'telemetry.sdk.version': scopeVersion\n };\n}\nfunction buildOtlpMetricsPayload(metrics, resourceAttributes, scopeName, scopeVersion) {\n return {\n resourceMetrics: [\n {\n resource: {\n attributes: toOtlpKeyValueList(resourceAttributes)\n },\n scopeMetrics: [\n {\n scope: {\n name: scopeName,\n version: scopeVersion\n },\n metrics\n }\n ]\n }\n ]\n };\n}\nexport { DEFAULT_HISTOGRAM_BOUNDS, bucketIndexFor, buildMetricsResourceAttributes, buildOtlpMetricsPayload, msToUnixNano, seriesKey };\n","const DEFAULT_FLUSH_INTERVAL_MS = 10000;\nconst DEFAULT_MAX_SERIES_PER_FLUSH = 1000;\nfunction resolveMetricsConfig(config) {\n const resourceAttributes = config?.resourceAttributes;\n return {\n serviceName: resourceAttributes?.['service.name'] ?? config?.serviceName,\n serviceVersion: resourceAttributes?.['service.version'] ?? config?.serviceVersion,\n environment: resourceAttributes?.['deployment.environment'] ?? config?.environment,\n resourceAttributes,\n beforeSend: config?.beforeSend,\n flushIntervalMs: config?.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,\n maxSeriesPerFlush: config?.maxSeriesPerFlush ?? DEFAULT_MAX_SERIES_PER_FLUSH\n };\n}\nexport { resolveMetricsConfig };\n","import { isArray, safeSetTimeout } from \"../utils/index.mjs\";\nimport { toOtlpKeyValueList } from \"../logs/logs-utils.mjs\";\nimport { DEFAULT_HISTOGRAM_BOUNDS, bucketIndexFor, buildMetricsResourceAttributes, buildOtlpMetricsPayload, msToUnixNano, seriesKey } from \"./metrics-utils.mjs\";\nimport { resolveMetricsConfig } from \"./config.mjs\";\nconst OTLP_TEMPORALITY_DELTA = 1;\nclass PostHogMetrics {\n constructor(_instance, _config, _logger){\n this._instance = _instance;\n this._config = _config;\n this._logger = _logger;\n this._series = new Map();\n this._flushPromise = null;\n this._seriesCapWarned = false;\n this._typeByName = new Map();\n this._typeCollisionWarned = new Set();\n this._generation = 0;\n }\n count(name, value = 1, options) {\n this._capture({\n name,\n type: 'count',\n value,\n unit: options?.unit,\n attributes: options?.attributes\n });\n }\n gauge(name, value, options) {\n this._capture({\n name,\n type: 'gauge',\n value,\n unit: options?.unit,\n attributes: options?.attributes\n });\n }\n histogram(name, value, options) {\n this._capture({\n name,\n type: 'histogram',\n value,\n unit: options?.unit,\n attributes: options?.attributes\n });\n }\n flush() {\n const prev = this._flushPromise;\n const run = async ()=>{\n if (prev) await prev.catch(()=>{});\n await this._doFlush();\n };\n const p = run().finally(()=>{\n if (this._flushPromise === p) this._flushPromise = null;\n });\n this._flushPromise = p;\n return p;\n }\n drainWindow() {\n if (0 === this._series.size) return null;\n const window = this._series;\n this._series = new Map();\n this._seriesCapWarned = false;\n this._typeByName = new Map();\n this._typeCollisionWarned = new Set();\n return this._buildPayload(window);\n }\n reset() {\n this._generation++;\n this._clearFlushTimer();\n this._series = new Map();\n this._flushPromise = null;\n this._seriesCapWarned = false;\n this._typeByName = new Map();\n this._typeCollisionWarned = new Set();\n }\n _capture(sample) {\n if (this._instance.isDisabled || this._instance.optedOut) return;\n const filtered = this._runBeforeSend(sample);\n if (null === filtered) return;\n if (!filtered.name || 'string' != typeof filtered.name) return void this._logger.warn('Dropping metric with empty name');\n if ('number' != typeof filtered.value || !Number.isFinite(filtered.value)) return void this._logger.warn(`Dropping metric '${filtered.name}': value must be a finite number`);\n if ('count' === filtered.type && filtered.value < 0) return void this._logger.warn(`Dropping count '${filtered.name}': counters are monotonic, value must be >= 0`);\n let attributes;\n let key;\n try {\n attributes = filtered.attributes ? {\n ...filtered.attributes\n } : void 0;\n key = seriesKey(filtered.type, filtered.name, filtered.unit, attributes);\n } catch (e) {\n this._logger.warn(`Dropping metric '${filtered.name}': attributes could not be serialized`, e);\n return;\n }\n let state = this._series.get(key);\n if (!state) {\n if (!this._admitNewSeries()) return;\n state = {\n name: filtered.name,\n type: filtered.type,\n unit: filtered.unit,\n attributes,\n windowStartMs: Date.now()\n };\n this._series.set(key, state);\n }\n const seenType = this._typeByName.get(filtered.name);\n if (void 0 === seenType) this._typeByName.set(filtered.name, filtered.type);\n else if (seenType !== filtered.type && !this._typeCollisionWarned.has(filtered.name)) {\n this._typeCollisionWarned.add(filtered.name);\n this._logger.warn(`Metric name '${filtered.name}' is already used as a ${seenType}; recording it as a ${filtered.type} too will blend both series in charts. Use a distinct name.`);\n }\n this._fold(state, filtered.value);\n this._armFlushTimer();\n }\n _admitNewSeries() {\n if (this._series.size < this._config.maxSeriesPerFlush) return true;\n if (!this._seriesCapWarned) {\n this._seriesCapWarned = true;\n this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`);\n }\n return false;\n }\n _fold(state, value) {\n switch(state.type){\n case 'count':\n state.total = (state.total ?? 0) + value;\n break;\n case 'gauge':\n state.last = value;\n break;\n case 'histogram':\n {\n if (!state.hist) state.hist = {\n count: 0,\n sum: 0,\n min: value,\n max: value,\n bucketCounts: new Array(DEFAULT_HISTOGRAM_BOUNDS.length + 1).fill(0)\n };\n const hist = state.hist;\n hist.count += 1;\n hist.sum += value;\n hist.min = Math.min(hist.min, value);\n hist.max = Math.max(hist.max, value);\n hist.bucketCounts[bucketIndexFor(value, DEFAULT_HISTOGRAM_BOUNDS)] += 1;\n break;\n }\n }\n }\n _runBeforeSend(sample) {\n const beforeSend = this._config.beforeSend;\n if (!beforeSend) return sample;\n const fns = isArray(beforeSend) ? beforeSend : [\n beforeSend\n ];\n let result = sample;\n for (const fn of fns)try {\n const next = fn(result);\n if (!next) {\n this._logger.info(\"Metric was rejected in beforeSend function\");\n return null;\n }\n result = next;\n } catch (e) {\n this._logger.error(\"Error in beforeSend function for metric:\", e);\n return null;\n }\n return result;\n }\n _armFlushTimer() {\n if (this._flushTimer) return;\n this._flushTimer = safeSetTimeout(()=>{\n this._flushTimer = void 0;\n this.flush().catch((e)=>{\n this._logger.error('Metrics flush failed:', e);\n });\n }, this._config.flushIntervalMs);\n }\n _clearFlushTimer() {\n if (this._flushTimer) {\n clearTimeout(this._flushTimer);\n this._flushTimer = void 0;\n }\n }\n async _doFlush() {\n if (0 === this._series.size) return;\n const window = this._series;\n this._series = new Map();\n this._seriesCapWarned = false;\n this._typeByName = new Map();\n this._typeCollisionWarned = new Set();\n const generation = this._generation;\n const outcome = await this._instance._sendMetricsBatch(this._buildPayload(window));\n if (generation !== this._generation) return;\n switch(outcome.kind){\n case 'ok':\n return;\n case 'retry-later':\n this._mergeWindowBack(window);\n this._armFlushTimer();\n return;\n case 'too-large':\n this._logger.warn('Metrics batch exceeded the server size limit and was dropped');\n return;\n case 'fatal':\n this._logger.error('Failed to send metrics batch:', outcome.error);\n return;\n }\n }\n _buildPayload(window) {\n return buildOtlpMetricsPayload(this._buildMetrics(window), buildMetricsResourceAttributes(this._config, this._instance.getLibraryId(), this._instance.getLibraryVersion()), this._instance.getLibraryId(), this._instance.getLibraryVersion());\n }\n _buildMetrics(window) {\n const nowNano = msToUnixNano(Date.now());\n const byMetric = new Map();\n for (const state of window.values()){\n const metricKey = seriesKey(state.type, state.name, state.unit, void 0);\n let metric = byMetric.get(metricKey);\n if (!metric) {\n metric = {\n name: state.name,\n ...state.unit && {\n unit: state.unit\n }\n };\n if ('count' === state.type) metric.sum = {\n aggregationTemporality: OTLP_TEMPORALITY_DELTA,\n isMonotonic: true,\n dataPoints: []\n };\n else if ('gauge' === state.type) metric.gauge = {\n dataPoints: []\n };\n else metric.histogram = {\n aggregationTemporality: OTLP_TEMPORALITY_DELTA,\n dataPoints: []\n };\n byMetric.set(metricKey, metric);\n }\n const attributes = toOtlpKeyValueList(state.attributes ?? {});\n const startNano = msToUnixNano(state.windowStartMs);\n if ('count' === state.type) {\n const dp = {\n attributes,\n startTimeUnixNano: startNano,\n timeUnixNano: nowNano,\n asDouble: state.total ?? 0\n };\n metric.sum.dataPoints.push(dp);\n } else if ('gauge' === state.type) {\n const dp = {\n attributes,\n timeUnixNano: nowNano,\n asDouble: state.last ?? 0\n };\n metric.gauge.dataPoints.push(dp);\n } else if (state.hist) {\n const dp = {\n attributes,\n startTimeUnixNano: startNano,\n timeUnixNano: nowNano,\n count: state.hist.count,\n sum: state.hist.sum,\n min: state.hist.min,\n max: state.hist.max,\n bucketCounts: state.hist.bucketCounts,\n explicitBounds: DEFAULT_HISTOGRAM_BOUNDS\n };\n metric.histogram.dataPoints.push(dp);\n }\n }\n return Array.from(byMetric.values());\n }\n _mergeWindowBack(window) {\n for (const [key, old] of window){\n const current = this._series.get(key);\n if (!current) {\n if (this._admitNewSeries()) this._series.set(key, old);\n continue;\n }\n current.windowStartMs = Math.min(current.windowStartMs, old.windowStartMs);\n switch(current.type){\n case 'count':\n current.total = (current.total ?? 0) + (old.total ?? 0);\n break;\n case 'gauge':\n break;\n case 'histogram':\n if (old.hist) if (current.hist) {\n current.hist.count += old.hist.count;\n current.hist.sum += old.hist.sum;\n current.hist.min = Math.min(current.hist.min, old.hist.min);\n current.hist.max = Math.max(current.hist.max, old.hist.max);\n for(let i = 0; i < current.hist.bucketCounts.length; i++)current.hist.bucketCounts[i] += old.hist.bucketCounts[i];\n } else current.hist = old.hist;\n break;\n }\n }\n }\n}\nexport { DEFAULT_HISTOGRAM_BOUNDS, PostHogMetrics, buildMetricsResourceAttributes, buildOtlpMetricsPayload, resolveMetricsConfig };\n","import { isArray, isNoLike } from \"./utils/index.mjs\";\nimport { uuidv7 } from \"./vendor/uuidv7.mjs\";\nconst COOKIE_PREFIX = 'ph_';\nconst COOKIE_SUFFIX = '_posthog';\nfunction cookieStoreFromHeader(cookieHeader) {\n const cookies = {};\n if (cookieHeader) for (const pair of cookieHeader.split(';')){\n const [key, ...valueParts] = pair.trim().split('=');\n if (key) {\n const raw = valueParts.join('=').trim();\n try {\n cookies[key.trim()] = decodeURIComponent(raw);\n } catch {\n cookies[key.trim()] = raw;\n }\n }\n }\n return {\n get: (name)=>name in cookies ? {\n value: cookies[name]\n } : void 0\n };\n}\nfunction getPostHogCookieName(apiKey) {\n const sanitized = apiKey.replace(/\\+/g, 'PL').replace(/\\//g, 'SL').replace(/=/g, 'EQ');\n return `${COOKIE_PREFIX}${sanitized}${COOKIE_SUFFIX}`;\n}\nfunction serializePostHogCookie(anonymousId) {\n const now = Date.now();\n const sessionId = uuidv7();\n return JSON.stringify({\n distinct_id: anonymousId,\n $device_id: anonymousId,\n $user_state: 'anonymous',\n $sesid: [\n now,\n sessionId,\n now\n ]\n });\n}\nfunction readPostHogCookie(cookies, apiKey) {\n const cookieName = getPostHogCookieName(apiKey);\n const cookie = cookies.get(cookieName);\n return cookie ? parsePostHogCookie(cookie.value) : null;\n}\nfunction cookieStateToProperties(state) {\n if (!state) return;\n const props = {};\n if (state.sessionId) props.$session_id = state.sessionId;\n if (state.deviceId) props.$device_id = state.deviceId;\n return Object.keys(props).length > 0 ? props : void 0;\n}\nfunction parsePostHogCookie(cookieValue) {\n if (!cookieValue) return null;\n try {\n const parsed = JSON.parse(cookieValue);\n if (!parsed || 'object' != typeof parsed || !parsed.distinct_id) return null;\n const sesid = isArray(parsed.$sesid) ? parsed.$sesid[1] : void 0;\n return {\n distinctId: String(parsed.distinct_id),\n isIdentified: 'identified' === parsed.$user_state,\n sessionId: 'string' == typeof sesid ? sesid : void 0,\n deviceId: 'string' == typeof parsed.$device_id ? parsed.$device_id : void 0\n };\n } catch {\n return null;\n }\n}\nconst CONSENT_PREFIX = '__ph_opt_in_out_';\nfunction getConsentCookieName(apiKey, config) {\n if (config?.consent_persistence_name) return config.consent_persistence_name;\n if (config?.opt_out_capturing_cookie_prefix) return config.opt_out_capturing_cookie_prefix + apiKey;\n return CONSENT_PREFIX + apiKey;\n}\nfunction isOptedOut(cookies, apiKey, config) {\n const cookieName = getConsentCookieName(apiKey, config);\n const cookie = cookies.get(cookieName);\n if (cookie) return isNoLike(cookie.value);\n return config?.opt_out_capturing_by_default ?? false;\n}\nexport { cookieStateToProperties, cookieStoreFromHeader, getConsentCookieName, getPostHogCookieName, isOptedOut, parsePostHogCookie, readPostHogCookie, serializePostHogCookie };\n","class SimpleEventEmitter {\n constructor(){\n this.events = {};\n this.events = {};\n }\n on(event, listener) {\n if (!this.events[event]) this.events[event] = [];\n this.events[event].push(listener);\n return ()=>{\n this.events[event] = this.events[event].filter((x)=>x !== listener);\n };\n }\n emit(event, payload) {\n for (const listener of this.events[event] || [])listener(payload);\n for (const listener of this.events['*'] || [])listener(event, payload);\n }\n}\nexport { SimpleEventEmitter };\n","let parsedStackResults;\nlet lastKeysCount;\nlet cachedFilenameChunkIds;\nfunction getFilenameToChunkIdMap(stackParser) {\n const chunkIdMap = globalThis._posthogChunkIds;\n if (!chunkIdMap) return;\n const chunkIdKeys = Object.keys(chunkIdMap);\n if (cachedFilenameChunkIds && chunkIdKeys.length === lastKeysCount) return cachedFilenameChunkIds;\n lastKeysCount = chunkIdKeys.length;\n cachedFilenameChunkIds = chunkIdKeys.reduce((acc, stackKey)=>{\n if (!parsedStackResults) parsedStackResults = {};\n const result = parsedStackResults[stackKey];\n if (result) acc[result[0]] = result[1];\n else {\n const parsedStack = stackParser(stackKey);\n for(let i = parsedStack.length - 1; i >= 0; i--){\n const stackFrame = parsedStack[i];\n const filename = stackFrame?.filename;\n const chunkId = chunkIdMap[stackKey];\n if (filename && chunkId) {\n acc[filename] = chunkId;\n parsedStackResults[stackKey] = [\n filename,\n chunkId\n ];\n break;\n }\n }\n }\n return acc;\n }, {});\n return cachedFilenameChunkIds;\n}\nexport { getFilenameToChunkIdMap };\n","import { isArray } from \"../utils/index.mjs\";\nimport { getFilenameToChunkIdMap } from \"./chunk-ids.mjs\";\nconst MAX_CAUSE_RECURSION = 4;\nclass ErrorPropertiesBuilder {\n constructor(coercers, stackParser, modifiers = []){\n this.coercers = coercers;\n this.stackParser = stackParser;\n this.modifiers = modifiers;\n }\n buildFromUnknown(input, hint = {}) {\n const providedMechanism = hint && hint.mechanism;\n const mechanism = providedMechanism || {\n handled: true,\n type: 'generic'\n };\n const coercingContext = this.buildCoercingContext(mechanism, hint, 0);\n const exceptionWithCause = coercingContext.apply(input);\n const parsingContext = this.buildParsingContext(hint);\n const exceptionWithStack = this.parseStacktrace(exceptionWithCause, parsingContext);\n const exceptionList = this.convertToExceptionList(exceptionWithStack, mechanism);\n return {\n $exception_list: exceptionList,\n $exception_level: 'error'\n };\n }\n async modifyFrames(exceptionList) {\n for (const exc of exceptionList)if (exc.stacktrace && exc.stacktrace.frames && isArray(exc.stacktrace.frames)) exc.stacktrace.frames = await this.applyModifiers(exc.stacktrace.frames);\n return exceptionList;\n }\n coerceFallback(ctx) {\n return {\n type: 'Error',\n value: 'Unknown error',\n stack: ctx.syntheticException?.stack,\n synthetic: true\n };\n }\n parseStacktrace(err, ctx) {\n let cause;\n if (null != err.cause) cause = this.parseStacktrace(err.cause, ctx);\n let stack;\n if ('' != err.stack && null != err.stack) stack = this.applyChunkIds(this.stackParser(err.stack, err.synthetic ? ctx.skipFirstLines : 0), ctx.chunkIdMap);\n return {\n ...err,\n cause,\n stack\n };\n }\n applyChunkIds(frames, chunkIdMap) {\n return frames.map((frame)=>{\n if (frame.filename && chunkIdMap) frame.chunk_id = chunkIdMap[frame.filename];\n return frame;\n });\n }\n applyCoercers(input, ctx) {\n for (const adapter of this.coercers)if (adapter.match(input)) return adapter.coerce(input, ctx);\n return this.coerceFallback(ctx);\n }\n async applyModifiers(frames) {\n let newFrames = frames;\n for (const modifier of this.modifiers)newFrames = await modifier(newFrames);\n return newFrames;\n }\n convertToExceptionList(exceptionWithStack, mechanism) {\n const currentException = {\n type: exceptionWithStack.type,\n value: exceptionWithStack.value,\n mechanism: {\n type: mechanism.type ?? 'generic',\n handled: mechanism.handled ?? true,\n synthetic: exceptionWithStack.synthetic ?? false\n }\n };\n if (exceptionWithStack.stack) currentException.stacktrace = {\n type: 'raw',\n frames: exceptionWithStack.stack\n };\n const exceptionList = [\n currentException\n ];\n if (null != exceptionWithStack.cause) exceptionList.push(...this.convertToExceptionList(exceptionWithStack.cause, {\n ...mechanism,\n handled: true\n }));\n return exceptionList;\n }\n buildParsingContext(hint) {\n const context = {\n chunkIdMap: getFilenameToChunkIdMap(this.stackParser),\n skipFirstLines: hint.skipFirstLines ?? 1\n };\n return context;\n }\n buildCoercingContext(mechanism, hint, depth = 0) {\n const coerce = (input, depth)=>{\n if (!(depth <= MAX_CAUSE_RECURSION)) return;\n {\n const ctx = this.buildCoercingContext(mechanism, hint, depth);\n return this.applyCoercers(input, ctx);\n }\n };\n const context = {\n ...hint,\n syntheticException: 0 == depth ? hint.syntheticException : void 0,\n mechanism,\n apply: (input)=>coerce(input, depth),\n next: (input)=>coerce(input, depth + 1)\n };\n return context;\n }\n}\nexport { ErrorPropertiesBuilder };\n","import { isUndefined } from \"../../utils/index.mjs\";\nconst UNKNOWN_FUNCTION = '?';\nfunction createFrame(platform, filename, func, lineno, colno) {\n const frame = {\n platform,\n filename,\n function: '<anonymous>' === func ? UNKNOWN_FUNCTION : func,\n in_app: true\n };\n if (!isUndefined(lineno)) frame.lineno = lineno;\n if (!isUndefined(colno)) frame.colno = colno;\n return frame;\n}\nexport { UNKNOWN_FUNCTION, createFrame };\n","import { UNKNOWN_FUNCTION } from \"./base.mjs\";\nconst extractSafariExtensionDetails = (func, filename)=>{\n const isSafariExtension = -1 !== func.indexOf('safari-extension');\n const isSafariWebExtension = -1 !== func.indexOf('safari-web-extension');\n return isSafariExtension || isSafariWebExtension ? [\n -1 !== func.indexOf('@') ? func.split('@')[0] : UNKNOWN_FUNCTION,\n isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`\n ] : [\n func,\n filename\n ];\n};\nexport { extractSafariExtensionDetails };\n","import { UNKNOWN_FUNCTION, createFrame } from \"./base.mjs\";\nimport { extractSafariExtensionDetails } from \"./safari.mjs\";\nconst chromeRegexNoFnName = /^\\s*at (\\S+?)(?::(\\d+))(?::(\\d+))\\s*$/i;\nconst chromeRegex = /^\\s*at (?:(.+?\\)(?: \\[.+\\])?|.*?) ?\\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\\/)?.*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\nconst chromeEvalRegex = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\nconst chromeStackLineParser = (line, platform)=>{\n const noFnParts = chromeRegexNoFnName.exec(line);\n if (noFnParts) {\n const [, filename, line, col] = noFnParts;\n return createFrame(platform, filename, UNKNOWN_FUNCTION, +line, +col);\n }\n const parts = chromeRegex.exec(line);\n if (parts) {\n const isEval = parts[2] && 0 === parts[2].indexOf('eval');\n if (isEval) {\n const subMatch = chromeEvalRegex.exec(parts[2]);\n if (subMatch) {\n parts[2] = subMatch[1];\n parts[3] = subMatch[2];\n parts[4] = subMatch[3];\n }\n }\n const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);\n return createFrame(platform, filename, func, parts[3] ? +parts[3] : void 0, parts[4] ? +parts[4] : void 0);\n }\n};\nexport { chromeStackLineParser };\n","import { UNKNOWN_FUNCTION, createFrame } from \"./base.mjs\";\nimport { extractSafariExtensionDetails } from \"./safari.mjs\";\nconst geckoREgex = /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)?((?:[-a-z]+)?:\\/.*?|\\[native code\\]|[^@]*(?:bundle|\\d+\\.js)|\\/[\\w\\-. /=]+)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nconst geckoEvalRegex = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\nconst geckoStackLineParser = (line, platform)=>{\n const parts = geckoREgex.exec(line);\n if (parts) {\n const isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n if (isEval) {\n const subMatch = geckoEvalRegex.exec(parts[3]);\n if (subMatch) {\n parts[1] = parts[1] || 'eval';\n parts[3] = subMatch[1];\n parts[4] = subMatch[2];\n parts[5] = '';\n }\n }\n let filename = parts[3];\n let func = parts[1] || UNKNOWN_FUNCTION;\n [func, filename] = extractSafariExtensionDetails(func, filename);\n return createFrame(platform, filename, func, parts[4] ? +parts[4] : void 0, parts[5] ? +parts[5] : void 0);\n }\n};\nexport { geckoStackLineParser };\n","import { UNKNOWN_FUNCTION, createFrame } from \"./base.mjs\";\nconst winjsRegex = /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:[-a-z]+):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\nconst winjsStackLineParser = (line, platform)=>{\n const parts = winjsRegex.exec(line);\n return parts ? createFrame(platform, parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : void 0) : void 0;\n};\nexport { winjsStackLineParser };\n","import { UNKNOWN_FUNCTION, createFrame } from \"./base.mjs\";\nconst opera10Regex = / line (\\d+).*script (?:in )?(\\S+)(?:: in function (\\S+))?$/i;\nconst opera10StackLineParser = (line, platform)=>{\n const parts = opera10Regex.exec(line);\n return parts ? createFrame(platform, parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : void 0;\n};\nconst opera11Regex = / line (\\d+), column (\\d+)\\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\\(.*\\))? in (.*):\\s*$/i;\nconst opera11StackLineParser = (line, platform)=>{\n const parts = opera11Regex.exec(line);\n return parts ? createFrame(platform, parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : void 0;\n};\nexport { opera10StackLineParser, opera11StackLineParser };\n","import { UNKNOWN_FUNCTION } from \"./base.mjs\";\nconst FILENAME_MATCH = /^\\s*[-]{4,}$/;\nconst FULL_MATCH = /at (?:async )?(?:(.+?)\\s+\\()?(?:(.+):(\\d+):(\\d+)?|([^)]+))\\)?/;\nconst nodeStackLineParser = (line, platform)=>{\n const lineMatch = line.match(FULL_MATCH);\n if (lineMatch) {\n let object;\n let method;\n let functionName;\n let typeName;\n let methodName;\n if (lineMatch[1]) {\n functionName = lineMatch[1];\n let methodStart = functionName.lastIndexOf('.');\n if ('.' === functionName[methodStart - 1]) methodStart--;\n if (methodStart > 0) {\n object = functionName.slice(0, methodStart);\n method = functionName.slice(methodStart + 1);\n const objectEnd = object.indexOf('.Module');\n if (objectEnd > 0) {\n functionName = functionName.slice(objectEnd + 1);\n object = object.slice(0, objectEnd);\n }\n }\n typeName = void 0;\n }\n if (method) {\n typeName = object;\n methodName = method;\n }\n if ('<anonymous>' === method) {\n methodName = void 0;\n functionName = void 0;\n }\n if (void 0 === functionName) {\n methodName = methodName || UNKNOWN_FUNCTION;\n functionName = typeName ? `${typeName}.${methodName}` : methodName;\n }\n let filename = lineMatch[2]?.startsWith('file://') ? lineMatch[2].slice(7) : lineMatch[2];\n const isNative = 'native' === lineMatch[5];\n if (filename?.match(/\\/[A-Z]:/)) filename = filename.slice(1);\n if (!filename && lineMatch[5] && !isNative) filename = lineMatch[5];\n return {\n filename: filename ? decodeURI(filename) : void 0,\n module: void 0,\n function: functionName,\n lineno: _parseIntOrUndefined(lineMatch[3]),\n colno: _parseIntOrUndefined(lineMatch[4]),\n in_app: filenameIsInApp(filename || '', isNative),\n platform: platform\n };\n }\n if (line.match(FILENAME_MATCH)) return {\n filename: line,\n platform: platform\n };\n};\nfunction filenameIsInApp(filename, isNative = false) {\n const isInternal = isNative || filename && !filename.startsWith('/') && !filename.match(/^[A-Z]:/) && !filename.startsWith('.') && !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\\-+])*:\\/\\//);\n return !isInternal && void 0 !== filename && !filename.includes('node_modules/');\n}\nfunction _parseIntOrUndefined(input) {\n return parseInt(input || '', 10) || void 0;\n}\nexport { nodeStackLineParser };\n","import { UNKNOWN_FUNCTION } from \"./base.mjs\";\nimport { chromeStackLineParser } from \"./chrome.mjs\";\nimport { geckoStackLineParser } from \"./gecko.mjs\";\nimport { winjsStackLineParser } from \"./winjs.mjs\";\nimport { opera10StackLineParser, opera11StackLineParser } from \"./opera.mjs\";\nimport { nodeStackLineParser } from \"./node.mjs\";\nconst WEBPACK_ERROR_REGEXP = /\\(error: (.*)\\)/;\nconst STACKTRACE_FRAME_LIMIT = 50;\nfunction reverseAndStripFrames(stack) {\n if (!stack.length) return [];\n const localStack = Array.from(stack);\n localStack.reverse();\n return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame)=>({\n ...frame,\n filename: frame.filename || getLastStackFrame(localStack).filename,\n function: frame.function || UNKNOWN_FUNCTION\n }));\n}\nfunction getLastStackFrame(arr) {\n return arr[arr.length - 1] || {};\n}\nfunction createDefaultStackParser() {\n return createStackParser(\"web:javascript\", chromeStackLineParser, geckoStackLineParser);\n}\nfunction createStackParser(platform, ...parsers) {\n return (stack, skipFirstLines = 0)=>{\n const frames = [];\n const lines = stack.split('\\n');\n for(let i = skipFirstLines; i < lines.length; i++){\n const line = lines[i];\n if (line.length > 1024) continue;\n const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;\n if (!cleanedLine.match(/\\S*Error: /)) {\n for (const parser of parsers){\n const frame = parser(cleanedLine, platform);\n if (frame) {\n frames.push(frame);\n break;\n }\n }\n if (frames.length >= STACKTRACE_FRAME_LIMIT) break;\n }\n }\n return reverseAndStripFrames(frames);\n };\n}\nexport { chromeStackLineParser, createDefaultStackParser, createStackParser, geckoStackLineParser, nodeStackLineParser, opera10StackLineParser, opera11StackLineParser, reverseAndStripFrames, winjsStackLineParser };\n","import { isBuiltin, isString } from \"../../utils/index.mjs\";\nclass DOMExceptionCoercer {\n match(err) {\n return this.isDOMException(err) || this.isDOMError(err);\n }\n coerce(err, ctx) {\n const hasStack = isString(err.stack);\n return {\n type: this.getType(err),\n value: this.getValue(err),\n stack: hasStack ? err.stack : void 0,\n cause: err.cause ? ctx.next(err.cause) : void 0,\n synthetic: false\n };\n }\n getType(candidate) {\n return this.isDOMError(candidate) ? 'DOMError' : 'DOMException';\n }\n getValue(err) {\n const name = err.name || (this.isDOMError(err) ? 'DOMError' : 'DOMException');\n const message = err.message ? `${name}: ${err.message}` : name;\n return message;\n }\n isDOMException(err) {\n return isBuiltin(err, 'DOMException');\n }\n isDOMError(err) {\n return isBuiltin(err, 'DOMError');\n }\n}\nexport { DOMExceptionCoercer };\n","import { isPlainError } from \"../../utils/index.mjs\";\nclass ErrorCoercer {\n match(err) {\n return isPlainError(err);\n }\n coerce(err, ctx) {\n return {\n type: this.getType(err),\n value: this.getMessage(err, ctx),\n stack: this.getStack(err),\n cause: err.cause ? ctx.next(err.cause) : void 0,\n synthetic: false\n };\n }\n getType(err) {\n return err.name || err.constructor.name;\n }\n getMessage(err, _ctx) {\n const message = err.message;\n if (message.error && 'string' == typeof message.error.message) return String(message.error.message);\n return String(message);\n }\n getStack(err) {\n return err.stacktrace || err.stack || void 0;\n }\n}\nexport { ErrorCoercer };\n","import { isErrorEvent } from \"../../utils/index.mjs\";\nclass ErrorEventCoercer {\n constructor(){}\n match(err) {\n return isErrorEvent(err) && void 0 != err.error;\n }\n coerce(err, ctx) {\n const exceptionLike = ctx.apply(err.error);\n if (!exceptionLike) return {\n type: 'ErrorEvent',\n value: err.message,\n stack: ctx.syntheticException?.stack,\n synthetic: true\n };\n return exceptionLike;\n }\n}\nexport { ErrorEventCoercer };\n","const ERROR_TYPES_PATTERN = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;\nclass StringCoercer {\n match(input) {\n return 'string' == typeof input;\n }\n coerce(input, ctx) {\n const [type, value] = this.getInfos(input);\n return {\n type: type ?? 'Error',\n value: value ?? input,\n stack: ctx.syntheticException?.stack,\n synthetic: true\n };\n }\n getInfos(candidate) {\n let type = 'Error';\n let value = candidate;\n const groups = candidate.match(ERROR_TYPES_PATTERN);\n if (groups) {\n type = groups[1];\n value = groups[2];\n }\n return [\n type,\n value\n ];\n }\n}\nexport { StringCoercer };\n","const severityLevels = [\n 'fatal',\n 'error',\n 'warning',\n 'log',\n 'info',\n 'debug'\n];\nexport { severityLevels };\n","function truncate(str, max = 0) {\n if ('string' != typeof str || 0 === max) return str;\n return str.length <= max ? str : `${str.slice(0, max)}...`;\n}\nfunction extractExceptionKeysForMessage(err, maxLength = 40) {\n const keys = Object.keys(err);\n keys.sort();\n if (!keys.length) return '[object has no keys]';\n for(let i = keys.length; i > 0; i--){\n const serialized = keys.slice(0, i).join(', ');\n if (!(serialized.length > maxLength)) {\n if (i === keys.length) return serialized;\n return serialized.length <= maxLength ? serialized : `${serialized.slice(0, maxLength)}...`;\n }\n }\n return '';\n}\nexport { extractExceptionKeysForMessage, truncate };\n","import { isEmptyString, isError, isEvent, isString } from \"../../utils/index.mjs\";\nimport { severityLevels } from \"../types.mjs\";\nimport { extractExceptionKeysForMessage } from \"./utils.mjs\";\nclass ObjectCoercer {\n match(candidate) {\n return 'object' == typeof candidate && null !== candidate;\n }\n coerce(candidate, ctx) {\n const errorProperty = this.getErrorPropertyFromObject(candidate);\n if (errorProperty) return ctx.apply(errorProperty);\n return {\n type: this.getType(candidate),\n value: this.getValue(candidate),\n stack: ctx.syntheticException?.stack,\n level: this.isSeverityLevel(candidate.level) ? candidate.level : 'error',\n synthetic: true\n };\n }\n getType(err) {\n return isEvent(err) ? err.constructor.name : 'Error';\n }\n getValue(err) {\n if ('name' in err && 'string' == typeof err.name) {\n let message = `'${err.name}' captured as exception`;\n if ('message' in err && 'string' == typeof err.message) message += ` with message: '${err.message}'`;\n return message;\n }\n if ('message' in err && 'string' == typeof err.message) return err.message;\n const className = this.getObjectClassName(err);\n const keys = extractExceptionKeysForMessage(err);\n return `${className && 'Object' !== className ? `'${className}'` : 'Object'} captured as exception with keys: ${keys}`;\n }\n isSeverityLevel(x) {\n return isString(x) && !isEmptyString(x) && severityLevels.indexOf(x) >= 0;\n }\n getErrorPropertyFromObject(obj) {\n for(const prop in obj)if (Object.prototype.hasOwnProperty.call(obj, prop)) {\n const value = obj[prop];\n if (isError(value)) return value;\n }\n }\n getObjectClassName(obj) {\n try {\n const prototype = Object.getPrototypeOf(obj);\n return prototype ? prototype.constructor.name : void 0;\n } catch (e) {\n return;\n }\n }\n}\nexport { ObjectCoercer };\n","import { isEvent } from \"../../utils/index.mjs\";\nimport { extractExceptionKeysForMessage } from \"./utils.mjs\";\nclass EventCoercer {\n match(err) {\n return isEvent(err);\n }\n coerce(evt, ctx) {\n const constructorName = evt.constructor.name;\n return {\n type: constructorName,\n value: `${constructorName} captured as exception with keys: ${extractExceptionKeysForMessage(evt)}`,\n stack: ctx.syntheticException?.stack,\n synthetic: true\n };\n }\n}\nexport { EventCoercer };\n","import { isPrimitive } from \"../../utils/index.mjs\";\nclass PrimitiveCoercer {\n match(candidate) {\n return isPrimitive(candidate);\n }\n coerce(value, ctx) {\n return {\n type: 'Error',\n value: `Primitive value captured as exception: ${String(value)}`,\n stack: ctx.syntheticException?.stack,\n synthetic: true\n };\n }\n}\nexport { PrimitiveCoercer };\n","import { isBuiltin, isEvent, isPrimitive } from \"../../utils/index.mjs\";\nclass PromiseRejectionEventCoercer {\n match(err) {\n return isBuiltin(err, 'PromiseRejectionEvent') || this.isCustomEventWrappingRejection(err);\n }\n isCustomEventWrappingRejection(err) {\n if (!isEvent(err)) return false;\n try {\n const detail = err.detail;\n return null != detail && 'object' == typeof detail && 'reason' in detail;\n } catch {\n return false;\n }\n }\n coerce(err, ctx) {\n const reason = this.getUnhandledRejectionReason(err);\n if (isPrimitive(reason)) return {\n type: 'UnhandledRejection',\n value: `Non-Error promise rejection captured with value: ${String(reason)}`,\n stack: ctx.syntheticException?.stack,\n synthetic: true\n };\n return ctx.apply(reason);\n }\n getUnhandledRejectionReason(error) {\n try {\n if ('reason' in error) return error.reason;\n if ('detail' in error && null != error.detail && 'object' == typeof error.detail && 'reason' in error.detail) return error.detail.reason;\n } catch {}\n return error;\n }\n}\nexport { PromiseRejectionEventCoercer };\n","export * from \"./dom-exception-coercer.mjs\";\nexport * from \"./error-coercer.mjs\";\nexport * from \"./error-event-coercer.mjs\";\nexport * from \"./string-coercer.mjs\";\nexport * from \"./object-coercer.mjs\";\nexport * from \"./event-coercer.mjs\";\nexport * from \"./primitive-coercer.mjs\";\nexport * from \"./promise-rejection-event.mjs\";\n","class ReduceableCache {\n constructor(_maxSize){\n this._maxSize = _maxSize;\n this._cache = new Map();\n }\n get(key) {\n const value = this._cache.get(key);\n if (void 0 === value) return;\n this._cache.delete(key);\n this._cache.set(key, value);\n return value;\n }\n set(key, value) {\n this._cache.set(key, value);\n }\n reduce() {\n while(this._cache.size >= this._maxSize){\n const value = this._cache.keys().next().value;\n if (value) this._cache.delete(value);\n }\n }\n}\nexport { ReduceableCache };\n","import { isNumber, isObject, isString, safeJsonStringify } from \"../utils/index.mjs\";\nconst EXCEPTION_STEP_INTERNAL_FIELDS = {\n MESSAGE: '$message',\n TIMESTAMP: '$timestamp'\n};\nconst RESERVED_EXCEPTION_STEP_KEYS = new Set([\n EXCEPTION_STEP_INTERNAL_FIELDS.MESSAGE,\n EXCEPTION_STEP_INTERNAL_FIELDS.TIMESTAMP\n]);\nconst DEFAULT_EXCEPTION_STEPS_CONFIG = {\n enabled: true,\n max_bytes: 32768\n};\nfunction resolveExceptionStepsConfig(config) {\n if (!config) return {\n ...DEFAULT_EXCEPTION_STEPS_CONFIG\n };\n return {\n enabled: config.enabled ?? DEFAULT_EXCEPTION_STEPS_CONFIG.enabled,\n max_bytes: normalizePositiveInteger(config.max_bytes, DEFAULT_EXCEPTION_STEPS_CONFIG.max_bytes)\n };\n}\nfunction stripReservedExceptionStepFields(properties) {\n if (!properties) return {\n sanitizedProperties: {},\n droppedKeys: []\n };\n const droppedKeys = [];\n const sanitizedProperties = Object.keys(properties).reduce((acc, key)=>{\n if (RESERVED_EXCEPTION_STEP_KEYS.has(key)) {\n droppedKeys.push(key);\n return acc;\n }\n acc[key] = properties[key];\n return acc;\n }, {});\n return {\n sanitizedProperties,\n droppedKeys\n };\n}\nclass ExceptionStepsBuffer {\n constructor(config){\n this._entries = [];\n this._totalBytes = 0;\n this._config = resolveExceptionStepsConfig(config);\n }\n setConfig(config) {\n this._config = resolveExceptionStepsConfig(config);\n this._trimToMaxBytes();\n }\n add(step) {\n const serialized = normalizeAndSerializeStep(step);\n if (!serialized) return;\n const bytes = getUtf8ByteLength(serialized.json);\n if (bytes > this._config.max_bytes) return;\n this._entries.push({\n step: serialized.step,\n bytes\n });\n this._totalBytes += bytes;\n this._trimToMaxBytes();\n }\n getAttachable() {\n return this._entries.map((e)=>e.step);\n }\n clear() {\n this._entries = [];\n this._totalBytes = 0;\n }\n size() {\n return this._entries.length;\n }\n _trimToMaxBytes() {\n while(this._totalBytes > this._config.max_bytes && this._entries.length > 0){\n const evicted = this._entries.shift();\n if (evicted) this._totalBytes -= evicted.bytes;\n }\n }\n}\nfunction normalizePositiveInteger(input, fallback) {\n if (!isNumber(input) || input === 1 / 0 || input === -1 / 0) return fallback;\n const normalized = Math.floor(input);\n if (normalized < 0) return fallback;\n return normalized;\n}\nfunction normalizeAndSerializeStep(step) {\n let json;\n try {\n json = safeJsonStringify(step);\n } catch {\n return;\n }\n try {\n const parsed = JSON.parse(json);\n if (!isObject(parsed)) return;\n const parsedStep = parsed;\n const message = parsedStep[EXCEPTION_STEP_INTERNAL_FIELDS.MESSAGE];\n const timestamp = parsedStep[EXCEPTION_STEP_INTERNAL_FIELDS.TIMESTAMP];\n if (!isString(message) || 0 === message.trim().length) return;\n if (!isString(timestamp) && !isNumber(timestamp)) return;\n return {\n step: parsedStep,\n json\n };\n } catch {\n return;\n }\n}\nfunction getUtf8ByteLength(value) {\n if ('undefined' != typeof TextEncoder) return new TextEncoder().encode(value).length;\n const encoded = encodeURIComponent(value);\n let byteLength = 0;\n for(let i = 0; i < encoded.length; i++)if ('%' === encoded[i]) {\n byteLength += 1;\n i += 2;\n } else byteLength += 1;\n return byteLength;\n}\nexport { DEFAULT_EXCEPTION_STEPS_CONFIG, EXCEPTION_STEP_INTERNAL_FIELDS, ExceptionStepsBuffer, getUtf8ByteLength, resolveExceptionStepsConfig, stripReservedExceptionStepFields };\n","export * from \"./error-properties-builder.mjs\";\nexport * from \"./parsers/index.mjs\";\nexport * from \"./coercers/index.mjs\";\nexport * from \"./utils.mjs\";\nexport * from \"./exception-steps.mjs\";\n","import { SimpleEventEmitter } from \"./eventemitter.mjs\";\nimport { getFeatureFlagValue, minimizeFlagCalledEventProperties, normalizeFlagsResponse } from \"./featureFlagUtils.mjs\";\nimport { gzipCompress, isGzipSupported } from \"./gzip.mjs\";\nimport { PostHogPersistedProperty } from \"./types.mjs\";\nimport { PromiseQueue, STRING_FORMAT, allSettled, createLogger, currentISOTime, getEventUuid, removeTrailingSlash, retriable, safeJsonStringify, safeSetTimeout } from \"./utils/index.mjs\";\nimport { uuidv7 } from \"./vendor/uuidv7.mjs\";\nimport { ErrorCoercer, ErrorPropertiesBuilder, ObjectCoercer, PrimitiveCoercer, StringCoercer, createDefaultStackParser } from \"./error-tracking/index.mjs\";\nclass PostHogFetchHttpError extends Error {\n constructor(response, reqByteLength){\n super('HTTP error while fetching PostHog: status=' + response.status + ', reqByteLength=' + reqByteLength), this.response = response, this.reqByteLength = reqByteLength, this.name = 'PostHogFetchHttpError';\n }\n get status() {\n return this.response.status;\n }\n get text() {\n return this.response.text();\n }\n get json() {\n return this.response.json();\n }\n}\nclass PostHogFetchNetworkError extends Error {\n constructor(error){\n super('Network error while fetching PostHog', error instanceof Error ? {\n cause: error\n } : {}), this.error = error, this.name = 'PostHogFetchNetworkError';\n }\n}\nconst maybeAdd = (key, value)=>void 0 !== value ? {\n [key]: value\n } : {};\nconst applyCallerFeatureFlagOverrides = (target, callerProperties)=>{\n for (const key of Object.keys(callerProperties))if (key.startsWith('$feature/') || '$active_feature_flags' === key) target[key] = callerProperties[key];\n};\nasync function logFlushError(err) {\n if (err instanceof PostHogFetchHttpError) {\n let text = '';\n try {\n text = await err.text;\n } catch {}\n console.error(`Error while flushing PostHog: message=${err.message}, response body=${text}`, err);\n } else console.error('Error while flushing PostHog', err);\n return Promise.resolve();\n}\nfunction isPostHogFetchError(err) {\n return 'object' == typeof err && (err instanceof PostHogFetchHttpError || isPostHogFetchNetworkError(err));\n}\nfunction isPostHogFetchNetworkError(err) {\n return err instanceof PostHogFetchNetworkError;\n}\nfunction isRetryableFlagsFetchError(err) {\n if (err instanceof PostHogFetchHttpError) return 502 === err.status || 504 === err.status;\n if (!(err instanceof PostHogFetchNetworkError)) return false;\n const cause = err.error;\n const code = cause?.code ?? cause?.cause?.code;\n return 'ECONNREFUSED' !== code;\n}\nfunction isPostHogFetchContentTooLargeError(err) {\n return 'object' == typeof err && err instanceof PostHogFetchHttpError && 413 === err.status;\n}\nfunction isPostHogFetchRetryableError(err) {\n if (err instanceof PostHogFetchHttpError) return 408 === err.status || 429 === err.status || err.status >= 500;\n return isPostHogFetchNetworkError(err);\n}\nfunction isPostHogEventProperties(value) {\n return null !== value && 'object' == typeof value && !Array.isArray(value);\n}\nvar posthog_core_stateless_QuotaLimitedFeature = /*#__PURE__*/ function(QuotaLimitedFeature) {\n QuotaLimitedFeature[\"FeatureFlags\"] = \"feature_flags\";\n QuotaLimitedFeature[\"Recordings\"] = \"recordings\";\n return QuotaLimitedFeature;\n}({});\nconst DEFAULT_QUEUE_ROUTE = 'default';\nclass PostHogCoreStateless {\n getErrorPropertiesBuilder() {\n if (!this._errorPropertiesBuilder) this._errorPropertiesBuilder = this.createErrorPropertiesBuilder();\n return this._errorPropertiesBuilder;\n }\n createErrorPropertiesBuilder() {\n return new ErrorPropertiesBuilder([\n new ErrorCoercer(),\n new ObjectCoercer(),\n new StringCoercer(),\n new PrimitiveCoercer()\n ], createDefaultStackParser());\n }\n constructor(apiKey, options = {}){\n this.flushPromise = null;\n this.pendingFlushPromise = null;\n this.flushPromises = new Set();\n this._dequeuedMessagesCount = 0;\n this.shutdownPromise = null;\n this.promiseQueue = new PromiseQueue();\n this._events = new SimpleEventEmitter();\n this._isInitialized = false;\n const normalizedApiKey = 'string' == typeof apiKey ? apiKey.trim() : '';\n const normalizedHost = 'string' == typeof options.host ? options.host.trim() : '';\n const missingApiKey = !normalizedApiKey;\n this._logger = createLogger('[PostHog]', this.logMsgIfDebug.bind(this));\n if (missingApiKey) this._logger.error(\"You must pass your PostHog project's api key. The client will be disabled.\");\n this.apiKey = normalizedApiKey;\n this.host = removeTrailingSlash(normalizedHost || 'https://us.i.posthog.com');\n this.flushAt = options.flushAt ? Math.max(options.flushAt, 1) : 20;\n this.maxBatchSize = Math.max(this.flushAt, options.maxBatchSize ?? 100);\n this.maxQueueSize = Math.max(this.flushAt, options.maxQueueSize ?? 1000);\n this.flushInterval = options.flushInterval ?? 10000;\n this.preloadFeatureFlags = options.preloadFeatureFlags ?? true;\n this.defaultOptIn = options.defaultOptIn ?? true;\n this.disableSurveys = options.disableSurveys ?? false;\n this._retryOptions = {\n retryCount: options.fetchRetryCount ?? 3,\n retryDelay: options.fetchRetryDelay ?? 3000,\n retryCheck: isPostHogFetchRetryableError\n };\n this.requestTimeout = options.requestTimeout ?? 10000;\n this.featureFlagsRequestTimeoutMs = options.featureFlagsRequestTimeoutMs ?? 3000;\n this.featureFlagsRequestMaxRetries = options.featureFlagsRequestMaxRetries ?? 1;\n this.remoteConfigRequestTimeoutMs = options.remoteConfigRequestTimeoutMs ?? 3000;\n this.disableGeoip = options.disableGeoip ?? true;\n this.disabled = (options.disabled ?? false) || missingApiKey;\n this.historicalMigration = options?.historicalMigration ?? false;\n this._initPromise = Promise.resolve();\n this._isInitialized = true;\n this.evaluationContexts = options?.evaluationContexts ?? options?.evaluationEnvironments;\n if (options?.evaluationEnvironments && !options?.evaluationContexts) this._logger.warn('evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.');\n this.disableCompression = !isGzipSupported() || (options?.disableCompression ?? false);\n }\n logMsgIfDebug(fn) {\n if (this.isDebug) fn();\n }\n wrap(fn) {\n if (this.disabled) return void this._logger.warn('The client is disabled');\n if (this._isInitialized) return fn();\n this._initPromise.then(()=>fn());\n }\n getCommonEventProperties() {\n return {\n $lib: this.getLibraryId(),\n $lib_version: this.getLibraryVersion()\n };\n }\n get optedOut() {\n return this.getPersistedProperty(PostHogPersistedProperty.OptedOut) ?? !this.defaultOptIn;\n }\n async optIn() {\n this.wrap(()=>{\n this.setPersistedProperty(PostHogPersistedProperty.OptedOut, false);\n });\n }\n async optOut() {\n this.wrap(()=>{\n this.setPersistedProperty(PostHogPersistedProperty.OptedOut, true);\n });\n }\n on(event, cb) {\n return this._events.on(event, cb);\n }\n debug(enabled = true) {\n this.removeDebugCallback?.();\n if (enabled) {\n const removeDebugCallback = this.on('*', (event, payload)=>this._logger.info(event, payload));\n this.removeDebugCallback = ()=>{\n removeDebugCallback();\n this.removeDebugCallback = void 0;\n };\n }\n }\n get isDebug() {\n return !!this.removeDebugCallback;\n }\n get isDisabled() {\n return this.disabled;\n }\n buildPayload(payload) {\n const userProperties = payload.properties || {};\n let properties = {\n ...userProperties,\n ...this.getCommonEventProperties()\n };\n applyCallerFeatureFlagOverrides(properties, userProperties);\n if ('$feature_flag_called' === payload.event && false === properties.$feature_flag_has_experiment && this.isMinimalFlagCalledEventsEnabled()) properties = minimizeFlagCalledEventProperties(properties);\n return {\n distinct_id: payload.distinct_id,\n event: payload.event,\n properties\n };\n }\n isMinimalFlagCalledEventsEnabled() {\n return false;\n }\n addPendingPromise(promise) {\n return this.promiseQueue.add(promise);\n }\n identifyStateless(distinctId, properties, options) {\n this.wrap(()=>{\n const payload = {\n ...this.buildPayload({\n distinct_id: distinctId,\n event: '$identify',\n properties\n })\n };\n this.enqueue('identify', payload, options);\n });\n }\n async identifyStatelessImmediate(distinctId, properties, options) {\n const payload = {\n ...this.buildPayload({\n distinct_id: distinctId,\n event: '$identify',\n properties\n })\n };\n await this.sendImmediate('identify', payload, options);\n }\n captureStateless(distinctId, event, properties, options) {\n this.wrap(()=>{\n const payload = this.buildPayload({\n distinct_id: distinctId,\n event,\n properties\n });\n this.enqueue('capture', payload, options);\n });\n }\n async captureStatelessImmediate(distinctId, event, properties, options) {\n const payload = this.buildPayload({\n distinct_id: distinctId,\n event,\n properties\n });\n await this.sendImmediate('capture', payload, options);\n }\n aliasStateless(alias, distinctId, properties, options) {\n this.wrap(()=>{\n const payload = this.buildPayload({\n event: '$create_alias',\n distinct_id: distinctId,\n properties: {\n ...properties || {},\n distinct_id: distinctId,\n alias\n }\n });\n this.enqueue('alias', payload, options);\n });\n }\n async aliasStatelessImmediate(alias, distinctId, properties, options) {\n const payload = this.buildPayload({\n event: '$create_alias',\n distinct_id: distinctId,\n properties: {\n ...properties || {},\n distinct_id: distinctId,\n alias\n }\n });\n await this.sendImmediate('alias', payload, options);\n }\n groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {\n this.wrap(()=>{\n const payload = this.buildPayload({\n distinct_id: distinctId || `$${groupType}_${groupKey}`,\n event: '$groupidentify',\n properties: {\n $group_type: groupType,\n $group_key: groupKey,\n $group_set: groupProperties || {},\n ...eventProperties || {}\n }\n });\n this.enqueue('capture', payload, options);\n });\n }\n async groupIdentifyStatelessImmediate(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {\n const payload = this.buildPayload({\n distinct_id: distinctId || `$${groupType}_${groupKey}`,\n event: '$groupidentify',\n properties: {\n $group_type: groupType,\n $group_key: groupKey,\n $group_set: groupProperties || {},\n ...eventProperties || {}\n }\n });\n await this.sendImmediate('capture', payload, options);\n }\n async getRemoteConfig() {\n await this._initPromise;\n let host = this.host;\n if ('https://us.i.posthog.com' === host) host = 'https://us-assets.i.posthog.com';\n else if ('https://eu.i.posthog.com' === host) host = 'https://eu-assets.i.posthog.com';\n const url = `${host}/array/${this.apiKey}/config`;\n const fetchOptions = {\n method: 'GET',\n headers: {\n ...this.getCustomHeaders(),\n 'Content-Type': 'application/json'\n }\n };\n return this.fetchWithRetry(url, fetchOptions, {\n retryCount: 0\n }, this.remoteConfigRequestTimeoutMs).then((response)=>response.json()).catch((error)=>{\n this._logger.error('Remote config could not be loaded', error);\n this._events.emit('error', error);\n });\n }\n async getFlags(distinctId, groups = {}, personProperties = {}, groupProperties = {}, extraPayload = {}, fetchConfig = false) {\n await this._initPromise;\n const configParam = fetchConfig ? '&config=true' : '';\n const url = `${this.host}/flags/?v=2${configParam}`;\n const requestData = {\n token: this.apiKey,\n distinct_id: distinctId,\n groups,\n person_properties: personProperties,\n group_properties: groupProperties,\n ...extraPayload\n };\n if (personProperties.$device_id) requestData.$device_id = personProperties.$device_id;\n if (this.evaluationContexts && this.evaluationContexts.length > 0) requestData.evaluation_contexts = this.evaluationContexts;\n const fetchOptions = {\n method: 'POST',\n headers: {\n ...this.getCustomHeaders(),\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(requestData)\n };\n this._logger.info('Flags URL', url);\n return this.fetchWithRetry(url, fetchOptions, {\n retryCount: this.featureFlagsRequestMaxRetries,\n retryCheck: isRetryableFlagsFetchError\n }, this.featureFlagsRequestTimeoutMs).then((response)=>response.json()).then((response)=>({\n success: true,\n response: normalizeFlagsResponse(response)\n })).catch((error)=>{\n this._events.emit('error', error);\n return {\n success: false,\n error: this.categorizeRequestError(error)\n };\n });\n }\n categorizeRequestError(error) {\n if (error instanceof PostHogFetchHttpError) return {\n type: 'api_error',\n statusCode: error.status\n };\n if (error instanceof PostHogFetchNetworkError) {\n const cause = error.error;\n if (cause instanceof Error && ('AbortError' === cause.name || 'TimeoutError' === cause.name)) return {\n type: 'timeout'\n };\n return {\n type: 'connection_error'\n };\n }\n return {\n type: 'unknown_error'\n };\n }\n async getFeatureFlagStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {\n await this._initPromise;\n const flagDetailResponse = await this.getFeatureFlagDetailStateless(key, distinctId, groups, personProperties, groupProperties, disableGeoip);\n if (void 0 === flagDetailResponse) return {\n response: void 0,\n requestId: void 0\n };\n let response = getFeatureFlagValue(flagDetailResponse.response);\n if (void 0 === response) response = false;\n return {\n response,\n requestId: flagDetailResponse.requestId\n };\n }\n async getFeatureFlagDetailStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {\n await this._initPromise;\n const flagsResponse = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [\n key\n ]);\n if (void 0 === flagsResponse) return;\n const featureFlags = flagsResponse.flags;\n const flagDetail = featureFlags[key];\n return {\n response: flagDetail,\n requestId: flagsResponse.requestId,\n evaluatedAt: flagsResponse.evaluatedAt\n };\n }\n async getFeatureFlagPayloadStateless(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip) {\n await this._initPromise;\n const payloads = await this.getFeatureFlagPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, [\n key\n ]);\n if (!payloads) return;\n const response = payloads[key];\n if (void 0 === response) return null;\n return response;\n }\n async getFeatureFlagPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {\n await this._initPromise;\n const payloads = (await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate)).payloads;\n return payloads;\n }\n async getFeatureFlagsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {\n await this._initPromise;\n return await this.getFeatureFlagsAndPayloadsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);\n }\n async getFeatureFlagsAndPayloadsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {\n await this._initPromise;\n const featureFlagDetails = await this.getFeatureFlagDetailsStateless(distinctId, groups, personProperties, groupProperties, disableGeoip, flagKeysToEvaluate);\n if (!featureFlagDetails) return {\n flags: void 0,\n payloads: void 0,\n requestId: void 0\n };\n return {\n flags: featureFlagDetails.featureFlags,\n payloads: featureFlagDetails.featureFlagPayloads,\n requestId: featureFlagDetails.requestId\n };\n }\n async getFeatureFlagDetailsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {\n await this._initPromise;\n const extraPayload = {\n geoip_disable: disableGeoip ?? this.disableGeoip\n };\n if (flagKeysToEvaluate) extraPayload['flag_keys_to_evaluate'] = flagKeysToEvaluate;\n const result = await this.getFlags(distinctId, groups, personProperties, groupProperties, extraPayload);\n if (!result.success) return;\n const flagsResponse = result.response;\n if (flagsResponse.errorsWhileComputingFlags) console.error('[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices');\n if (flagsResponse.quotaLimited?.includes(\"feature_flags\")) {\n console.warn('[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts');\n return {\n flags: {},\n featureFlags: {},\n featureFlagPayloads: {},\n requestId: flagsResponse?.requestId,\n quotaLimited: flagsResponse.quotaLimited\n };\n }\n return flagsResponse;\n }\n async getSurveysStateless() {\n await this._initPromise;\n if (this.disabled) return [];\n if (true === this.disableSurveys) {\n this._logger.info('Loading surveys is disabled.');\n return [];\n }\n const url = `${this.host}/api/surveys/?token=${this.apiKey}`;\n const fetchOptions = {\n method: 'GET',\n headers: {\n ...this.getCustomHeaders(),\n 'Content-Type': 'application/json'\n }\n };\n const response = await this.fetchWithRetry(url, fetchOptions).then((response)=>{\n if (200 !== response.status || !response.json) {\n const msg = `Surveys API could not be loaded: ${response.status}`;\n const error = new Error(msg);\n this._logger.error(error);\n this._events.emit('error', new Error(msg));\n return;\n }\n return response.json();\n }).catch((error)=>{\n this._logger.error('Surveys API could not be loaded', error);\n this._events.emit('error', error);\n });\n const newSurveys = response?.surveys;\n if (newSurveys) this._logger.info('Surveys fetched from API: ', JSON.stringify(newSurveys));\n return newSurveys ?? [];\n }\n get props() {\n if (!this._props) this._props = this.getPersistedProperty(PostHogPersistedProperty.Props);\n return this._props || {};\n }\n set props(val) {\n this._props = val;\n }\n async register(properties) {\n this.wrap(()=>{\n this.props = {\n ...this.props,\n ...properties\n };\n this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);\n });\n }\n async unregister(property) {\n this.wrap(()=>{\n delete this.props[property];\n this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);\n });\n }\n processBeforeEnqueue(message) {\n return message;\n }\n async flushStorage() {}\n getQueueRouteKey(_message) {\n return DEFAULT_QUEUE_ROUTE;\n }\n persistedQueueKeyForRoute(_route) {\n return PostHogPersistedProperty.Queue;\n }\n getActiveQueueRoutes() {\n return [\n DEFAULT_QUEUE_ROUTE\n ];\n }\n getRouteQueue(route) {\n return this.getPersistedProperty(this.persistedQueueKeyForRoute(route)) || [];\n }\n enqueue(type, _message, options) {\n this.wrap(()=>{\n if (this.optedOut) return void this._events.emit(type, \"Library is disabled. Not sending event. To re-enable, call posthog.optIn()\");\n let message = this.prepareMessage(_message, options);\n message = this.processBeforeEnqueue(message);\n if (null === message) return;\n message = this.normalizeMessage(message);\n const queueKey = this.persistedQueueKeyForRoute(this.getQueueRouteKey(message));\n const queue = this.getPersistedProperty(queueKey) || [];\n if (queue.length >= this.maxQueueSize) {\n queue.shift();\n this._logger.warn('Queue is full, the oldest event is dropped.');\n }\n queue.push({\n message\n });\n this.setPersistedProperty(queueKey, queue);\n this._events.emit(type, message);\n if (queue.length >= this.flushAt) this.flushBackground();\n if (this.flushInterval && !this._flushTimer) this._flushTimer = safeSetTimeout(()=>this.flushBackground(), this.flushInterval);\n });\n }\n async sendImmediate(type, _message, options) {\n if (this.disabled) return void this._logger.warn('The client is disabled');\n if (!this._isInitialized) await this._initPromise;\n if (this.optedOut) return void this._events.emit(type, \"Library is disabled. Not sending event. To re-enable, call posthog.optIn()\");\n let message = this.prepareMessage(_message, options);\n message = this.processBeforeEnqueue(message);\n if (null === message) return;\n message = this.normalizeMessage(message);\n try {\n await this.sendBatch([\n message\n ], void 0, this.getQueueRouteKey(message));\n } catch (err) {\n this._events.emit('error', err);\n }\n }\n normalizeMessage(message) {\n const { type: _type, library, library_version, ...sanitizedMessage } = message;\n let properties = isPostHogEventProperties(sanitizedMessage.properties) ? sanitizedMessage.properties : void 0;\n if (void 0 !== library && properties?.$lib === void 0) properties = {\n ...properties || {},\n $lib: library\n };\n if (void 0 !== library_version && properties?.$lib_version === void 0) properties = {\n ...properties || {},\n $lib_version: library_version\n };\n if (properties) sanitizedMessage.properties = properties;\n sanitizedMessage.uuid = getEventUuid(sanitizedMessage.uuid, uuidv7);\n return sanitizedMessage;\n }\n prepareMessage(_message, options) {\n const message = {\n ..._message,\n timestamp: options?.timestamp ? options?.timestamp : currentISOTime(),\n uuid: getEventUuid(options?.uuid, uuidv7)\n };\n const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip;\n if (addGeoipDisableProperty) {\n if (!isPostHogEventProperties(message.properties)) message.properties = {};\n message.properties['$geoip_disable'] = true;\n }\n if (message.distinctId) {\n message.distinct_id = message.distinctId;\n delete message.distinctId;\n }\n return message;\n }\n clearFlushTimer() {\n if (this._flushTimer) {\n clearTimeout(this._flushTimer);\n this._flushTimer = void 0;\n }\n }\n flushBackground() {\n if (this.pendingFlushPromise) return;\n this.flush().catch(async (err)=>{\n await logFlushError(err);\n });\n }\n async waitForPendingPromises(maxPromiseId, ignoredPromises = []) {\n const ignoredPendingPromises = ignoredPromises.filter((promise)=>!!promise);\n let iteration = 0;\n while(true){\n const promises = this.promiseQueue.getPromises([\n ...ignoredPendingPromises,\n ...this.flushPromises\n ], maxPromiseId);\n if (0 === promises.length) return;\n if (iteration > 0) this._logger.debug(`flush() re-checking ${promises.length} pending promise(s) before flushing`);\n await Promise.all(promises.map((promise)=>promise.catch(()=>{})));\n iteration++;\n }\n }\n flushWithPendingPromises() {\n return this.flushInternal(true);\n }\n flush() {\n return this.flushInternal(false);\n }\n flushInternal(waitForPendingPromises) {\n if (this.disabled) return Promise.resolve();\n if (!waitForPendingPromises && this.pendingFlushPromise) return this.pendingFlushPromise;\n const previousFlushPromise = this.flushPromise;\n const maxPromiseId = this.promiseQueue.maxId;\n const nextFlushPromise = Promise.resolve().then(()=>{\n if (waitForPendingPromises) return this.waitForPendingPromises(maxPromiseId, [\n previousFlushPromise,\n nextFlushPromise\n ]);\n }).then(()=>allSettled([\n previousFlushPromise\n ])).then(()=>{\n if (this.pendingFlushPromise === nextFlushPromise) this.pendingFlushPromise = null;\n return this._flush();\n });\n this.pendingFlushPromise = nextFlushPromise;\n this.flushPromise = nextFlushPromise;\n this.flushPromises.add(nextFlushPromise);\n this.addPendingPromise(nextFlushPromise);\n allSettled([\n nextFlushPromise\n ]).then(()=>{\n this.flushPromises.delete(nextFlushPromise);\n if (this.pendingFlushPromise === nextFlushPromise) this.pendingFlushPromise = null;\n if (this.flushPromise === nextFlushPromise) this.flushPromise = null;\n });\n return nextFlushPromise;\n }\n getCustomHeaders() {\n const customUserAgent = this.getCustomUserAgent();\n const headers = {};\n if (customUserAgent && '' !== customUserAgent) headers['User-Agent'] = customUserAgent;\n return headers;\n }\n async sendBatch(batchMessages, retryOptions, _route = DEFAULT_QUEUE_ROUTE) {\n const data = {\n api_key: this.apiKey,\n batch: batchMessages,\n sent_at: currentISOTime()\n };\n if (this.historicalMigration) data.historical_migration = true;\n const payload = safeJsonStringify(data);\n const url = `${this.host}/batch/`;\n const gzippedPayload = this.disableCompression ? null : await gzipCompress(payload, this.isDebug);\n const fetchOptions = {\n method: 'POST',\n headers: {\n ...this.getCustomHeaders(),\n 'Content-Type': 'application/json',\n ...null !== gzippedPayload && {\n 'Content-Encoding': 'gzip'\n }\n },\n body: gzippedPayload || payload\n };\n const response = await this.fetchWithRetry(url, fetchOptions, retryOptions);\n await response.body?.cancel()?.catch(()=>{});\n }\n async _flush() {\n this.clearFlushTimer();\n await this._initPromise;\n const routes = this.getActiveQueueRoutes();\n if (!routes.some((route)=>this.getRouteQueue(route).length > 0)) return;\n const sentMessages = [];\n let firstError;\n for (const route of routes)try {\n await this._flushRoute(route, sentMessages);\n } catch (err) {\n if (void 0 === firstError) firstError = err;\n }\n if (void 0 !== firstError) throw firstError;\n this._events.emit('flush', sentMessages);\n }\n async _flushRoute(route, sentMessages) {\n const queueKey = this.persistedQueueKeyForRoute(route);\n let queue = this.getPersistedProperty(queueKey) || [];\n if (!queue.length) return;\n const originalQueueLength = queue.length;\n let sentFromRoute = 0;\n while(queue.length > 0 && sentFromRoute < originalQueueLength){\n const batchItems = queue.slice(0, this.maxBatchSize);\n const batchMessages = batchItems.map((item)=>void 0 === item.message ? item.message : this.normalizeMessage(item.message));\n const persistQueueChange = async ()=>{\n const refreshedQueue = this.getPersistedProperty(queueKey) || [];\n const newQueue = refreshedQueue.slice(batchItems.length);\n this.setPersistedProperty(queueKey, newQueue);\n queue = newQueue;\n this._dequeuedMessagesCount += batchItems.length;\n await this.flushStorage();\n };\n const retryOptions = {\n retryCheck: (err)=>{\n if (isPostHogFetchContentTooLargeError(err)) return false;\n return isPostHogFetchRetryableError(err);\n }\n };\n try {\n await this.sendBatch(batchMessages, retryOptions, route);\n } catch (err) {\n if (isPostHogFetchContentTooLargeError(err) && batchMessages.length > 1) {\n this.maxBatchSize = Math.max(1, Math.floor(batchMessages.length / 2));\n this._logger.warn(`Received 413 when sending batch of size ${batchMessages.length}, reducing batch size to ${this.maxBatchSize}`);\n continue;\n }\n if (!(err instanceof PostHogFetchNetworkError)) await persistQueueChange();\n this._events.emit('error', err);\n throw err;\n }\n await persistQueueChange();\n sentMessages.push(...batchMessages);\n sentFromRoute += batchMessages.length;\n }\n }\n async _sendLogsBatch(payload) {\n if (this.disabled) return {\n kind: 'fatal',\n error: new Error('The client is disabled')\n };\n const serialized = JSON.stringify(payload);\n const url = `${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`;\n const gzippedPayload = this.disableCompression ? null : await gzipCompress(serialized, this.isDebug);\n const fetchOptions = {\n method: 'POST',\n headers: {\n ...this.getCustomHeaders(),\n 'Content-Type': 'application/json',\n ...null !== gzippedPayload && {\n 'Content-Encoding': 'gzip'\n }\n },\n body: gzippedPayload || serialized\n };\n try {\n await this.fetchWithRetry(url, fetchOptions, {\n retryCheck: (err)=>{\n if (isPostHogFetchContentTooLargeError(err)) return false;\n return isPostHogFetchRetryableError(err);\n }\n });\n return {\n kind: 'ok'\n };\n } catch (err) {\n if (isPostHogFetchContentTooLargeError(err)) return {\n kind: 'too-large'\n };\n if (err instanceof PostHogFetchNetworkError) return {\n kind: 'retry-later',\n error: err\n };\n return {\n kind: 'fatal',\n error: err\n };\n }\n }\n async _sendMetricsBatch(payload) {\n if (this.disabled) return {\n kind: 'fatal',\n error: new Error('The client is disabled')\n };\n const serialized = JSON.stringify(payload);\n const url = `${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`;\n const gzippedPayload = this.disableCompression ? null : await gzipCompress(serialized, this.isDebug);\n const fetchOptions = {\n method: 'POST',\n headers: {\n ...this.getCustomHeaders(),\n 'Content-Type': 'application/json',\n ...null !== gzippedPayload && {\n 'Content-Encoding': 'gzip'\n }\n },\n body: gzippedPayload || serialized\n };\n try {\n await this.fetchWithRetry(url, fetchOptions, {\n retryCheck: (err)=>{\n if (isPostHogFetchContentTooLargeError(err)) return false;\n return isPostHogFetchRetryableError(err);\n }\n });\n return {\n kind: 'ok'\n };\n } catch (err) {\n if (isPostHogFetchContentTooLargeError(err)) return {\n kind: 'too-large'\n };\n if (isPostHogFetchRetryableError(err)) return {\n kind: 'retry-later',\n error: err\n };\n return {\n kind: 'fatal',\n error: err\n };\n }\n }\n async fetchWithRetry(url, options, retryOptions, requestTimeout) {\n const body = options.body ? options.body : '';\n let reqByteLength = -1;\n try {\n reqByteLength = body instanceof Blob ? body.size : Buffer.byteLength(body, STRING_FORMAT);\n } catch {\n if (body instanceof Blob) reqByteLength = body.size;\n else {\n const encoded = new TextEncoder().encode(body);\n reqByteLength = encoded.length;\n }\n }\n return await retriable(async ()=>{\n const ctrl = new AbortController();\n const timeoutMs = requestTimeout ?? this.requestTimeout;\n const timer = safeSetTimeout(()=>ctrl.abort(), timeoutMs);\n let res = null;\n try {\n res = await this.fetch(url, {\n signal: ctrl.signal,\n ...options\n });\n } catch (e) {\n throw new PostHogFetchNetworkError(e);\n } finally{\n clearTimeout(timer);\n }\n const isNoCors = 'no-cors' === options.mode;\n if (!isNoCors && (res.status < 200 || res.status >= 400)) throw new PostHogFetchHttpError(res, reqByteLength);\n return res;\n }, {\n ...this._retryOptions,\n ...retryOptions\n });\n }\n async _shutdown(shutdownTimeoutMs = 30000) {\n await this._initPromise;\n let hasTimedOut = false;\n this.clearFlushTimer();\n if (this.disabled) return;\n const doShutdown = async ()=>{\n try {\n await this.promiseQueue.join();\n while(true){\n const hasQueuedEvents = this.getActiveQueueRoutes().some((route)=>this.getRouteQueue(route).length > 0);\n if (!hasQueuedEvents) break;\n const dequeuedBeforeFlush = this._dequeuedMessagesCount;\n await this.flush();\n if (hasTimedOut) break;\n if (this._dequeuedMessagesCount === dequeuedBeforeFlush) {\n this._logger.warn('Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.');\n break;\n }\n }\n } catch (e) {\n if (!isPostHogFetchError(e)) throw e;\n await logFlushError(e);\n }\n };\n let timeoutHandle;\n try {\n return await Promise.race([\n new Promise((_, reject)=>{\n timeoutHandle = safeSetTimeout(()=>{\n this._logger.error('Timed out while shutting down PostHog');\n hasTimedOut = true;\n reject('Timeout while shutting down PostHog. Some events may not have been sent.');\n }, shutdownTimeoutMs);\n }),\n doShutdown()\n ]);\n } finally{\n clearTimeout(timeoutHandle);\n }\n }\n async shutdown(shutdownTimeoutMs = 30000) {\n if (this.shutdownPromise) this._logger.warn('shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup');\n else this.shutdownPromise = this._shutdown(shutdownTimeoutMs).finally(()=>{\n this.shutdownPromise = null;\n });\n return this.shutdownPromise;\n }\n}\nexport { PostHogCoreStateless, posthog_core_stateless_QuotaLimitedFeature as QuotaLimitedFeature, applyCallerFeatureFlagOverrides, isPostHogFetchNetworkError, logFlushError, maybeAdd };\n","import { createFlagsResponseFromFlagsAndPayloads, flagDetailsToResults, getEnabledFromValue, getFeatureFlagValue, getFlagValuesFromFlags, getPayloadsFromFlags, getVariantFromValue, normalizeFlagsResponse, parsePayload, updateFlagValue } from \"./featureFlagUtils.mjs\";\nimport { Compression, FeatureFlagError, PostHogPersistedProperty } from \"./types.mjs\";\nimport { PostHogCoreStateless, QuotaLimitedFeature, applyCallerFeatureFlagOverrides, maybeAdd } from \"./posthog-core-stateless.mjs\";\nimport { uuidv7 } from \"./vendor/uuidv7.mjs\";\nimport { getEventUuid, getPersonPropertiesHash, isArray, isEmptyObject, isNullish, isObject, isString } from \"./utils/index.mjs\";\nclass PostHogCore extends PostHogCoreStateless {\n constructor(apiKey, options){\n const disableGeoipOption = options?.disableGeoip ?? false;\n const featureFlagsRequestTimeoutMs = options?.featureFlagsRequestTimeoutMs ?? 10000;\n super(apiKey, {\n ...options,\n disableGeoip: disableGeoipOption,\n featureFlagsRequestTimeoutMs\n }), this.flagCallReported = {}, this._sessionMaxLengthSeconds = 86400, this.sessionProps = {}, this._cachedPersonProperties = null;\n this.sendFeatureFlagEvent = options?.sendFeatureFlagEvent ?? true;\n this.disableRemoteFeatureFlags = options?.disableRemoteFeatureFlags ?? false;\n this._sessionExpirationTimeSeconds = options?.sessionExpirationTimeSeconds ?? 1800;\n this._personProfiles = options?.personProfiles ?? 'identified_only';\n this._beforeSend = options?.before_send;\n }\n setupBootstrap(options) {\n const bootstrap = options?.bootstrap;\n if (!bootstrap) return;\n if (bootstrap.distinctId) if (bootstrap.isIdentifiedId) {\n const distinctId = this.getPersistedProperty(PostHogPersistedProperty.DistinctId);\n if (!distinctId) {\n this.setPersistedProperty(PostHogPersistedProperty.DistinctId, bootstrap.distinctId);\n this.setPersistedProperty(PostHogPersistedProperty.PersonMode, 'identified');\n }\n } else {\n const anonymousId = this.getPersistedProperty(PostHogPersistedProperty.AnonymousId);\n if (!anonymousId) this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, bootstrap.distinctId);\n }\n const bootstrapFeatureFlags = bootstrap.featureFlags;\n const bootstrapFeatureFlagPayloads = bootstrap.featureFlagPayloads ?? {};\n if (bootstrapFeatureFlags && Object.keys(bootstrapFeatureFlags).length) {\n const normalizedBootstrapFeatureFlagDetails = createFlagsResponseFromFlagsAndPayloads(bootstrapFeatureFlags, bootstrapFeatureFlagPayloads);\n if (Object.keys(normalizedBootstrapFeatureFlagDetails.flags).length > 0) {\n this.setBootstrappedFeatureFlagDetails(normalizedBootstrapFeatureFlagDetails);\n const currentFeatureFlagDetails = this.getKnownFeatureFlagDetails() || {\n flags: {},\n requestId: void 0\n };\n const newFeatureFlagDetails = {\n flags: {\n ...normalizedBootstrapFeatureFlagDetails.flags,\n ...currentFeatureFlagDetails.flags\n },\n requestId: normalizedBootstrapFeatureFlagDetails.requestId\n };\n this.setKnownFeatureFlagDetails(newFeatureFlagDetails);\n }\n }\n }\n clearProps() {\n this.props = void 0;\n this.sessionProps = {};\n this.flagCallReported = {};\n }\n on(event, cb) {\n return this._events.on(event, cb);\n }\n reset(propertiesToKeep) {\n this.wrap(()=>{\n const allPropertiesToKeep = [\n PostHogPersistedProperty.Queue,\n PostHogPersistedProperty.AiQueue,\n PostHogPersistedProperty.LogsQueue,\n ...propertiesToKeep || []\n ];\n this.clearProps();\n this._cachedPersonProperties = null;\n for (const key of Object.keys(PostHogPersistedProperty))if (!allPropertiesToKeep.includes(PostHogPersistedProperty[key])) this.setPersistedProperty(PostHogPersistedProperty[key], null);\n if (this.disableRemoteFeatureFlags && !this.disabled) {\n if (!allPropertiesToKeep.includes(PostHogPersistedProperty.FeatureFlagDetails)) this.setKnownFeatureFlagDetails({\n flags: {}\n });\n } else this.reloadFeatureFlags();\n });\n }\n async _shutdown(shutdownTimeoutMs = 30000) {\n try {\n return await super._shutdown(shutdownTimeoutMs);\n } finally{\n this.flagCallReported = {};\n }\n }\n getCommonEventProperties() {\n const featureFlags = this.getFeatureFlags();\n const featureVariantProperties = {};\n if (featureFlags) for (const [feature, variant] of Object.entries(featureFlags))featureVariantProperties[`$feature/${feature}`] = variant;\n return {\n ...maybeAdd('$active_feature_flags', featureFlags ? Object.keys(featureFlags) : void 0),\n ...featureVariantProperties,\n ...super.getCommonEventProperties()\n };\n }\n enrichProperties(properties) {\n const userProperties = properties || {};\n const enriched = {\n ...this.props,\n ...this.sessionProps,\n ...userProperties,\n ...this.getCommonEventProperties(),\n $session_id: this.getSessionId()\n };\n applyCallerFeatureFlagOverrides(enriched, userProperties);\n return enriched;\n }\n getSessionId() {\n if (!this._isInitialized) return '';\n let sessionId = this.getPersistedProperty(PostHogPersistedProperty.SessionId);\n const sessionLastTimestamp = this.getPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp) || 0;\n const sessionStartTimestamp = this.getPersistedProperty(PostHogPersistedProperty.SessionStartTimestamp) || 0;\n const now = Date.now();\n const sessionLastDif = now - sessionLastTimestamp;\n const sessionStartDif = now - sessionStartTimestamp;\n if (!sessionId || sessionLastDif > 1000 * this._sessionExpirationTimeSeconds || sessionStartDif > 1000 * this._sessionMaxLengthSeconds) {\n sessionId = uuidv7();\n this.setPersistedProperty(PostHogPersistedProperty.SessionId, sessionId);\n this.setPersistedProperty(PostHogPersistedProperty.SessionStartTimestamp, now);\n }\n this.setPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp, now);\n return sessionId;\n }\n resetSessionId() {\n this.wrap(()=>{\n this.setPersistedProperty(PostHogPersistedProperty.SessionId, null);\n this.setPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp, null);\n this.setPersistedProperty(PostHogPersistedProperty.SessionStartTimestamp, null);\n });\n }\n getAnonymousId() {\n if (!this._isInitialized) return '';\n let anonId = this.getPersistedProperty(PostHogPersistedProperty.AnonymousId);\n if (!anonId) {\n anonId = uuidv7();\n this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, anonId);\n }\n return anonId;\n }\n getDistinctId() {\n if (!this._isInitialized) return '';\n return this.getPersistedProperty(PostHogPersistedProperty.DistinctId) || this.getAnonymousId();\n }\n registerForSession(properties) {\n this.sessionProps = {\n ...this.sessionProps,\n ...properties\n };\n }\n unregisterForSession(property) {\n delete this.sessionProps[property];\n }\n identify(distinctId, properties, options) {\n this.wrap(()=>{\n if (!this._requirePersonProcessing('posthog.identify')) return;\n const previousDistinctId = this.getDistinctId();\n distinctId = distinctId || previousDistinctId;\n if (properties?.$groups) this.groups(properties.$groups);\n const userPropsOnce = properties?.$set_once;\n delete properties?.$set_once;\n const userProps = properties?.$set || properties;\n const allProperties = this.enrichProperties({\n $anon_distinct_id: this.getAnonymousId(),\n ...maybeAdd('$set', userProps),\n ...maybeAdd('$set_once', userPropsOnce)\n });\n const userPropsObj = isObject(userProps) ? userProps : void 0;\n const userPropsOnceObj = isObject(userPropsOnce) ? userPropsOnce : void 0;\n if (distinctId !== previousDistinctId) {\n this.setPersistedProperty(PostHogPersistedProperty.AnonymousId, previousDistinctId);\n this.setPersistedProperty(PostHogPersistedProperty.DistinctId, distinctId);\n this.setPersistedProperty(PostHogPersistedProperty.PersonMode, 'identified');\n this.reloadFeatureFlags();\n super.identifyStateless(distinctId, allProperties, options);\n this._cachedPersonProperties = getPersonPropertiesHash(distinctId, userPropsObj, userPropsOnceObj);\n } else if (userPropsObj || userPropsOnceObj) this.setPersonProperties(userPropsObj, userPropsOnceObj);\n });\n }\n capture(event, properties, options) {\n if ('$exception' === event && !options?._originatedFromCaptureException) this._logger.warn(\"Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically.\");\n this.wrap(()=>{\n const distinctId = this.getDistinctId();\n if (properties?.$groups) this.groups(properties.$groups);\n const allProperties = this.enrichProperties(properties);\n const hasPersonProcessing = this._hasPersonProcessing();\n allProperties['$process_person_profile'] = hasPersonProcessing;\n allProperties['$is_identified'] = this._isIdentified();\n if (hasPersonProcessing) this._requirePersonProcessing('capture');\n super.captureStateless(distinctId, event, allProperties, options);\n });\n }\n alias(alias) {\n this.wrap(()=>{\n if (!this._requirePersonProcessing('posthog.alias')) return;\n const distinctId = this.getDistinctId();\n const allProperties = this.enrichProperties({});\n super.aliasStateless(alias, distinctId, allProperties);\n });\n }\n autocapture(eventType, elements, properties = {}, options) {\n this.wrap(()=>{\n const distinctId = this.getDistinctId();\n const payload = {\n distinct_id: distinctId,\n event: '$autocapture',\n properties: {\n ...this.enrichProperties(properties),\n $event_type: eventType,\n $elements: elements\n }\n };\n this.enqueue('autocapture', payload, options);\n });\n }\n groups(groups) {\n this.wrap(()=>{\n if (!this._requirePersonProcessing('posthog.group')) return;\n const existingGroups = this.props.$groups || {};\n this.register({\n $groups: {\n ...existingGroups,\n ...groups\n }\n });\n if (Object.keys(groups).find((type)=>existingGroups[type] !== groups[type])) this.reloadFeatureFlags();\n });\n }\n group(groupType, groupKey, groupProperties, options) {\n this.wrap(()=>{\n const existingGroups = this.props.$groups || {};\n const isNewGroup = existingGroups[groupType] !== groupKey;\n this.groups({\n [groupType]: groupKey\n });\n if (isNewGroup || groupProperties) this.groupIdentify(groupType, groupKey, groupProperties, options);\n });\n }\n groupIdentify(groupType, groupKey, groupProperties, options) {\n this.wrap(()=>{\n if (!this._requirePersonProcessing('posthog.groupIdentify')) return;\n const distinctId = this.getDistinctId();\n const eventProperties = this.enrichProperties({});\n super.groupIdentifyStateless(groupType, groupKey, groupProperties, options, distinctId, eventProperties);\n });\n }\n setPersonPropertiesForFlags(properties, reloadFeatureFlags = true) {\n this.wrap(()=>{\n const existingProperties = this.getPersistedProperty(PostHogPersistedProperty.PersonProperties) || {};\n const propsToSet = properties?.['$set'] || (properties?.['$set_once'] ? {} : properties);\n const propsToSetOnce = properties?.['$set_once'];\n const setOnceProps = {};\n if (propsToSetOnce) {\n for(const key in propsToSetOnce)if (Object.prototype.hasOwnProperty.call(propsToSetOnce, key)) {\n if (!(key in existingProperties)) setOnceProps[key] = propsToSetOnce[key];\n }\n }\n this.setPersistedProperty(PostHogPersistedProperty.PersonProperties, {\n ...existingProperties,\n ...setOnceProps,\n ...propsToSet\n });\n if (reloadFeatureFlags) this.reloadFeatureFlags();\n });\n }\n resetPersonPropertiesForFlags() {\n this.wrap(()=>{\n this.setPersistedProperty(PostHogPersistedProperty.PersonProperties, null);\n });\n }\n setGroupPropertiesForFlags(properties) {\n this.wrap(()=>{\n const existingProperties = this.getPersistedProperty(PostHogPersistedProperty.GroupProperties) || {};\n if (0 !== Object.keys(existingProperties).length) Object.keys(existingProperties).forEach((groupType)=>{\n existingProperties[groupType] = {\n ...existingProperties[groupType],\n ...properties[groupType]\n };\n delete properties[groupType];\n });\n this.setPersistedProperty(PostHogPersistedProperty.GroupProperties, {\n ...existingProperties,\n ...properties\n });\n });\n }\n resetGroupPropertiesForFlags() {\n this.wrap(()=>{\n this.setPersistedProperty(PostHogPersistedProperty.GroupProperties, null);\n });\n }\n async remoteConfigAsync() {\n await this._initPromise;\n if (this.disabled) return;\n if (this._remoteConfigResponsePromise) return this._remoteConfigResponsePromise;\n return this._remoteConfigAsync();\n }\n async flagsAsync(options) {\n const { sendAnonDistinctId = true, fetchConfig = false, triggerOnRemoteConfig = false } = options ?? {};\n await this._initPromise;\n if (this.disabled) return;\n if (this.disableRemoteFeatureFlags && !fetchConfig) return void this._logger.info('Feature flags are disabled (disableRemoteFeatureFlags), skipping reload.');\n if (this._flagsResponsePromise) {\n this._logger.info('Feature flags are being loaded already, queuing reload.');\n if (this._pendingFlagsRequest) this._flagsResponsePromise.then(this._pendingFlagsRequest.resolve).catch(this._pendingFlagsRequest.reject);\n return new Promise((resolve, reject)=>{\n this._pendingFlagsRequest = {\n sendAnonDistinctId,\n fetchConfig,\n triggerOnRemoteConfig,\n resolve,\n reject\n };\n });\n }\n return this._flagsAsync({\n sendAnonDistinctId,\n fetchConfig,\n triggerOnRemoteConfig\n });\n }\n onRemoteConfig(_response) {}\n maybeNotifyRemoteConfig(shouldTrigger, response) {\n if (shouldTrigger) try {\n this.onRemoteConfig(response);\n } catch (e) {\n this._logger.error('Error in onRemoteConfig callback:', e);\n }\n }\n cacheSessionReplay(source, response) {\n const sessionReplay = response?.sessionRecording;\n if (sessionReplay) {\n this.setPersistedProperty(PostHogPersistedProperty.SessionReplay, sessionReplay);\n this._logger.info(`Session replay config from ${source}: `, JSON.stringify(sessionReplay));\n } else if ('boolean' == typeof sessionReplay && false === sessionReplay) {\n this._logger.info(`Session replay config from ${source} disabled.`);\n this.setPersistedProperty(PostHogPersistedProperty.SessionReplay, null);\n }\n }\n async _remoteConfigAsync() {\n this._remoteConfigResponsePromise = this._initPromise.then(()=>{\n let remoteConfig = this.getPersistedProperty(PostHogPersistedProperty.RemoteConfig);\n this._logger.info('Cached remote config: ', JSON.stringify(remoteConfig));\n return super.getRemoteConfig().then((response)=>{\n if (response) {\n const remoteConfigWithoutSurveys = {\n ...response\n };\n delete remoteConfigWithoutSurveys.surveys;\n this._logger.info('Fetched remote config: ', JSON.stringify(remoteConfigWithoutSurveys));\n if (false === this.disableSurveys) {\n const surveys = response.surveys;\n let hasSurveys = true;\n if (Array.isArray(surveys)) this._logger.info('Surveys fetched from remote config: ', JSON.stringify(surveys));\n else {\n this._logger.info('There are no surveys.');\n hasSurveys = false;\n }\n if (hasSurveys) this.setPersistedProperty(PostHogPersistedProperty.Surveys, surveys);\n else this.setPersistedProperty(PostHogPersistedProperty.Surveys, null);\n } else this.setPersistedProperty(PostHogPersistedProperty.Surveys, null);\n this.setPersistedProperty(PostHogPersistedProperty.RemoteConfig, remoteConfigWithoutSurveys);\n this.cacheSessionReplay('remote config', response);\n let willLoadFlags = false;\n if (false === response.hasFeatureFlags) {\n if (!this.disableRemoteFeatureFlags) this.setKnownFeatureFlagDetails({\n flags: {}\n });\n this._logger.warn('Remote config has no feature flags, will not load feature flags.');\n } else if (false !== this.preloadFeatureFlags && !this.disableRemoteFeatureFlags) {\n willLoadFlags = true;\n this.flagsAsync({\n sendAnonDistinctId: true,\n fetchConfig: true,\n triggerOnRemoteConfig: true\n });\n }\n if (!response.supportedCompression?.includes(Compression.GZipJS)) this.disableCompression = true;\n this.maybeNotifyRemoteConfig(!willLoadFlags, response);\n remoteConfig = response;\n }\n return remoteConfig;\n });\n }).finally(()=>{\n this._remoteConfigResponsePromise = void 0;\n });\n return this._remoteConfigResponsePromise;\n }\n async _flagsAsync(options) {\n const sendAnonDistinctId = options?.sendAnonDistinctId ?? true;\n const fetchConfig = options?.fetchConfig ?? false;\n const triggerOnRemoteConfig = options?.triggerOnRemoteConfig ?? false;\n this._flagsResponsePromise = this._initPromise.then(async ()=>{\n const distinctId = this.getDistinctId();\n const groups = this.props.$groups || {};\n const personProperties = this.getPersistedProperty(PostHogPersistedProperty.PersonProperties) || {};\n const groupProperties = this.getPersistedProperty(PostHogPersistedProperty.GroupProperties) || {};\n const deviceId = this.getPersistedProperty(PostHogPersistedProperty.DeviceId);\n const extraProperties = {\n $anon_distinct_id: sendAnonDistinctId ? this.getAnonymousId() : void 0,\n $device_id: deviceId ?? void 0,\n ...this.disableRemoteFeatureFlags ? {\n disable_flags: true\n } : {}\n };\n const result = await super.getFlags(distinctId, groups, personProperties, groupProperties, extraProperties, fetchConfig);\n if (!result.success) {\n if (!this.disableRemoteFeatureFlags) this.setKnownFeatureFlagDetails({\n flags: this.getKnownFeatureFlagDetails()?.flags ?? {},\n requestError: result.error,\n minimalFlagCalledEvents: this.getStoredFlagDetails()?.minimalFlagCalledEvents\n });\n return;\n }\n const res = result.response;\n if (res?.quotaLimited?.includes(QuotaLimitedFeature.FeatureFlags)) {\n if (!this.disableRemoteFeatureFlags) this.setKnownFeatureFlagDetails({\n flags: this.getKnownFeatureFlagDetails()?.flags ?? {},\n quotaLimited: res.quotaLimited,\n minimalFlagCalledEvents: this.getStoredFlagDetails()?.minimalFlagCalledEvents\n });\n this._logger.warn('[FEATURE FLAGS] Feature flags quota limit exceeded. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts');\n this.maybeNotifyRemoteConfig(triggerOnRemoteConfig, res);\n return res;\n }\n if (res?.featureFlags) {\n if (this.disableRemoteFeatureFlags) {\n this.cacheSessionReplay('flags', res);\n this.maybeNotifyRemoteConfig(triggerOnRemoteConfig, res);\n return res;\n }\n let newFeatureFlagDetails = res;\n if (res.errorsWhileComputingFlags) {\n const currentFlagDetails = this.getKnownFeatureFlagDetails();\n this._logger.info('Cached feature flags: ', JSON.stringify(currentFlagDetails));\n const filteredFlags = {};\n for(const key in res.flags)if (!res.flags[key].failed) filteredFlags[key] = res.flags[key];\n newFeatureFlagDetails = {\n ...res,\n flags: {\n ...currentFlagDetails?.flags,\n ...filteredFlags\n }\n };\n }\n this.cacheSessionReplay('flags', res);\n this.setKnownFeatureFlagDetails({\n flags: newFeatureFlagDetails.flags,\n requestId: res.requestId,\n evaluatedAt: res.evaluatedAt,\n errorsWhileComputingFlags: res.errorsWhileComputingFlags,\n quotaLimited: res.quotaLimited,\n minimalFlagCalledEvents: true === res.minimalFlagCalledEvents\n });\n this.setPersistedProperty(PostHogPersistedProperty.FlagsEndpointWasHit, true);\n this.maybeNotifyRemoteConfig(triggerOnRemoteConfig, res);\n }\n return res;\n }).finally(()=>{\n this._flagsResponsePromise = void 0;\n const pendingRequest = this._pendingFlagsRequest;\n if (pendingRequest) {\n this._pendingFlagsRequest = void 0;\n this._logger.info('Executing pending feature flags reload.');\n this.flagsAsync({\n sendAnonDistinctId: pendingRequest.sendAnonDistinctId,\n fetchConfig: pendingRequest.fetchConfig,\n triggerOnRemoteConfig: pendingRequest.triggerOnRemoteConfig\n }).then(pendingRequest.resolve).catch(pendingRequest.reject);\n }\n });\n return this._flagsResponsePromise;\n }\n setKnownFeatureFlagDetails(flagsResponse) {\n this.wrap(()=>{\n this.setPersistedProperty(PostHogPersistedProperty.FeatureFlagDetails, flagsResponse);\n this._events.emit('featureflags', getFlagValuesFromFlags(flagsResponse?.flags ?? {}));\n });\n }\n getKnownFeatureFlagDetails() {\n const storedDetails = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlagDetails);\n if (!storedDetails) {\n const featureFlags = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlags);\n const featureFlagPayloads = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlagPayloads);\n if (void 0 === featureFlags && void 0 === featureFlagPayloads) return;\n return createFlagsResponseFromFlagsAndPayloads(featureFlags ?? {}, featureFlagPayloads ?? {});\n }\n return normalizeFlagsResponse(storedDetails);\n }\n getStoredFlagDetails() {\n return this.getPersistedProperty(PostHogPersistedProperty.FeatureFlagDetails);\n }\n isMinimalFlagCalledEventsEnabled() {\n return this.getStoredFlagDetails()?.minimalFlagCalledEvents === true;\n }\n getKnownFeatureFlags() {\n const featureFlagDetails = this.getKnownFeatureFlagDetails();\n if (!featureFlagDetails) return;\n return getFlagValuesFromFlags(featureFlagDetails.flags);\n }\n getBootstrappedFeatureFlagDetails() {\n const details = this.getPersistedProperty(PostHogPersistedProperty.BootstrapFeatureFlagDetails);\n if (!details) return;\n return details;\n }\n setBootstrappedFeatureFlagDetails(details) {\n this.setPersistedProperty(PostHogPersistedProperty.BootstrapFeatureFlagDetails, details);\n }\n getBootstrappedFeatureFlags() {\n const details = this.getBootstrappedFeatureFlagDetails();\n if (!details) return;\n return getFlagValuesFromFlags(details.flags);\n }\n getBootstrappedFeatureFlagPayloads() {\n const details = this.getBootstrappedFeatureFlagDetails();\n if (!details) return;\n return getPayloadsFromFlags(details.flags);\n }\n getFeatureFlagResult(key, options) {\n return this._getFeatureFlagResult(key, options);\n }\n getAllFeatureFlags() {\n return flagDetailsToResults(this.getFeatureFlagDetails()?.flags ?? {});\n }\n _getFeatureFlagResult(key, options = {}) {\n const storedDetails = this.getStoredFlagDetails();\n const details = this.getFeatureFlagDetails();\n const isQuotaLimited = storedDetails?.quotaLimited?.includes(QuotaLimitedFeature.FeatureFlags);\n const featureFlag = details?.flags[key];\n const flagValue = getFeatureFlagValue(featureFlag);\n const sendEvent = (options.sendEvent ?? this.sendFeatureFlagEvent) && !this.flagCallReported[key]?.has(flagValue);\n if (sendEvent) {\n const errors = [];\n if (storedDetails?.requestError) {\n const { type, statusCode } = storedDetails.requestError;\n if ('timeout' === type) errors.push(FeatureFlagError.TIMEOUT);\n else if ('api_error' === type && void 0 !== statusCode) errors.push(FeatureFlagError.apiError(statusCode));\n else if ('connection_error' === type) errors.push(FeatureFlagError.CONNECTION_ERROR);\n else errors.push(FeatureFlagError.UNKNOWN_ERROR);\n } else if (storedDetails) {\n if (storedDetails.errorsWhileComputingFlags) errors.push(FeatureFlagError.ERRORS_WHILE_COMPUTING);\n if (isQuotaLimited) errors.push(FeatureFlagError.QUOTA_LIMITED);\n else if (void 0 === flagValue && !featureFlag) errors.push(FeatureFlagError.FLAG_MISSING);\n }\n const bootstrappedResponse = this.getBootstrappedFeatureFlags()?.[key];\n const bootstrappedPayload = this.getBootstrappedFeatureFlagPayloads()?.[key];\n const featureFlagError = errors.length > 0 ? errors.join(',') : void 0;\n this.flagCallReported[key] = this.flagCallReported[key] ?? new Set();\n this.flagCallReported[key].add(flagValue);\n const properties = {\n $feature_flag: key,\n $feature_flag_response: flagValue,\n ...maybeAdd('$feature_flag_id', featureFlag?.metadata?.id),\n ...maybeAdd('$feature_flag_version', featureFlag?.metadata?.version),\n ...maybeAdd('$feature_flag_reason', featureFlag?.reason?.description ?? featureFlag?.reason?.code),\n ...maybeAdd('$feature_flag_bootstrapped_response', bootstrappedResponse),\n ...maybeAdd('$feature_flag_bootstrapped_payload', bootstrappedPayload),\n $used_bootstrap_value: !this.getPersistedProperty(PostHogPersistedProperty.FlagsEndpointWasHit),\n ...maybeAdd('$feature_flag_request_id', details?.requestId),\n ...maybeAdd('$feature_flag_evaluated_at', details?.evaluatedAt),\n ...maybeAdd('$feature_flag_error', featureFlagError),\n ...maybeAdd('$feature_flag_has_experiment', featureFlag?.metadata?.has_experiment)\n };\n this.capture('$feature_flag_called', properties);\n }\n if (void 0 === flagValue) switch(options.missingFlagBehavior){\n case 'getFeatureFlagPayload':\n return details ? {\n key,\n enabled: false,\n payload: null\n } : void 0;\n case 'getFeatureFlag':\n return details && Object.keys(details.flags).length ? {\n key,\n enabled: false,\n payload: null\n } : void 0;\n case void 0:\n return;\n }\n const rawPayload = featureFlag?.metadata?.payload;\n const payload = void 0 !== rawPayload ? parsePayload(rawPayload) : null;\n return {\n key,\n enabled: getEnabledFromValue(flagValue),\n variant: getVariantFromValue(flagValue),\n payload\n };\n }\n getFeatureFlag(key, options) {\n const result = this._getFeatureFlagResult(key, {\n missingFlagBehavior: 'getFeatureFlag',\n sendEvent: options?.sendEvent\n });\n return result?.variant ?? result?.enabled;\n }\n getFeatureFlagPayload(key) {\n const result = this._getFeatureFlagResult(key, {\n missingFlagBehavior: 'getFeatureFlagPayload',\n sendEvent: false\n });\n return result?.payload;\n }\n getFeatureFlagPayloads() {\n return this.getFeatureFlagDetails()?.featureFlagPayloads;\n }\n getFeatureFlags() {\n return this.getFeatureFlagDetails()?.featureFlags;\n }\n getFeatureFlagDetails() {\n let details = this.getKnownFeatureFlagDetails();\n const overriddenFlags = this.getPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags);\n if (!overriddenFlags) return details;\n details = details ?? {\n featureFlags: {},\n featureFlagPayloads: {},\n flags: {}\n };\n const flags = {\n ...details.flags ?? {}\n };\n for(const key in overriddenFlags)if (overriddenFlags[key]) flags[key] = updateFlagValue(flags[key], overriddenFlags[key]);\n else delete flags[key];\n const result = {\n ...details,\n flags\n };\n return normalizeFlagsResponse(result);\n }\n getFeatureFlagsAndPayloads() {\n const flags = this.getFeatureFlags();\n const payloads = this.getFeatureFlagPayloads();\n return {\n flags,\n payloads\n };\n }\n isFeatureEnabled(key, options) {\n if (options?.defaultValue === void 0) {\n const response = this.getFeatureFlag(key, options);\n return void 0 === response ? void 0 : !!response;\n }\n const result = this._getFeatureFlagResult(key, {\n sendEvent: options.sendEvent\n });\n const value = result?.variant ?? result?.enabled;\n return void 0 === value ? options.defaultValue : !!value;\n }\n reloadFeatureFlags(options) {\n if (this.disableRemoteFeatureFlags && !this.disabled) return void this._initPromise.then(()=>options?.cb?.(void 0, this.getFeatureFlags()));\n this.flagsAsync({\n sendAnonDistinctId: true\n }).then((res)=>{\n options?.cb?.(void 0, res?.featureFlags);\n }).catch((e)=>{\n options?.cb?.(e, void 0);\n if (!options?.cb) this._logger.info('Error reloading feature flags', e);\n });\n }\n async reloadRemoteConfigAsync() {\n return await this.remoteConfigAsync();\n }\n async reloadFeatureFlagsAsync(sendAnonDistinctId) {\n if (this.disableRemoteFeatureFlags && !this.disabled) {\n await this._initPromise;\n return this.getFeatureFlags();\n }\n return (await this.flagsAsync({\n sendAnonDistinctId: sendAnonDistinctId\n }))?.featureFlags;\n }\n onFeatureFlags(cb) {\n return this.on('featureflags', async ()=>{\n const flags = this.getFeatureFlags();\n if (flags) cb(flags);\n });\n }\n onFeatureFlag(key, cb) {\n return this.on('featureflags', async ()=>{\n const flagResponse = this.getFeatureFlag(key);\n if (void 0 !== flagResponse) cb(flagResponse);\n });\n }\n async overrideFeatureFlag(flags) {\n this.wrap(()=>{\n if (null === flags) return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, null);\n return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, flags);\n });\n }\n updateFlags(flags, payloads, options) {\n this.wrap(()=>{\n const existingDetails = options?.merge ? this.getKnownFeatureFlagDetails()?.flags : void 0;\n const existingFlags = existingDetails ? getFlagValuesFromFlags(existingDetails) : {};\n const existingPayloads = {};\n for(const key in existingDetails){\n const storedPayload = existingDetails[key].metadata?.payload;\n if (void 0 !== storedPayload) existingPayloads[key] = parsePayload(storedPayload);\n }\n const finalFlags = {\n ...existingFlags,\n ...flags\n };\n const finalPayloads = {\n ...existingPayloads,\n ...payloads ?? {}\n };\n const flagDetails = {};\n for (const [key, value] of Object.entries(finalFlags)){\n const payload = finalPayloads[key];\n let serializedPayload;\n if (void 0 !== payload) try {\n serializedPayload = JSON.stringify(payload);\n } catch (e) {\n this._logger.error(`updateFlags: could not serialize the payload for flag \"${key}\", dropping it.`, e);\n }\n flagDetails[key] = {\n key,\n enabled: getEnabledFromValue(value),\n variant: getVariantFromValue(value),\n reason: void 0,\n metadata: {\n id: void 0,\n version: void 0,\n description: void 0,\n payload: serializedPayload\n }\n };\n }\n this.setKnownFeatureFlagDetails({\n flags: flagDetails\n });\n });\n }\n captureException(error, additionalProperties, hint) {\n try {\n const exceptionProperties = this.getErrorPropertiesBuilder().buildFromUnknown(error, hint);\n this.capture('$exception', {\n ...exceptionProperties,\n ...additionalProperties\n }, {\n _originatedFromCaptureException: true\n });\n } catch (e) {\n this._logger.error('Error while capturing $exception:', e);\n }\n }\n captureTraceFeedback(traceId, userFeedback) {\n this.capture('$ai_feedback', {\n $ai_feedback_text: userFeedback,\n $ai_trace_id: String(traceId)\n });\n }\n captureTraceMetric(traceId, metricName, metricValue) {\n this.capture('$ai_metric', {\n $ai_metric_name: metricName,\n $ai_metric_value: String(metricValue),\n $ai_trace_id: String(traceId)\n });\n }\n _isIdentified() {\n const personMode = this.getPersistedProperty(PostHogPersistedProperty.PersonMode);\n if ('identified' === personMode) return true;\n if (void 0 === personMode) {\n const distinctId = this.getPersistedProperty(PostHogPersistedProperty.DistinctId);\n const anonymousId = this.getPersistedProperty(PostHogPersistedProperty.AnonymousId);\n if (distinctId && anonymousId && distinctId !== anonymousId) return true;\n }\n return false;\n }\n _getGroups() {\n return this.props.$groups || {};\n }\n _hasPersonProcessing() {\n if ('always' === this._personProfiles) return true;\n if ('never' === this._personProfiles) return false;\n const isIdentified = this._isIdentified();\n const hasGroups = Object.keys(this._getGroups()).length > 0;\n const personProcessingEnabled = true === this.getPersistedProperty(PostHogPersistedProperty.EnablePersonProcessing);\n return isIdentified || hasGroups || personProcessingEnabled;\n }\n _requirePersonProcessing(functionName) {\n if ('never' === this._personProfiles) {\n this._logger.error(`${functionName} was called, but personProfiles is set to \"never\". This call will be ignored.`);\n return false;\n }\n this.setPersistedProperty(PostHogPersistedProperty.EnablePersonProcessing, true);\n return true;\n }\n createPersonProfile() {\n if (this._hasPersonProcessing()) return;\n if (!this._requirePersonProcessing('posthog.createPersonProfile')) return;\n this.capture('$set', {\n $set: {},\n $set_once: {}\n });\n }\n setPersonProperties(userPropertiesToSet, userPropertiesToSetOnce, reloadFeatureFlags = true) {\n this.wrap(()=>{\n const isSetEmpty = isNullish(userPropertiesToSet) || isEmptyObject(userPropertiesToSet);\n const isSetOnceEmpty = isNullish(userPropertiesToSetOnce) || isEmptyObject(userPropertiesToSetOnce);\n if (isSetEmpty && isSetOnceEmpty) return;\n if (!this._requirePersonProcessing('posthog.setPersonProperties')) return;\n const hash = getPersonPropertiesHash(this.getDistinctId(), userPropertiesToSet, userPropertiesToSetOnce);\n if (this._cachedPersonProperties === hash) return void this._logger.info('A duplicate setPersonProperties call was made with the same properties. It has been ignored.');\n this.setPersonPropertiesForFlags({\n $set: userPropertiesToSet || {},\n $set_once: userPropertiesToSetOnce || {}\n }, reloadFeatureFlags);\n this.capture('$set', {\n $set: userPropertiesToSet || {},\n $set_once: userPropertiesToSetOnce || {}\n });\n this._cachedPersonProperties = hash;\n });\n }\n unsetPersonProperties(propertyNames, reloadFeatureFlags = true) {\n this.wrap(()=>{\n const names = (isArray(propertyNames) ? propertyNames : [\n propertyNames\n ]).filter((name)=>isString(name) && name.length > 0);\n if (0 === names.length) return;\n if (!this._requirePersonProcessing('posthog.unsetPersonProperties')) return;\n const existingProperties = this.getPersistedProperty(PostHogPersistedProperty.PersonProperties) || {};\n const nextProperties = {\n ...existingProperties\n };\n for (const name of names)delete nextProperties[name];\n this.setPersistedProperty(PostHogPersistedProperty.PersonProperties, nextProperties);\n if (reloadFeatureFlags) this.reloadFeatureFlags();\n this.capture('$set', {\n $unset: names\n });\n this._cachedPersonProperties = null;\n });\n }\n processBeforeEnqueue(message) {\n if (!this._beforeSend) return message;\n const timestamp = message.timestamp;\n const props = message.properties || {};\n const captureEvent = {\n uuid: message.uuid,\n event: message.event,\n properties: props,\n $set: props.$set,\n $set_once: props.$set_once,\n timestamp: 'string' == typeof timestamp ? new Date(timestamp) : timestamp\n };\n const result = this._runBeforeSend(captureEvent);\n if (!result) return null;\n const resultProps = {\n ...result.properties ?? props\n };\n if (void 0 !== result.$set) resultProps.$set = result.$set;\n else delete resultProps.$set;\n if (void 0 !== result.$set_once) resultProps.$set_once = result.$set_once;\n else delete resultProps.$set_once;\n return {\n ...message,\n uuid: getEventUuid(result.uuid ?? message.uuid, uuidv7),\n event: result.event,\n properties: resultProps,\n timestamp: result.timestamp\n };\n }\n _runBeforeSend(captureEvent) {\n const beforeSend = this._beforeSend;\n if (!beforeSend) return captureEvent;\n const fns = Array.isArray(beforeSend) ? beforeSend : [\n beforeSend\n ];\n let result = captureEvent;\n for (const fn of fns)try {\n result = fn(result);\n if (!result) {\n this._logger.info(`Event '${captureEvent.event}' was rejected in before_send function`);\n return null;\n }\n } catch (e) {\n this._logger.error(`Error in before_send function for event '${captureEvent.event}':`, e);\n }\n return result;\n }\n}\nexport { PostHogCore };\n","import { isFunction } from \"./utils/type-utils.mjs\";\nconst DISTINCT_ID_HEADER = 'X-POSTHOG-DISTINCT-ID';\nconst SESSION_ID_HEADER = 'X-POSTHOG-SESSION-ID';\nconst PATCH_MARKER = '__posthog_tracing_headers_patched__';\nconst parseHostname = (url)=>{\n try {\n return new URL(url).hostname;\n } catch {\n return;\n }\n};\nconst shouldAddHeaders = (url, hostnames)=>{\n const hostname = parseHostname(url);\n if (!hostname) return false;\n return hostnames.includes(hostname);\n};\nconst patchFetchForTracingHeaders = (client, hostnames)=>{\n const globalAny = globalThis;\n const currentFetch = globalAny.fetch;\n if (!isFunction(currentFetch)) return ()=>{};\n const originalFetch = currentFetch[PATCH_MARKER]?.original ?? currentFetch;\n const wrappedFetch = async function(input, init) {\n try {\n const urlString = 'string' == typeof input ? input : input instanceof URL ? input.toString() : input instanceof Request ? input.url : void 0;\n if (urlString && shouldAddHeaders(urlString, hostnames)) {\n const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : void 0));\n const distinctId = client.getDistinctId();\n const sessionId = client.getSessionId();\n if (distinctId) headers.set(DISTINCT_ID_HEADER, distinctId);\n if (sessionId) headers.set(SESSION_ID_HEADER, sessionId);\n const initWithHeaders = {\n ...init ?? {},\n headers\n };\n return originalFetch.call(globalAny, input, initWithHeaders);\n }\n } catch {}\n return originalFetch.call(globalAny, input, init);\n };\n Object.defineProperty(wrappedFetch, PATCH_MARKER, {\n value: {\n original: originalFetch\n },\n enumerable: false\n });\n globalAny.fetch = wrappedFetch;\n return ()=>{\n if (globalAny.fetch === wrappedFetch) globalAny.fetch = originalFetch;\n };\n};\nexport { patchFetchForTracingHeaders };\n","import { flagDetailsToResults, getEnabledFromValue, getFeatureFlagValue, getVariantFromValue, minimizeFlagCalledEventProperties, parsePayload } from \"./featureFlagUtils.mjs\";\nimport { gzipCompress, isGzipData, isGzipRequest, isGzipSupported, isNativeAsyncGzipError, isNativeAsyncGzipReadError } from \"./gzip.mjs\";\nimport { buildOtlpLogRecord, buildOtlpLogsPayload, buildResourceAttributes, getOtlpSeverityNumber, getOtlpSeverityText, toOtlpAnyValue, toOtlpKeyValueList } from \"./logs/logs-utils.mjs\";\nimport { PostHogLogs } from \"./logs/index.mjs\";\nimport { DEFAULT_HISTOGRAM_BOUNDS, PostHogMetrics, buildMetricsResourceAttributes, buildOtlpMetricsPayload, resolveMetricsConfig } from \"./metrics/index.mjs\";\nimport { uuidv7 } from \"./vendor/uuidv7.mjs\";\nimport { getLengthFromRules, getRequirementsHint, getValidationError } from \"./surveys/validation.mjs\";\nexport * from \"./utils/index.mjs\";\nexport * from \"./cookie.mjs\";\nexport * from \"./posthog-core.mjs\";\nexport * from \"./posthog-core-stateless.mjs\";\nexport * from \"./tracing-headers.mjs\";\nexport * from \"./types.mjs\";\nimport * as __WEBPACK_EXTERNAL_MODULE__error_tracking_index_mjs_b3406d6f__ from \"./error-tracking/index.mjs\";\nexport { DEFAULT_HISTOGRAM_BOUNDS, __WEBPACK_EXTERNAL_MODULE__error_tracking_index_mjs_b3406d6f__ as ErrorTracking, PostHogLogs, PostHogMetrics, buildMetricsResourceAttributes, buildOtlpLogRecord, buildOtlpLogsPayload, buildOtlpMetricsPayload, buildResourceAttributes, flagDetailsToResults, getEnabledFromValue, getFeatureFlagValue, getLengthFromRules, getOtlpSeverityNumber, getOtlpSeverityText, getRequirementsHint, getValidationError, getVariantFromValue, gzipCompress, isGzipData, isGzipRequest, isGzipSupported, isNativeAsyncGzipError, isNativeAsyncGzipReadError, minimizeFlagCalledEventProperties, parsePayload, resolveMetricsConfig, toOtlpAnyValue, toOtlpKeyValueList, uuidv7 };\n","import { ErrorTracking } from \"@posthog/core\";\nimport { createReadStream } from \"node:fs\";\nimport { createInterface } from \"node:readline\";\nconst LRU_FILE_CONTENTS_CACHE = new ErrorTracking.ReduceableCache(25);\nconst LRU_FILE_CONTENTS_FS_READ_FAILED = new ErrorTracking.ReduceableCache(20);\nconst DEFAULT_LINES_OF_CONTEXT = 7;\nconst MAX_CONTEXTLINES_COLNO = 1000;\nconst MAX_CONTEXTLINES_LINENO = 10000;\nasync function addSourceContext(frames) {\n const filesToLines = {};\n for(let i = frames.length - 1; i >= 0; i--){\n const frame = frames[i];\n const filename = frame?.filename;\n if (!frame || 'string' != typeof filename || 'number' != typeof frame.lineno || shouldSkipContextLinesForFile(filename) || shouldSkipContextLinesForFrame(frame)) continue;\n const filesToLinesOutput = filesToLines[filename];\n if (!filesToLinesOutput) filesToLines[filename] = [];\n filesToLines[filename].push(frame.lineno);\n }\n const files = Object.keys(filesToLines);\n if (0 == files.length) return frames;\n const readlinePromises = [];\n for (const file of files){\n if (LRU_FILE_CONTENTS_FS_READ_FAILED.get(file)) continue;\n const filesToLineRanges = filesToLines[file];\n if (!filesToLineRanges) continue;\n filesToLineRanges.sort((a, b)=>a - b);\n const ranges = makeLineReaderRanges(filesToLineRanges);\n if (ranges.every((r)=>rangeExistsInContentCache(file, r))) continue;\n const cache = emplace(LRU_FILE_CONTENTS_CACHE, file, {});\n readlinePromises.push(getContextLinesFromFile(file, ranges, cache));\n }\n await Promise.all(readlinePromises).catch(()=>{});\n if (frames && frames.length > 0) addSourceContextToFrames(frames, LRU_FILE_CONTENTS_CACHE);\n LRU_FILE_CONTENTS_CACHE.reduce();\n return frames;\n}\nfunction getContextLinesFromFile(path, ranges, output) {\n return new Promise((resolve)=>{\n const stream = createReadStream(path);\n const lineReaded = createInterface({\n input: stream\n });\n function destroyStreamAndResolve() {\n stream.destroy();\n resolve();\n }\n let lineNumber = 0;\n let currentRangeIndex = 0;\n const range = ranges[currentRangeIndex];\n if (void 0 === range) return void destroyStreamAndResolve();\n let rangeStart = range[0];\n let rangeEnd = range[1];\n function onStreamError() {\n LRU_FILE_CONTENTS_FS_READ_FAILED.set(path, 1);\n lineReaded.close();\n lineReaded.removeAllListeners();\n destroyStreamAndResolve();\n }\n stream.on('error', onStreamError);\n lineReaded.on('error', onStreamError);\n lineReaded.on('close', destroyStreamAndResolve);\n lineReaded.on('line', (line)=>{\n lineNumber++;\n if (lineNumber < rangeStart) return;\n output[lineNumber] = snipLine(line, 0);\n if (lineNumber >= rangeEnd) {\n if (currentRangeIndex === ranges.length - 1) {\n lineReaded.close();\n lineReaded.removeAllListeners();\n return;\n }\n currentRangeIndex++;\n const range = ranges[currentRangeIndex];\n if (void 0 === range) {\n lineReaded.close();\n lineReaded.removeAllListeners();\n return;\n }\n rangeStart = range[0];\n rangeEnd = range[1];\n }\n });\n });\n}\nfunction addSourceContextToFrames(frames, cache) {\n for (const frame of frames)if (frame.filename && void 0 === frame.context_line && 'number' == typeof frame.lineno) {\n const contents = cache.get(frame.filename);\n if (void 0 === contents) continue;\n addContextToFrame(frame.lineno, frame, contents);\n }\n}\nfunction addContextToFrame(lineno, frame, contents) {\n if (void 0 === frame.lineno || void 0 === contents) return;\n frame.pre_context = [];\n for(let i = makeRangeStart(lineno); i < lineno; i++){\n const line = contents[i];\n if (void 0 === line) return void clearLineContext(frame);\n frame.pre_context.push(line);\n }\n if (void 0 === contents[lineno]) return void clearLineContext(frame);\n frame.context_line = contents[lineno];\n const end = makeRangeEnd(lineno);\n frame.post_context = [];\n for(let i = lineno + 1; i <= end; i++){\n const line = contents[i];\n if (void 0 === line) break;\n frame.post_context.push(line);\n }\n}\nfunction clearLineContext(frame) {\n delete frame.pre_context;\n delete frame.context_line;\n delete frame.post_context;\n}\nfunction shouldSkipContextLinesForFile(path) {\n return path.startsWith('node:') || path.endsWith('.min.js') || path.endsWith('.min.cjs') || path.endsWith('.min.mjs') || path.startsWith('data:');\n}\nfunction shouldSkipContextLinesForFrame(frame) {\n if (void 0 !== frame.lineno && frame.lineno > MAX_CONTEXTLINES_LINENO) return true;\n if (void 0 !== frame.colno && frame.colno > MAX_CONTEXTLINES_COLNO) return true;\n return false;\n}\nfunction rangeExistsInContentCache(file, range) {\n const contents = LRU_FILE_CONTENTS_CACHE.get(file);\n if (void 0 === contents) return false;\n for(let i = range[0]; i <= range[1]; i++)if (void 0 === contents[i]) return false;\n return true;\n}\nfunction makeLineReaderRanges(lines) {\n if (!lines.length) return [];\n let i = 0;\n const line = lines[0];\n if ('number' != typeof line) return [];\n let current = makeContextRange(line);\n const out = [];\n while(true){\n if (i === lines.length - 1) {\n out.push(current);\n break;\n }\n const next = lines[i + 1];\n if ('number' != typeof next) break;\n if (next <= current[1]) current[1] = next + DEFAULT_LINES_OF_CONTEXT;\n else {\n out.push(current);\n current = makeContextRange(next);\n }\n i++;\n }\n return out;\n}\nfunction makeContextRange(line) {\n return [\n makeRangeStart(line),\n makeRangeEnd(line)\n ];\n}\nfunction makeRangeStart(line) {\n return Math.max(1, line - DEFAULT_LINES_OF_CONTEXT);\n}\nfunction makeRangeEnd(line) {\n return line + DEFAULT_LINES_OF_CONTEXT;\n}\nfunction emplace(map, key, contents) {\n const value = map.get(key);\n if (void 0 === value) {\n map.set(key, contents);\n return contents;\n }\n return value;\n}\nfunction snipLine(line, colno) {\n let newLine = line;\n const lineLength = newLine.length;\n if (lineLength <= 150) return newLine;\n if (colno > lineLength) colno = lineLength;\n let start = Math.max(colno - 60, 0);\n if (start < 5) start = 0;\n let end = Math.min(start + 140, lineLength);\n if (end > lineLength - 5) end = lineLength;\n if (end === lineLength) start = Math.max(end - 140, 0);\n newLine = newLine.slice(start, end);\n if (start > 0) newLine = `...${newLine}`;\n if (end < lineLength) newLine += '...';\n return newLine;\n}\nexport { MAX_CONTEXTLINES_COLNO, MAX_CONTEXTLINES_LINENO, addSourceContext };\n","import { isAbsolute, relative, sep } from \"path\";\nfunction createRelativePathModifier(basePath = process.cwd()) {\n const isWindows = '\\\\' === sep;\n const toUnix = (p)=>isWindows ? p.replace(/\\\\/g, '/') : p;\n const normalizedBase = toUnix(basePath);\n return async (frames)=>{\n for (const frame of frames)if (!(!frame.filename || frame.filename.startsWith('node:') || frame.filename.startsWith('data:'))) {\n if (isAbsolute(frame.filename)) frame.filename = toUnix(relative(normalizedBase, toUnix(frame.filename)));\n }\n return frames;\n };\n}\nexport { createRelativePathModifier };\n","const version = '5.46.0';\nexport { version };\n","const FeatureFlagError = {\n ERRORS_WHILE_COMPUTING: 'errors_while_computing_flags',\n FLAG_MISSING: 'flag_missing',\n QUOTA_LIMITED: 'quota_limited',\n UNKNOWN_ERROR: 'unknown_error'\n};\nexport { FeatureFlagError };\n","import { FeatureFlagError } from \"./types.mjs\";\nclass FeatureFlagEvaluations {\n constructor(init){\n this._host = init.host;\n this._distinctId = init.distinctId;\n this._groups = init.groups;\n this._disableGeoip = init.disableGeoip;\n this._flags = init.flags;\n this._requestId = init.requestId;\n this._evaluatedAt = init.evaluatedAt;\n this._flagDefinitionsLoadedAt = init.flagDefinitionsLoadedAt;\n this._errorsWhileComputing = init.errorsWhileComputing ?? false;\n this._quotaLimited = init.quotaLimited ?? false;\n this._accessed = init.accessed ?? new Set();\n this._isSlice = init.isSlice ?? false;\n }\n isEnabled(key) {\n const flag = this._flags[key];\n this._recordAccess(key);\n return flag?.enabled ?? false;\n }\n getFlag(key) {\n const flag = this._flags[key];\n this._recordAccess(key);\n if (!flag) return;\n if (!flag.enabled) return false;\n return flag.variant ?? true;\n }\n getFlagPayload(key) {\n return this._flags[key]?.payload;\n }\n onlyAccessed() {\n const filtered = {};\n for (const key of this._accessed){\n const flag = this._flags[key];\n if (flag) filtered[key] = flag;\n }\n return this._cloneWith(filtered);\n }\n only(keys) {\n const filtered = {};\n const missing = [];\n for (const key of keys){\n const flag = this._flags[key];\n if (flag) filtered[key] = flag;\n else missing.push(key);\n }\n if (missing.length > 0) this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${missing.join(', ')}`);\n return this._cloneWith(filtered);\n }\n get keys() {\n return Object.keys(this._flags);\n }\n _getEventProperties() {\n const properties = {};\n const activeFlags = [];\n for (const [key, flag] of Object.entries(this._flags)){\n const value = false === flag.enabled ? false : flag.variant ?? true;\n properties[`$feature/${key}`] = value;\n if (flag.enabled) activeFlags.push(key);\n }\n if (activeFlags.length > 0) {\n activeFlags.sort();\n properties['$active_feature_flags'] = activeFlags;\n }\n return properties;\n }\n _cloneWith(flags) {\n return new FeatureFlagEvaluations({\n host: this._host,\n distinctId: this._distinctId,\n groups: this._groups,\n disableGeoip: this._disableGeoip,\n flags,\n requestId: this._requestId,\n evaluatedAt: this._evaluatedAt,\n flagDefinitionsLoadedAt: this._flagDefinitionsLoadedAt,\n errorsWhileComputing: this._errorsWhileComputing,\n quotaLimited: this._quotaLimited,\n accessed: new Set(this._accessed),\n isSlice: true\n });\n }\n _recordAccess(key) {\n this._accessed.add(key);\n if ('' === this._distinctId) return;\n if (this._isSlice && !(key in this._flags)) return;\n const flag = this._flags[key];\n const response = void 0 === flag ? void 0 : false === flag.enabled ? false : flag.variant ?? true;\n const properties = {\n $feature_flag: key,\n $feature_flag_response: response,\n $feature_flag_id: flag?.id,\n $feature_flag_version: flag?.version,\n $feature_flag_reason: flag?.reason,\n locally_evaluated: flag?.locallyEvaluated ?? false,\n [`$feature/${key}`]: response,\n $feature_flag_request_id: this._requestId,\n $feature_flag_evaluated_at: flag?.locallyEvaluated ? Date.now() : this._evaluatedAt\n };\n if (flag?.hasExperiment !== void 0) properties.$feature_flag_has_experiment = flag.hasExperiment;\n if (flag?.locallyEvaluated && void 0 !== this._flagDefinitionsLoadedAt) properties.$feature_flag_definitions_loaded_at = this._flagDefinitionsLoadedAt;\n const errors = [];\n if (this._errorsWhileComputing) errors.push(FeatureFlagError.ERRORS_WHILE_COMPUTING);\n if (this._quotaLimited) errors.push(FeatureFlagError.QUOTA_LIMITED);\n if (void 0 === flag) errors.push(FeatureFlagError.FLAG_MISSING);\n if (errors.length > 0) properties.$feature_flag_error = errors.join(',');\n this._host.captureFlagCalledEventIfNeeded({\n distinctId: this._distinctId,\n key,\n response,\n groups: this._groups,\n disableGeoip: this._disableGeoip,\n properties\n });\n }\n}\nexport { FeatureFlagEvaluations };\n","async function hashSHA1(text) {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) throw new Error('SubtleCrypto API not available');\n const hashBuffer = await subtle.digest('SHA-1', new TextEncoder().encode(text));\n const hashArray = Array.from(new Uint8Array(hashBuffer));\n return hashArray.map((byte)=>byte.toString(16).padStart(2, '0')).join('');\n}\nexport { hashSHA1 };\n","import { safeSetTimeout } from \"@posthog/core\";\nimport { hashSHA1 } from \"./crypto.mjs\";\nconst SIXTY_SECONDS = 60000;\nconst LONG_SCALE = 0xfffffffffffffff;\nconst NULL_VALUES_ALLOWED_OPERATORS = [\n 'is_not',\n 'is_set'\n];\nclass ClientError extends Error {\n constructor(message){\n super();\n Error.captureStackTrace(this, this.constructor);\n this.name = 'ClientError';\n this.message = message;\n Object.setPrototypeOf(this, ClientError.prototype);\n }\n}\nfunction setCustomErrorPrototype(error, constructor) {\n error.name = constructor.name;\n Error.captureStackTrace(error, constructor);\n Object.setPrototypeOf(error, constructor.prototype);\n}\nclass InconclusiveMatchError extends Error {\n constructor(message){\n super(message);\n setCustomErrorPrototype(this, InconclusiveMatchError);\n }\n}\nclass RequiresServerEvaluation extends Error {\n constructor(message){\n super(message);\n setCustomErrorPrototype(this, RequiresServerEvaluation);\n }\n}\nclass FeatureFlagsPoller {\n constructor({ pollingInterval, personalApiKey, projectApiKey, timeout, host, customHeaders, ...options }){\n this.debugMode = false;\n this.shouldBeginExponentialBackoff = false;\n this.backOffCount = 0;\n this.pollingInterval = pollingInterval;\n this.personalApiKey = personalApiKey;\n this.featureFlags = [];\n this.featureFlagsByKey = {};\n this.groupTypeMapping = {};\n this.cohorts = {};\n this.loadedSuccessfullyOnce = false;\n this.timeout = timeout;\n this.projectApiKey = projectApiKey;\n this.host = host;\n this.poller = void 0;\n this.fetch = options.fetch || fetch;\n this.onError = options.onError;\n this.customHeaders = customHeaders;\n this.onLoad = options.onLoad;\n this.onMinimalFlagCalledEvents = options.onMinimalFlagCalledEvents;\n this.cacheProvider = options.cacheProvider;\n this.strictLocalEvaluation = options.strictLocalEvaluation ?? false;\n this.loadFeatureFlags();\n }\n debug(enabled = true) {\n this.debugMode = enabled;\n }\n logMsgIfDebug(fn) {\n if (this.debugMode) fn();\n }\n createEvaluationContext(distinctId, groups = {}, personProperties = {}, groupProperties = {}, evaluationCache = {}) {\n return {\n distinctId,\n groups,\n personProperties,\n groupProperties,\n evaluationCache\n };\n }\n async getFeatureFlag(key, distinctId, groups = {}, personProperties = {}, groupProperties = {}) {\n await this.loadFeatureFlags();\n let response;\n let featureFlag;\n if (!this.loadedSuccessfullyOnce) return response;\n featureFlag = this.featureFlagsByKey[key];\n if (void 0 !== featureFlag) {\n const evaluationContext = this.createEvaluationContext(distinctId, groups, personProperties, groupProperties);\n try {\n const result = await this.computeFlagAndPayloadLocally(featureFlag, evaluationContext);\n response = result.value;\n this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${key} -> ${response}`));\n } catch (e) {\n if (e instanceof RequiresServerEvaluation || e instanceof InconclusiveMatchError) this.logMsgIfDebug(()=>console.debug(`${e.name} when computing flag locally: ${key}: ${e.message}`));\n else if (e instanceof Error) this.onError?.(new Error(`Error computing flag locally: ${key}: ${e}`));\n }\n }\n return response;\n }\n async getAllFlagsAndPayloads(evaluationContext, flagKeysToExplicitlyEvaluate) {\n await this.loadFeatureFlags();\n const response = {};\n const payloads = {};\n let fallbackToFlags = 0 == this.featureFlags.length;\n const flagsToEvaluate = flagKeysToExplicitlyEvaluate ? flagKeysToExplicitlyEvaluate.map((key)=>this.featureFlagsByKey[key]).filter(Boolean) : this.featureFlags;\n const sharedEvaluationContext = {\n ...evaluationContext,\n evaluationCache: evaluationContext.evaluationCache ?? {}\n };\n await Promise.all(flagsToEvaluate.map(async (flag)=>{\n try {\n const { value: matchValue, payload: matchPayload } = await this.computeFlagAndPayloadLocally(flag, sharedEvaluationContext);\n response[flag.key] = matchValue;\n if (matchPayload) payloads[flag.key] = matchPayload;\n } catch (e) {\n if (e instanceof RequiresServerEvaluation || e instanceof InconclusiveMatchError) this.logMsgIfDebug(()=>console.debug(`${e.name} when computing flag locally: ${flag.key}: ${e.message}`));\n else if (e instanceof Error) this.onError?.(new Error(`Error computing flag locally: ${flag.key}: ${e}`));\n fallbackToFlags = true;\n }\n }));\n return {\n response,\n payloads,\n fallbackToFlags\n };\n }\n async computeFlagAndPayloadLocally(flag, evaluationContext, options = {}) {\n const { matchValue, skipLoadCheck = false } = options;\n if (!skipLoadCheck) await this.loadFeatureFlags();\n if (!this.loadedSuccessfullyOnce) return {\n value: false,\n payload: null\n };\n let flagValue;\n flagValue = void 0 !== matchValue ? matchValue : await this.computeFlagValueLocally(flag, evaluationContext);\n const payload = this.getFeatureFlagPayload(flag.key, flagValue);\n return {\n value: flagValue,\n payload\n };\n }\n async computeFlagValueLocally(flag, evaluationContext) {\n const { distinctId, groups, personProperties, groupProperties } = evaluationContext;\n if (!flag.active) return false;\n if (flag.ensure_experience_continuity) throw new InconclusiveMatchError('Flag has experience continuity enabled');\n const flagFilters = flag.filters || {};\n const aggregation_group_type_index = flagFilters.aggregation_group_type_index;\n if (void 0 != aggregation_group_type_index) {\n const groupName = this.groupTypeMapping[String(aggregation_group_type_index)];\n if (!groupName) {\n this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${aggregation_group_type_index} for feature flag ${flag.key}`));\n throw new InconclusiveMatchError('Flag has unknown group type index');\n }\n if (!(groupName in groups)) {\n this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${flag.key} without group names passed in`));\n return false;\n }\n if ('device_id' === flag.bucketing_identifier && (personProperties?.$device_id === void 0 || personProperties?.$device_id === null || personProperties?.$device_id === '')) this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${flag.key}`));\n const focusedGroupProperties = groupProperties[groupName];\n return await this.matchFeatureFlagProperties(flag, groups[groupName], focusedGroupProperties, evaluationContext);\n }\n {\n const bucketingValue = this.getBucketingValueForFlag(flag, distinctId, personProperties);\n if (void 0 === bucketingValue) {\n this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${flag.key} without $device_id, falling back to server evaluation`));\n throw new InconclusiveMatchError(`Can't compute feature flag: ${flag.key} without $device_id`);\n }\n return await this.matchFeatureFlagProperties(flag, bucketingValue, personProperties, evaluationContext);\n }\n }\n getBucketingValueForFlag(flag, distinctId, properties) {\n if (flag.filters?.aggregation_group_type_index != void 0) return distinctId;\n if ('device_id' === flag.bucketing_identifier) {\n const deviceId = properties?.$device_id;\n if (null == deviceId || '' === deviceId) return;\n return deviceId;\n }\n return distinctId;\n }\n getFeatureFlagPayload(key, flagValue) {\n let payload = null;\n if (false !== flagValue && null != flagValue) {\n if ('boolean' == typeof flagValue) payload = this.featureFlagsByKey?.[key]?.filters?.payloads?.[flagValue.toString()] || null;\n else if ('string' == typeof flagValue) payload = this.featureFlagsByKey?.[key]?.filters?.payloads?.[flagValue] || null;\n if (null != payload) {\n if ('object' == typeof payload) return payload;\n if ('string' == typeof payload) try {\n return JSON.parse(payload);\n } catch {}\n return payload;\n }\n }\n return null;\n }\n async evaluateFlagDependency(property, properties, evaluationContext) {\n const { evaluationCache } = evaluationContext;\n const targetFlagKey = property.key;\n if (!this.featureFlagsByKey) throw new InconclusiveMatchError('Feature flags not available for dependency evaluation');\n if (!('dependency_chain' in property)) throw new InconclusiveMatchError(`Flag dependency property for '${targetFlagKey}' is missing required 'dependency_chain' field`);\n const dependencyChain = property.dependency_chain;\n if (!Array.isArray(dependencyChain)) throw new InconclusiveMatchError(`Flag dependency property for '${targetFlagKey}' has an invalid 'dependency_chain' (expected array, got ${typeof dependencyChain})`);\n if (0 === dependencyChain.length) throw new InconclusiveMatchError(`Circular dependency detected for flag '${targetFlagKey}' (empty dependency chain)`);\n for (const depFlagKey of dependencyChain){\n if (!(depFlagKey in evaluationCache)) {\n const depFlag = this.featureFlagsByKey[depFlagKey];\n if (depFlag) if (depFlag.active) try {\n const depResult = await this.computeFlagValueLocally(depFlag, evaluationContext);\n evaluationCache[depFlagKey] = depResult;\n } catch (error) {\n throw new InconclusiveMatchError(`Error evaluating flag dependency '${depFlagKey}' for flag '${targetFlagKey}': ${error}`);\n }\n else evaluationCache[depFlagKey] = false;\n else throw new InconclusiveMatchError(`Missing flag dependency '${depFlagKey}' for flag '${targetFlagKey}'`);\n }\n const cachedResult = evaluationCache[depFlagKey];\n if (null == cachedResult) throw new InconclusiveMatchError(`Dependency '${depFlagKey}' could not be evaluated`);\n }\n const targetFlagValue = evaluationCache[targetFlagKey];\n return this.flagEvaluatesToExpectedValue(property.value, targetFlagValue);\n }\n flagEvaluatesToExpectedValue(expectedValue, flagValue) {\n if ('boolean' == typeof expectedValue) return expectedValue === flagValue || 'string' == typeof flagValue && '' !== flagValue && true === expectedValue;\n if ('string' == typeof expectedValue) return flagValue === expectedValue;\n return false;\n }\n async matchFeatureFlagProperties(flag, bucketingValue, properties, evaluationContext) {\n const flagFilters = flag.filters || {};\n const flagConditions = flagFilters.groups || [];\n const flagAggregation = flagFilters.aggregation_group_type_index;\n const earlyExitEnabled = flagFilters.early_exit ?? false;\n const { groups, groupProperties } = evaluationContext;\n let isInconclusive = false;\n let result;\n for (const condition of flagConditions)try {\n const conditionAggregation = void 0 !== condition.aggregation_group_type_index ? condition.aggregation_group_type_index : flagAggregation;\n let effectiveProperties = properties;\n let effectiveBucketingValue = bucketingValue;\n if (conditionAggregation !== flagAggregation) {\n if (null != conditionAggregation) {\n const groupName = this.groupTypeMapping[String(conditionAggregation)];\n if (!groupName || !(groupName in groups)) {\n this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${flag.key}': group type index ${conditionAggregation} not available`));\n continue;\n }\n if (!(groupName in groupProperties)) {\n isInconclusive = true;\n continue;\n }\n effectiveProperties = groupProperties[groupName];\n effectiveBucketingValue = groups[groupName];\n }\n }\n const matchResult = await this.isConditionMatch(flag, effectiveBucketingValue, condition, effectiveProperties, evaluationContext);\n if ('match' === matchResult) {\n const variantOverride = condition.variant;\n const flagVariants = flagFilters.multivariate?.variants || [];\n result = variantOverride && flagVariants.some((variant)=>variant.key === variantOverride) ? variantOverride : await this.getMatchingVariant(flag, effectiveBucketingValue) || true;\n break;\n }\n if (earlyExitEnabled && 'out_of_rollout_bound' === matchResult) return false;\n } catch (e) {\n if (e instanceof RequiresServerEvaluation) throw e;\n if (e instanceof InconclusiveMatchError) isInconclusive = true;\n else throw e;\n }\n if (void 0 !== result) return result;\n if (isInconclusive) throw new InconclusiveMatchError(\"Can't determine if feature flag is enabled or not with given properties\");\n return false;\n }\n async isConditionMatch(flag, bucketingValue, condition, properties, evaluationContext) {\n const rolloutPercentage = condition.rollout_percentage;\n const warnFunction = (msg)=>{\n this.logMsgIfDebug(()=>console.warn(msg));\n };\n if ((condition.properties || []).length > 0) {\n for (const prop of condition.properties){\n const propertyType = prop.type;\n let matches = false;\n if ('cohort' === propertyType) {\n const inCohort = await matchCohort(prop, properties, this.cohorts, this.debugMode, (depProp)=>this.evaluateFlagDependency(depProp, properties, evaluationContext));\n matches = 'not_in' === prop.operator ? !inCohort : inCohort;\n } else matches = 'flag' === propertyType ? await this.evaluateFlagDependency(prop, properties, evaluationContext) : matchProperty(prop, properties, warnFunction);\n if (!matches) return 'no_match';\n }\n if (void 0 == rolloutPercentage) return 'match';\n }\n if (void 0 != rolloutPercentage && await _hash(flag.key, bucketingValue) > rolloutPercentage / 100.0) return 'out_of_rollout_bound';\n return 'match';\n }\n async getMatchingVariant(flag, bucketingValue) {\n const hashValue = await _hash(flag.key, bucketingValue, 'variant');\n const matchingVariant = this.variantLookupTable(flag).find((variant)=>hashValue >= variant.valueMin && hashValue < variant.valueMax);\n if (matchingVariant) return matchingVariant.key;\n }\n variantLookupTable(flag) {\n const lookupTable = [];\n let valueMin = 0;\n let valueMax = 0;\n const flagFilters = flag.filters || {};\n const multivariates = flagFilters.multivariate?.variants || [];\n multivariates.forEach((variant)=>{\n valueMax = valueMin + variant.rollout_percentage / 100.0;\n lookupTable.push({\n valueMin,\n valueMax,\n key: variant.key\n });\n valueMin = valueMax;\n });\n return lookupTable;\n }\n updateFlagState(flagData) {\n this.featureFlags = flagData.flags;\n this.featureFlagsByKey = flagData.flags.reduce((acc, curr)=>(acc[curr.key] = curr, acc), {});\n this.groupTypeMapping = flagData.groupTypeMapping;\n this.cohorts = flagData.cohorts;\n this.loadedSuccessfullyOnce = true;\n this.onMinimalFlagCalledEvents?.(true === flagData.minimalFlagCalledEvents);\n }\n warnAboutExperienceContinuityFlags(flags) {\n if (this.strictLocalEvaluation) return;\n const experienceContinuityFlags = flags.filter((f)=>f.ensure_experience_continuity);\n if (experienceContinuityFlags.length > 0) console.warn(`[PostHog] You are using local evaluation but ${experienceContinuityFlags.length} flag(s) have experience continuity enabled: ${experienceContinuityFlags.map((f)=>f.key).join(', ')}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`);\n }\n async loadFromCache(debugMessage) {\n if (!this.cacheProvider) return false;\n try {\n const cached = await this.cacheProvider.getFlagDefinitions();\n if (cached) {\n this.updateFlagState(cached);\n this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${debugMessage} (${cached.flags.length} flags)`));\n this.onLoad?.(this.featureFlags.length);\n this.warnAboutExperienceContinuityFlags(cached.flags);\n return true;\n }\n return false;\n } catch (err) {\n this.onError?.(new Error(`Failed to load from cache: ${err}`));\n return false;\n }\n }\n async loadFeatureFlags(forceReload = false) {\n if (this.loadedSuccessfullyOnce && !forceReload) return;\n if (!forceReload && this.nextFetchAllowedAt && Date.now() < this.nextFetchAllowedAt) return void this.logMsgIfDebug(()=>console.debug('[FEATURE FLAGS] Skipping fetch, in backoff period'));\n if (!this.loadingPromise) this.loadingPromise = this._loadFeatureFlags().catch((err)=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${err}`))).finally(()=>{\n this.loadingPromise = void 0;\n });\n return this.loadingPromise;\n }\n isLocalEvaluationReady() {\n return (this.loadedSuccessfullyOnce ?? false) && (this.featureFlags?.length ?? 0) > 0;\n }\n getFlagDefinitionsLoadedAt() {\n return this.flagDefinitionsLoadedAt;\n }\n getPollingInterval() {\n if (!this.shouldBeginExponentialBackoff) return this.pollingInterval;\n return Math.min(SIXTY_SECONDS, this.pollingInterval * 2 ** this.backOffCount);\n }\n beginBackoff() {\n this.shouldBeginExponentialBackoff = true;\n this.backOffCount += 1;\n this.nextFetchAllowedAt = Date.now() + this.getPollingInterval();\n }\n clearBackoff() {\n this.shouldBeginExponentialBackoff = false;\n this.backOffCount = 0;\n this.nextFetchAllowedAt = void 0;\n }\n async _loadFeatureFlags() {\n if (this.poller) {\n clearTimeout(this.poller);\n this.poller = void 0;\n }\n this.poller = setTimeout(()=>this.loadFeatureFlags(true), this.getPollingInterval());\n try {\n let shouldFetch = true;\n if (this.cacheProvider) try {\n shouldFetch = await this.cacheProvider.shouldFetchFlagDefinitions();\n } catch (err) {\n this.onError?.(new Error(`Error in shouldFetchFlagDefinitions: ${err}`));\n }\n if (!shouldFetch) {\n const loaded = await this.loadFromCache('Loaded flags from cache (skipped fetch)');\n if (loaded) return;\n if (this.loadedSuccessfullyOnce) return;\n }\n const res = await this._requestFeatureFlagDefinitions();\n if (!res) return;\n switch(res.status){\n case 304:\n this.logMsgIfDebug(()=>console.debug('[FEATURE FLAGS] Flags not modified (304), using cached data'));\n this.flagsEtag = res.headers?.get('ETag') ?? this.flagsEtag;\n this.loadedSuccessfullyOnce = true;\n this.clearBackoff();\n return;\n case 401:\n this.beginBackoff();\n throw new ClientError(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);\n case 402:\n console.warn('[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts');\n this.featureFlags = [];\n this.featureFlagsByKey = {};\n this.groupTypeMapping = {};\n this.cohorts = {};\n this.onMinimalFlagCalledEvents?.(false);\n return;\n case 403:\n this.beginBackoff();\n throw new ClientError(`Your secret key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);\n case 429:\n this.beginBackoff();\n throw new ClientError(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);\n case 200:\n {\n const responseJson = await res.json() ?? {};\n if (!('flags' in responseJson)) return void this.onError?.(new Error(`Invalid response when getting feature flags: ${JSON.stringify(responseJson)}`));\n this.flagsEtag = res.headers?.get('ETag') ?? void 0;\n const flagData = {\n flags: responseJson.flags ?? [],\n groupTypeMapping: responseJson.group_type_mapping || {},\n cohorts: responseJson.cohorts || {},\n minimalFlagCalledEvents: true === responseJson.minimal_flag_called_events\n };\n this.updateFlagState(flagData);\n this.flagDefinitionsLoadedAt = Date.now();\n this.clearBackoff();\n if (this.cacheProvider && shouldFetch) try {\n await this.cacheProvider.onFlagDefinitionsReceived(flagData);\n } catch (err) {\n this.onError?.(new Error(`Failed to store in cache: ${err}`));\n }\n this.onLoad?.(this.featureFlags.length);\n this.warnAboutExperienceContinuityFlags(flagData.flags);\n break;\n }\n default:\n return;\n }\n } catch (err) {\n if (err instanceof ClientError) this.onError?.(err);\n }\n }\n getPersonalApiKeyRequestOptions(method = 'GET', etag) {\n const headers = {\n ...this.customHeaders,\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.personalApiKey}`\n };\n if (etag) headers['If-None-Match'] = etag;\n return {\n method,\n headers\n };\n }\n _requestFeatureFlagDefinitions() {\n const url = `${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`;\n const options = this.getPersonalApiKeyRequestOptions('GET', this.flagsEtag);\n let abortTimeout = null;\n if (this.timeout && 'number' == typeof this.timeout) {\n const controller = new AbortController();\n abortTimeout = safeSetTimeout(()=>{\n controller.abort();\n }, this.timeout);\n options.signal = controller.signal;\n }\n try {\n const fetch1 = this.fetch;\n return fetch1(url, options);\n } finally{\n clearTimeout(abortTimeout);\n }\n }\n async stopPoller(timeoutMs = 30000) {\n clearTimeout(this.poller);\n if (this.cacheProvider) try {\n const shutdownResult = this.cacheProvider.shutdown();\n if (shutdownResult instanceof Promise) await Promise.race([\n shutdownResult,\n new Promise((_, reject)=>setTimeout(()=>reject(new Error(`Cache shutdown timeout after ${timeoutMs}ms`)), timeoutMs))\n ]);\n } catch (err) {\n this.onError?.(new Error(`Error during cache shutdown: ${err}`));\n }\n }\n}\nasync function _hash(key, bucketingValue, salt = '') {\n const hashString = await hashSHA1(`${key}.${bucketingValue}${salt}`);\n return parseInt(hashString.slice(0, 15), 16) / LONG_SCALE;\n}\nfunction matchProperty(property, propertyValues, warnFunction) {\n const key = property.key;\n const value = property.value;\n const operator = property.operator || 'exact';\n if (key in propertyValues) {\n if ('is_not_set' === operator) return false;\n } else {\n if ('is_not_set' === operator) return true;\n throw new InconclusiveMatchError(`Property ${key} not found in propertyValues`);\n }\n const overrideValue = propertyValues[key];\n if (null == overrideValue && !NULL_VALUES_ALLOWED_OPERATORS.includes(operator)) {\n if (warnFunction) warnFunction(`Property ${key} cannot have a value of null/undefined with the ${operator} operator`);\n return false;\n }\n function computeExactMatch(value, overrideValue) {\n if (Array.isArray(value)) return value.map((val)=>String(val).toLowerCase()).includes(String(overrideValue).toLowerCase());\n return String(value).toLowerCase() === String(overrideValue).toLowerCase();\n }\n function compare(lhs, rhs, operator) {\n if ('gt' === operator) return lhs > rhs;\n if ('gte' === operator) return lhs >= rhs;\n if ('lt' === operator) return lhs < rhs;\n if ('lte' === operator) return lhs <= rhs;\n throw new Error(`Invalid operator: ${operator}`);\n }\n switch(operator){\n case 'exact':\n return computeExactMatch(value, overrideValue);\n case 'is_not':\n return !computeExactMatch(value, overrideValue);\n case 'is_set':\n return key in propertyValues;\n case 'icontains':\n return String(overrideValue).toLowerCase().includes(String(value).toLowerCase());\n case 'not_icontains':\n return !String(overrideValue).toLowerCase().includes(String(value).toLowerCase());\n case 'regex':\n return isValidRegex(String(value)) && null !== String(overrideValue).match(String(value));\n case 'not_regex':\n return isValidRegex(String(value)) && null === String(overrideValue).match(String(value));\n case 'gt':\n case 'gte':\n case 'lt':\n case 'lte':\n {\n const parsedValue = 'number' == typeof value ? value : parseFloat(String(value));\n let parsedOverride;\n parsedOverride = 'number' == typeof overrideValue ? overrideValue : null != overrideValue ? parseFloat(String(overrideValue)) : NaN;\n if (Number.isFinite(parsedValue) && Number.isFinite(parsedOverride)) return compare(parsedOverride, parsedValue, operator);\n return compare(String(overrideValue), String(value), operator);\n }\n case 'is_date_after':\n case 'is_date_before':\n {\n if ('boolean' == typeof value) throw new InconclusiveMatchError(\"Date operations cannot be performed on boolean values\");\n let parsedDate = relativeDateParseForFeatureFlagMatching(String(value));\n if (null == parsedDate) parsedDate = convertToDateTime(value);\n if (null == parsedDate) throw new InconclusiveMatchError(`Invalid date: ${value}`);\n const overrideDate = convertToDateTime(overrideValue);\n if ([\n 'is_date_before'\n ].includes(operator)) return overrideDate < parsedDate;\n return overrideDate > parsedDate;\n }\n case 'semver_eq':\n {\n const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));\n return 0 === cmp;\n }\n case 'semver_neq':\n {\n const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));\n return 0 !== cmp;\n }\n case 'semver_gt':\n {\n const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));\n return cmp > 0;\n }\n case 'semver_gte':\n {\n const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));\n return cmp >= 0;\n }\n case 'semver_lt':\n {\n const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));\n return cmp < 0;\n }\n case 'semver_lte':\n {\n const cmp = compareSemverTuples(parseSemver(String(overrideValue)), parseSemver(String(value)));\n return cmp <= 0;\n }\n case 'semver_tilde':\n {\n const overrideParsed = parseSemver(String(overrideValue));\n const { lower, upper } = computeTildeBounds(String(value));\n return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;\n }\n case 'semver_caret':\n {\n const overrideParsed = parseSemver(String(overrideValue));\n const { lower, upper } = computeCaretBounds(String(value));\n return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;\n }\n case 'semver_wildcard':\n {\n const overrideParsed = parseSemver(String(overrideValue));\n const { lower, upper } = computeWildcardBounds(String(value));\n return compareSemverTuples(overrideParsed, lower) >= 0 && compareSemverTuples(overrideParsed, upper) < 0;\n }\n default:\n throw new InconclusiveMatchError(`Unknown operator: ${operator}`);\n }\n}\nfunction checkCohortExists(cohortId, cohortProperties) {\n if (!(cohortId in cohortProperties)) throw new RequiresServerEvaluation(`cohort ${cohortId} not found in local cohorts - likely a static cohort that requires server evaluation`);\n}\nasync function matchCohort(property, propertyValues, cohortProperties, debugMode = false, flagDependencyEvaluator) {\n const cohortId = String(property.value);\n checkCohortExists(cohortId, cohortProperties);\n const propertyGroup = cohortProperties[cohortId];\n return matchPropertyGroup(propertyGroup, propertyValues, cohortProperties, debugMode, flagDependencyEvaluator);\n}\nasync function matchPropertyGroup(propertyGroup, propertyValues, cohortProperties, debugMode = false, flagDependencyEvaluator) {\n if (!propertyGroup) return true;\n const propertyGroupType = propertyGroup.type;\n const properties = propertyGroup.values;\n if (!properties || 0 === properties.length) return true;\n let errorMatchingLocally = false;\n if ('values' in properties[0]) {\n for (const prop of properties)try {\n const matches = await matchPropertyGroup(prop, propertyValues, cohortProperties, debugMode, flagDependencyEvaluator);\n if ('AND' === propertyGroupType) {\n if (!matches) return false;\n } else if (matches) return true;\n } catch (err) {\n if (err instanceof RequiresServerEvaluation) throw err;\n if (err instanceof InconclusiveMatchError) {\n if (debugMode) console.debug(`Failed to compute property ${prop} locally: ${err}`);\n errorMatchingLocally = true;\n } else throw err;\n }\n if (errorMatchingLocally) throw new InconclusiveMatchError(\"Can't match cohort without a given cohort property value\");\n return 'AND' === propertyGroupType;\n }\n for (const prop of properties)try {\n let matches;\n if ('cohort' === prop.type) matches = await matchCohort(prop, propertyValues, cohortProperties, debugMode, flagDependencyEvaluator);\n else if ('flag' === prop.type) {\n if (!flagDependencyEvaluator) throw new InconclusiveMatchError(`Flag dependency '${prop.key || 'unknown'}' cannot be evaluated without a flag dependency evaluator`);\n matches = await flagDependencyEvaluator(prop);\n } else matches = matchProperty(prop, propertyValues);\n const negation = prop.negation || false;\n if ('AND' === propertyGroupType) {\n if (!matches && !negation) return false;\n if (matches && negation) return false;\n } else {\n if (matches && !negation) return true;\n if (!matches && negation) return true;\n }\n } catch (err) {\n if (err instanceof RequiresServerEvaluation) throw err;\n if (err instanceof InconclusiveMatchError) {\n if (debugMode) console.debug(`Failed to compute property ${prop} locally: ${err}`);\n errorMatchingLocally = true;\n } else throw err;\n }\n if (errorMatchingLocally) throw new InconclusiveMatchError(\"can't match cohort without a given cohort property value\");\n return 'AND' === propertyGroupType;\n}\nfunction isValidRegex(regex) {\n try {\n new RegExp(regex);\n return true;\n } catch (err) {\n return false;\n }\n}\nfunction parseSemverNumericIdentifier(part, raw) {\n if (!/^\\d+$/.test(part)) throw new InconclusiveMatchError(`Invalid semver: ${raw}`);\n if (part.length > 1 && '0' === part[0]) throw new InconclusiveMatchError(`Invalid semver: ${raw}`);\n return parseInt(part, 10);\n}\nfunction parseSemver(value) {\n const text = String(value).trim().replace(/^[vV]/, '');\n const baseVersion = text.split('-')[0].split('+')[0];\n if (!baseVersion || baseVersion.startsWith('.')) throw new InconclusiveMatchError(`Invalid semver: ${value}`);\n const parts = baseVersion.split('.');\n const parsePart = (part)=>{\n if (void 0 === part || '' === part) return 0;\n return parseSemverNumericIdentifier(part, value);\n };\n const major = parsePart(parts[0]);\n const minor = parsePart(parts[1]);\n const patch = parsePart(parts[2]);\n return [\n major,\n minor,\n patch\n ];\n}\nfunction compareSemverTuples(a, b) {\n for(let i = 0; i < 3; i++){\n if (a[i] < b[i]) return -1;\n if (a[i] > b[i]) return 1;\n }\n return 0;\n}\nfunction computeTildeBounds(value) {\n const parsed = parseSemver(value);\n const lower = [\n parsed[0],\n parsed[1],\n parsed[2]\n ];\n const upper = [\n parsed[0],\n parsed[1] + 1,\n 0\n ];\n return {\n lower,\n upper\n };\n}\nfunction computeCaretBounds(value) {\n const parsed = parseSemver(value);\n const [major, minor, patch] = parsed;\n const lower = [\n major,\n minor,\n patch\n ];\n let upper;\n upper = major > 0 ? [\n major + 1,\n 0,\n 0\n ] : minor > 0 ? [\n 0,\n minor + 1,\n 0\n ] : [\n 0,\n 0,\n patch + 1\n ];\n return {\n lower,\n upper\n };\n}\nfunction computeWildcardBounds(value) {\n const text = String(value).trim().replace(/^[vV]/, '');\n const cleanedText = text.replace(/\\.\\*$/, '').replace(/\\*$/, '');\n if (!cleanedText) throw new InconclusiveMatchError(`Invalid wildcard semver: ${value}`);\n const parts = cleanedText.split('.');\n const parseWildcardPart = (part)=>{\n try {\n return parseSemverNumericIdentifier(part, value);\n } catch {\n throw new InconclusiveMatchError(`Invalid wildcard semver: ${value}`);\n }\n };\n const major = parseWildcardPart(parts[0]);\n let lower;\n let upper;\n if (1 === parts.length) {\n lower = [\n major,\n 0,\n 0\n ];\n upper = [\n major + 1,\n 0,\n 0\n ];\n } else {\n const minor = parseWildcardPart(parts[1]);\n lower = [\n major,\n minor,\n 0\n ];\n upper = [\n major,\n minor + 1,\n 0\n ];\n }\n return {\n lower,\n upper\n };\n}\nfunction convertToDateTime(value) {\n if (value instanceof Date) return value;\n if ('string' == typeof value || 'number' == typeof value) {\n const date = new Date(value);\n if (!isNaN(date.valueOf())) return date;\n throw new InconclusiveMatchError(`${value} is in an invalid date format`);\n }\n throw new InconclusiveMatchError(`The date provided ${value} must be a string, number, or date object`);\n}\nfunction relativeDateParseForFeatureFlagMatching(value) {\n const regex = /^-?(?<number>[0-9]+)(?<interval>[a-z])$/;\n const match = value.match(regex);\n const parsedDt = new Date(new Date().toISOString());\n if (!match) return null;\n {\n if (!match.groups) return null;\n const number = parseInt(match.groups['number']);\n if (number >= 10000) return null;\n const interval = match.groups['interval'];\n if ('h' == interval) parsedDt.setUTCHours(parsedDt.getUTCHours() - number);\n else if ('d' == interval) parsedDt.setUTCDate(parsedDt.getUTCDate() - number);\n else if ('w' == interval) parsedDt.setUTCDate(parsedDt.getUTCDate() - 7 * number);\n else if ('m' == interval) parsedDt.setUTCMonth(parsedDt.getUTCMonth() - number);\n else {\n if ('y' != interval) return null;\n parsedDt.setUTCFullYear(parsedDt.getUTCFullYear() - number);\n }\n return parsedDt;\n }\n}\nexport { ClientError, FeatureFlagsPoller, InconclusiveMatchError, RequiresServerEvaluation, matchProperty, parseSemver, relativeDateParseForFeatureFlagMatching };\n","function makeUncaughtExceptionHandler(captureFn, onFatalFn) {\n let calledFatalError = false;\n return Object.assign((error)=>{\n const userProvidedListenersCount = global.process.listeners('uncaughtException').filter((listener)=>'domainUncaughtExceptionClear' !== listener.name && true !== listener._posthogErrorHandler).length;\n const processWouldExit = 0 === userProvidedListenersCount;\n captureFn(error, {\n mechanism: {\n type: 'onuncaughtexception',\n handled: false\n }\n });\n if (!calledFatalError && processWouldExit) {\n calledFatalError = true;\n onFatalFn(error);\n }\n }, {\n _posthogErrorHandler: true\n });\n}\nfunction addUncaughtExceptionListener(captureFn, onFatalFn) {\n globalThis.process?.on('uncaughtException', makeUncaughtExceptionHandler(captureFn, onFatalFn));\n}\nfunction addUnhandledRejectionListener(captureFn) {\n globalThis.process?.on('unhandledRejection', (reason)=>captureFn(reason, {\n mechanism: {\n type: 'onunhandledrejection',\n handled: false\n }\n }));\n}\nexport { addUncaughtExceptionListener, addUnhandledRejectionListener };\n","import { addUncaughtExceptionListener, addUnhandledRejectionListener } from \"./autocapture.mjs\";\nimport { BucketedRateLimiter, isObject, resolveExceptionRateLimiterConfig } from \"@posthog/core\";\nconst SHUTDOWN_TIMEOUT = 2000;\nclass ErrorTracking {\n constructor(client, options, _logger){\n this.client = client;\n this._exceptionAutocaptureEnabled = options.enableExceptionAutocapture || false;\n this._logger = _logger;\n this._rateLimiter = new BucketedRateLimiter({\n ...resolveExceptionRateLimiterConfig(options),\n refillInterval: 10000,\n _logger: this._logger\n });\n this.startAutocaptureIfEnabled();\n }\n static isPreviouslyCapturedError(x) {\n return isObject(x) && '__posthog_previously_captured_error' in x && true === x.__posthog_previously_captured_error;\n }\n static async buildEventMessage(builder, error, hint, distinctId, additionalProperties) {\n const properties = {\n ...additionalProperties\n };\n const exceptionProperties = builder.buildFromUnknown(error, hint);\n exceptionProperties.$exception_list = await builder.modifyFrames(exceptionProperties.$exception_list);\n return {\n event: '$exception',\n distinctId: distinctId,\n properties: {\n ...exceptionProperties,\n ...properties\n },\n _originatedFromCaptureException: true\n };\n }\n startAutocaptureIfEnabled() {\n if (this.isEnabled()) {\n addUncaughtExceptionListener(this.onException.bind(this), this.onFatalError.bind(this));\n addUnhandledRejectionListener(this.onException.bind(this));\n }\n }\n onException(exception, hint) {\n this.client.addPendingPromise((async ()=>{\n if (!ErrorTracking.isPreviouslyCapturedError(exception)) {\n const eventMessage = await ErrorTracking.buildEventMessage(this.client.getErrorPropertiesBuilder(), exception, hint);\n const exceptionProperties = eventMessage.properties;\n const exceptionType = exceptionProperties?.$exception_list[0]?.type ?? 'Exception';\n const isRateLimited = this._rateLimiter.consumeRateLimit(exceptionType);\n if (isRateLimited) return void this._logger.info('Skipping exception capture because of client rate limiting.', {\n exception: exceptionType\n });\n return this.client._capturePreparedEvent(eventMessage, false);\n }\n })());\n }\n async onFatalError(exception) {\n console.error(exception);\n await this.client.shutdown(SHUTDOWN_TIMEOUT);\n globalThis.process.exit(1);\n }\n isEnabled() {\n return !this.client.isDisabled && this._exceptionAutocaptureEnabled;\n }\n shutdown() {\n this._rateLimiter.stop();\n }\n}\nexport { ErrorTracking as default };\n","class PostHogMemoryStorage {\n getProperty(key) {\n return this._memoryStorage[key];\n }\n setProperty(key, value) {\n this._memoryStorage[key] = null !== value ? value : void 0;\n }\n constructor(){\n this._memoryStorage = {};\n }\n}\nexport { PostHogMemoryStorage };\n","function isCaptureMode(value) {\n return 'v0' === value || 'v1' === value;\n}\nfunction resolveCaptureMode() {\n const envMode = 'undefined' != typeof process ? process.env?.POSTHOG_CAPTURE_MODE : void 0;\n return isCaptureMode(envMode) ? envMode : 'v0';\n}\nexport { resolveCaptureMode };\n","const AI_EVENT_PREFIX = '$ai_';\nconst ANALYTICS_ROUTE = 'analytics';\nconst AI_ROUTE = 'ai';\nfunction isLegacyOnlyEvent(message) {\n return 'string' == typeof message.event && message.event.startsWith(AI_EVENT_PREFIX);\n}\nexport { AI_ROUTE, ANALYTICS_ROUTE, isLegacyOnlyEvent };\n","class CaptureV1Error extends Error {\n constructor({ requestId, drops, retryExhausted, cause }){\n super(CaptureV1Error.buildMessage(requestId, drops, retryExhausted, cause)), this.name = 'CaptureV1Error';\n this.requestId = requestId;\n this.drops = drops;\n this.retryExhausted = retryExhausted;\n this.cause = cause;\n }\n static buildMessage(requestId, drops, retryExhausted, cause) {\n let message = `Capture V1 batch ${requestId} did not fully deliver: ${drops.length} dropped, ${retryExhausted.length} undelivered`;\n if (cause instanceof Error) message += ` (${cause.message})`;\n return message;\n }\n}\nexport { CaptureV1Error };\n","function coerceBool(value) {\n if ('boolean' == typeof value) return value;\n if ('number' == typeof value) return 0 !== value;\n if ('string' == typeof value) {\n const normalized = value.trim().toLowerCase();\n if ('true' === normalized || '1' === normalized) return true;\n if ('false' === normalized || '0' === normalized) return false;\n }\n}\nfunction coerceString(value) {\n return 'string' == typeof value ? value : void 0;\n}\nconst OPTION_SENTINELS = [\n {\n property: '$cookieless_mode',\n optionKey: 'cookieless_mode',\n coerce: coerceBool\n },\n {\n property: '$ignore_sent_at',\n optionKey: 'disable_skew_correction',\n coerce: coerceBool\n },\n {\n property: '$process_person_profile',\n optionKey: 'process_person_profile',\n coerce: coerceBool\n },\n {\n property: '$product_tour_id',\n optionKey: 'product_tour_id',\n coerce: coerceString\n }\n];\nconst TOPLEVEL_SENTINELS = [\n {\n property: '$session_id',\n field: 'session_id'\n },\n {\n property: '$window_id',\n field: 'window_id'\n }\n];\nfunction isRecord(value) {\n return 'object' == typeof value && null !== value && !Array.isArray(value);\n}\nfunction toRfc3339(timestamp) {\n if ('string' == typeof timestamp) {\n const asDate = new Date(timestamp);\n return Number.isNaN(asDate.getTime()) ? new Date().toISOString() : timestamp;\n }\n if (timestamp instanceof Date) return Number.isNaN(timestamp.getTime()) ? new Date().toISOString() : timestamp.toISOString();\n const asDate = null == timestamp ? new Date() : new Date(timestamp);\n return Number.isNaN(asDate.getTime()) ? new Date().toISOString() : asDate.toISOString();\n}\nfunction relocateInto(properties, key, value) {\n if (void 0 !== value && !(key in properties)) properties[key] = value;\n}\nfunction buildV1Event(message) {\n const sourceProperties = isRecord(message.properties) ? message.properties : {};\n const properties = {\n ...sourceProperties\n };\n const options = {};\n for (const { property, optionKey, coerce } of OPTION_SENTINELS)if (property in properties) {\n const coerced = coerce(properties[property]);\n if (void 0 !== coerced) options[optionKey] = coerced;\n delete properties[property];\n }\n const topLevel = {};\n for (const { property, field } of TOPLEVEL_SENTINELS)if (property in properties) {\n const value = properties[property];\n if ('string' == typeof value) topLevel[field] = value;\n delete properties[property];\n }\n delete properties.$lib;\n delete properties.$lib_version;\n relocateInto(properties, '$set', message.$set);\n relocateInto(properties, '$set_once', message.$set_once);\n return {\n event: String(message.event ?? ''),\n uuid: String(message.uuid ?? ''),\n distinct_id: String(message.distinct_id ?? ''),\n timestamp: toRfc3339(message.timestamp),\n ...topLevel,\n options,\n properties\n };\n}\nfunction buildV1Batch(messages, { createdAt, historicalMigration }) {\n const batch = {\n created_at: createdAt,\n batch: messages.map(buildV1Event)\n };\n if (historicalMigration) batch.historical_migration = true;\n return batch;\n}\nexport { buildV1Batch, buildV1Event, coerceBool, coerceString };\n","import { gzipCompress, safeJsonStringify, safeSetTimeout, uuidv7 } from \"@posthog/core\";\nimport { CaptureV1Error } from \"./errors.mjs\";\nimport { buildV1Batch } from \"./transform.mjs\";\nconst V1_ANALYTICS_PATH = '/i/v1/analytics/events';\nconst DEFAULT_MAX_BACKOFF_MS = 30000;\nconst RETRYABLE_STATUSES = new Set([\n 408,\n 500,\n 502,\n 503,\n 504\n]);\nclass V1CaptureSender {\n constructor(config, hooks){\n this.config = config;\n this.maxBackoffMs = config.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS;\n this.fetchFn = hooks.fetch;\n this.onError = hooks.onError;\n this.now = hooks.now ?? Date.now;\n this.sleep = hooks.sleep ?? ((ms)=>new Promise((resolve)=>safeSetTimeout(resolve, ms)));\n this.generateRequestId = hooks.generateRequestId ?? uuidv7;\n this.compress = hooks.compress ?? gzipCompress;\n }\n async sendV1Batch(messages) {\n if (0 === messages.length) return;\n const requestId = this.generateRequestId();\n const createdAt = new Date(this.now()).toISOString();\n const { batch } = buildV1Batch(messages, {\n createdAt,\n historicalMigration: this.config.historicalMigration\n });\n const url = `${this.config.host}${V1_ANALYTICS_PATH}`;\n const drops = [];\n let pending = batch;\n const maxAttempts = Math.max(1, this.config.maxAttempts);\n for(let attempt = 1; attempt <= maxAttempts; attempt++){\n const isLastAttempt = attempt === maxAttempts;\n const payload = safeJsonStringify({\n created_at: createdAt,\n ...this.config.historicalMigration ? {\n historical_migration: true\n } : {},\n batch: pending\n });\n let response;\n try {\n response = await this.sendOnce(url, payload, attempt, requestId);\n } catch (transportError) {\n if (isLastAttempt) return this.surfaceBatchFailure(requestId, drops, pending, transportError);\n await this.sleep(this.backoffDelay(attempt));\n continue;\n }\n const { status } = response;\n if (status < 200 || status >= 300) {\n if (!isLastAttempt && RETRYABLE_STATUSES.has(status)) {\n const retryAfterMs = this.parseRetryAfter(response);\n await this.cancelBody(response);\n await this.sleep(this.backoffDelay(attempt, retryAfterMs));\n continue;\n }\n const httpError = await this.buildHttpError(response, status);\n return this.surfaceBatchFailure(requestId, drops, pending, httpError);\n }\n let parsed;\n try {\n parsed = await this.parseResponse(response);\n } catch {\n return this.surfaceBatchFailure(requestId, drops, pending, new Error(`Capture V1 returned an unparseable ${status} response body`));\n }\n const retryable = this.classify(pending, parsed, drops);\n if (0 === retryable.length) return this.surfacePartialDrops(requestId, drops);\n if (isLastAttempt) return void this.onError(new CaptureV1Error({\n requestId,\n drops,\n retryExhausted: retryable.map((event)=>event.uuid)\n }));\n pending = retryable;\n const retryAfterMs = this.parseRetryAfter(response);\n await this.sleep(this.backoffDelay(attempt, retryAfterMs));\n }\n }\n async sendOnce(url, payload, attempt, requestId) {\n const headers = this.buildHeaders(attempt, requestId);\n let body = payload;\n if (this.config.compressionEnabled) {\n const compressed = await this.compress(payload, this.config.isDebug);\n if (null !== compressed) {\n body = compressed;\n headers['Content-Encoding'] = 'gzip';\n }\n }\n const controller = new AbortController();\n const timer = safeSetTimeout(()=>controller.abort(), this.config.requestTimeoutMs);\n try {\n return await this.fetchFn(url, {\n method: 'POST',\n headers,\n body,\n signal: controller.signal\n });\n } finally{\n clearTimeout(timer);\n }\n }\n buildHeaders(attempt, requestId) {\n const sdkInfo = `${this.config.libraryId}/${this.config.libraryVersion}`;\n const headers = {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.config.apiKey}`,\n 'PostHog-Sdk-Info': sdkInfo,\n 'PostHog-Attempt': String(attempt),\n 'PostHog-Request-Id': requestId,\n 'PostHog-Request-Timestamp': new Date(this.now()).toISOString()\n };\n if (this.config.userAgent) headers['User-Agent'] = this.config.userAgent;\n return headers;\n }\n classify(pending, parsed, drops) {\n const results = parsed.results ?? {};\n const retryable = [];\n for (const event of pending){\n const result = results[event.uuid];\n if (result) {\n if ('drop' === result.result) drops.push({\n uuid: event.uuid,\n details: result.details ?? void 0\n });\n else if ('retry' === result.result) retryable.push(event);\n }\n }\n return retryable;\n }\n backoffDelay(attempt, retryAfterMs) {\n const exponential = Math.min(this.config.initialRetryDelayMs * 2 ** (attempt - 1), this.maxBackoffMs);\n if (void 0 === retryAfterMs) return exponential;\n return Math.max(exponential, Math.min(retryAfterMs, this.maxBackoffMs));\n }\n parseRetryAfter(response) {\n const raw = response.headers?.get('Retry-After');\n if (!raw) return;\n const trimmed = raw.trim();\n if (/^\\d+$/.test(trimmed)) {\n const seconds = parseInt(trimmed, 10);\n return Number.isFinite(seconds) && seconds > 0 ? 1000 * seconds : void 0;\n }\n const dateMs = Date.parse(trimmed);\n if (Number.isNaN(dateMs)) return;\n const delta = dateMs - this.now();\n return delta > 0 ? delta : void 0;\n }\n async parseResponse(response) {\n const text = await response.text();\n const parsed = JSON.parse(text);\n if ('object' != typeof parsed || null === parsed || Array.isArray(parsed)) throw new Error('unexpected response shape');\n const results = parsed.results;\n if (void 0 !== results && ('object' != typeof results || null === results || Array.isArray(results))) throw new Error('unexpected results shape');\n return {\n results: results ?? {}\n };\n }\n async buildHttpError(response, status) {\n let bodyText = '';\n try {\n bodyText = (await response.text()).slice(0, 512);\n } catch {}\n const suffix = bodyText ? `: ${bodyText}` : '';\n return new Error(`Capture V1 request failed with HTTP ${status}${suffix}`);\n }\n surfaceBatchFailure(requestId, drops, pending, cause) {\n this.onError(new CaptureV1Error({\n requestId,\n drops,\n retryExhausted: pending.map((event)=>event.uuid),\n cause\n }));\n }\n surfacePartialDrops(requestId, drops) {\n if (drops.length > 0) this.onError(new CaptureV1Error({\n requestId,\n drops,\n retryExhausted: []\n }));\n }\n async cancelBody(response) {\n await response.body?.cancel()?.catch(()=>{});\n }\n}\nexport { V1CaptureSender };\n","import { version } from \"./version.mjs\";\nimport { PostHogCoreStateless, PostHogMetrics, PostHogPersistedProperty, isBlockedUA, isPlainObject, minimizeFlagCalledEventProperties, resolveMetricsConfig, safeSetTimeout, uuidv7 } from \"@posthog/core\";\nimport { FeatureFlagError } from \"./types.mjs\";\nimport { FeatureFlagEvaluations } from \"./feature-flag-evaluations.mjs\";\nimport { FeatureFlagsPoller, InconclusiveMatchError, RequiresServerEvaluation } from \"./extensions/feature-flags/feature-flags.mjs\";\nimport error_tracking from \"./extensions/error-tracking/index.mjs\";\nimport { PostHogMemoryStorage } from \"./storage-memory.mjs\";\nimport { resolveCaptureMode } from \"./capture-v1/config.mjs\";\nimport { AI_ROUTE, ANALYTICS_ROUTE, isLegacyOnlyEvent } from \"./capture-v1/routing.mjs\";\nimport { V1CaptureSender } from \"./capture-v1/sender.mjs\";\nconst MINIMUM_POLLING_INTERVAL = 100;\nconst THIRTY_SECONDS = 30000;\nconst MAX_CACHE_SIZE = 50000;\nconst WAITUNTIL_DEBOUNCE_MS = 50;\nconst WAITUNTIL_MAX_WAIT_MS = 500;\nconst DEFAULT_NODE_HOST = 'https://us.i.posthog.com';\nconst _emittedDeprecations = new Set();\nfunction emitDeprecationWarningOnce(id, message) {\n if (_emittedDeprecations.has(id)) return;\n _emittedDeprecations.add(id);\n console.warn(`[PostHog] ${message}`);\n}\nfunction _resetDeprecationWarningsForTests() {\n _emittedDeprecations.clear();\n}\nfunction normalizeApiKey(value) {\n return 'string' == typeof value ? value.trim() : '';\n}\nfunction normalizePersonalApiKey(value) {\n const normalizedValue = 'string' == typeof value ? value.trim() : '';\n return normalizedValue || void 0;\n}\nfunction normalizeHost(value) {\n const normalizedValue = 'string' == typeof value ? value.trim() : '';\n return normalizedValue || DEFAULT_NODE_HOST;\n}\nfunction normalizeUnsetPersonProperties(value) {\n const propertyNames = Array.isArray(value) ? value : [\n value\n ];\n return propertyNames.filter((propertyName)=>'string' == typeof propertyName && propertyName.trim().length > 0);\n}\nfunction buildFlagEventProperties(flagValues) {\n if (!flagValues) return {};\n const additionalProperties = {};\n for (const [feature, variant] of Object.entries(flagValues))additionalProperties[`$feature/${feature}`] = variant;\n const activeFlags = Object.keys(flagValues).filter((flag)=>false !== flagValues[flag]).sort();\n if (activeFlags.length > 0) additionalProperties['$active_feature_flags'] = activeFlags;\n return additionalProperties;\n}\nclass PostHogBackendClient extends PostHogCoreStateless {\n constructor(apiKey, options = {}){\n const normalizedApiKey = normalizeApiKey(apiKey);\n const normalizedOptions = {\n ...options,\n maxQueueSize: options.maxQueueSize ?? 10000,\n flushInterval: options.flushInterval ?? 5000,\n host: normalizeHost(options.host),\n personalApiKey: normalizePersonalApiKey(options.secretKey ?? options.personalApiKey)\n };\n super(normalizedApiKey, normalizedOptions), this._memoryStorage = new PostHogMemoryStorage(), this._minimalFlagCalledEvents = false;\n this.options = normalizedOptions;\n this.captureMode = resolveCaptureMode();\n this.context = this.initializeContext();\n this.options.featureFlagsPollingInterval = 'number' == typeof normalizedOptions.featureFlagsPollingInterval ? Math.max(normalizedOptions.featureFlagsPollingInterval, MINIMUM_POLLING_INTERVAL) : THIRTY_SECONDS;\n if ('number' == typeof normalizedOptions.waitUntilDebounceMs) this.options.waitUntilDebounceMs = Math.max(normalizedOptions.waitUntilDebounceMs, 0);\n if ('number' == typeof normalizedOptions.waitUntilMaxWaitMs) this.options.waitUntilMaxWaitMs = Math.max(normalizedOptions.waitUntilMaxWaitMs, 0);\n if (!this.disabled && normalizedOptions.personalApiKey) {\n if (normalizedOptions.personalApiKey.includes('phc_')) throw new Error('Your Personal API key is invalid. These keys are prefixed with \"phx_\" and can be created in PostHog project settings.');\n const shouldEnableLocalEvaluation = false !== normalizedOptions.enableLocalEvaluation;\n if (shouldEnableLocalEvaluation) this.featureFlagsPoller = new FeatureFlagsPoller({\n pollingInterval: this.options.featureFlagsPollingInterval,\n personalApiKey: normalizedOptions.personalApiKey,\n projectApiKey: normalizedApiKey,\n timeout: normalizedOptions.requestTimeout ?? 10000,\n host: this.host,\n fetch: normalizedOptions.fetch,\n onError: (err)=>{\n this._events.emit('error', err);\n },\n onLoad: (count)=>{\n this._events.emit('localEvaluationFlagsLoaded', count);\n },\n onMinimalFlagCalledEvents: (enabled)=>{\n this._minimalFlagCalledEvents = enabled;\n },\n customHeaders: this.getCustomHeaders(),\n cacheProvider: normalizedOptions.flagDefinitionCacheProvider,\n strictLocalEvaluation: normalizedOptions.strictLocalEvaluation\n });\n }\n this.errorTracking = new error_tracking(this, normalizedOptions, this._logger);\n this.distinctIdHasSentFlagCalls = {};\n this.maxCacheSize = normalizedOptions.maxCacheSize || MAX_CACHE_SIZE;\n }\n enqueue(type, message, options) {\n super.enqueue(type, message, options);\n this.scheduleDebouncedFlush();\n }\n async flush() {\n const flushPromise = this.flushWithPendingPromises();\n const waitUntil = this.options.waitUntil;\n if (waitUntil && !this._waitUntilCycle) try {\n waitUntil(flushPromise.catch(()=>{}));\n } catch {}\n return flushPromise;\n }\n scheduleDebouncedFlush() {\n const waitUntil = this.options.waitUntil;\n if (!waitUntil) return;\n if (this.disabled || this.optedOut) return;\n if (!this._waitUntilCycle) {\n let resolve;\n const promise = new Promise((r)=>{\n resolve = r;\n });\n try {\n waitUntil(promise);\n } catch {\n return;\n }\n this._waitUntilCycle = {\n resolve: resolve,\n startedAt: Date.now(),\n timer: void 0\n };\n }\n const elapsed = Date.now() - this._waitUntilCycle.startedAt;\n const maxWaitMs = this.options.waitUntilMaxWaitMs ?? WAITUNTIL_MAX_WAIT_MS;\n const flushNow = elapsed >= maxWaitMs;\n if (void 0 !== this._waitUntilCycle.timer) clearTimeout(this._waitUntilCycle.timer);\n if (flushNow) return void this.resolveWaitUntilFlush();\n const debounceMs = this.options.waitUntilDebounceMs ?? WAITUNTIL_DEBOUNCE_MS;\n this._waitUntilCycle.timer = safeSetTimeout(()=>{\n this.resolveWaitUntilFlush();\n }, debounceMs);\n }\n _consumeWaitUntilCycle() {\n const cycle = this._waitUntilCycle;\n if (cycle) {\n clearTimeout(cycle.timer);\n this._waitUntilCycle = void 0;\n }\n return cycle?.resolve;\n }\n async resolveWaitUntilFlush() {\n const resolve = this._consumeWaitUntilCycle();\n try {\n await this.flushWithPendingPromises();\n } catch {} finally{\n resolve?.();\n }\n }\n getPersistedProperty(key) {\n return this._memoryStorage.getProperty(key);\n }\n setPersistedProperty(key, value) {\n return this._memoryStorage.setProperty(key, value);\n }\n fetch(url, options) {\n return this.options.fetch ? this.options.fetch(url, options) : fetch(url, options);\n }\n getQueueRouteKey(message) {\n return 'v1' === this.captureMode && isLegacyOnlyEvent(message) ? AI_ROUTE : ANALYTICS_ROUTE;\n }\n persistedQueueKeyForRoute(route) {\n return route === AI_ROUTE ? PostHogPersistedProperty.AiQueue : PostHogPersistedProperty.Queue;\n }\n getActiveQueueRoutes() {\n return 'v1' === this.captureMode ? [\n ANALYTICS_ROUTE,\n AI_ROUTE\n ] : [\n ANALYTICS_ROUTE\n ];\n }\n async sendBatch(batchMessages, retryOptions, route = ANALYTICS_ROUTE) {\n if ('v1' !== this.captureMode || route === AI_ROUTE) return super.sendBatch(batchMessages, retryOptions, route);\n const v1Events = batchMessages.filter((message)=>void 0 !== message);\n await this.getV1Sender().sendV1Batch(v1Events);\n }\n getV1Sender() {\n if (!this._v1Sender) this._v1Sender = new V1CaptureSender({\n host: this.host,\n apiKey: this.apiKey,\n libraryId: this.getLibraryId(),\n libraryVersion: this.getLibraryVersion(),\n userAgent: this.getCustomUserAgent() || void 0,\n historicalMigration: this.historicalMigration,\n compressionEnabled: !this.disableCompression,\n requestTimeoutMs: this.requestTimeout,\n maxAttempts: (this.options.fetchRetryCount ?? 3) + 1,\n initialRetryDelayMs: this.options.fetchRetryDelay ?? 3000,\n isDebug: this.isDebug\n }, {\n fetch: (url, fetchOptions)=>this.fetch(url, fetchOptions),\n onError: (error)=>this._events.emit('error', error)\n });\n return this._v1Sender;\n }\n getLibraryVersion() {\n return version;\n }\n get metrics() {\n if (!this._metrics) this._metrics = new PostHogMetrics(this, resolveMetricsConfig(this.options.metrics), this._logger);\n return this._metrics;\n }\n getCustomUserAgent() {\n return `${this.getLibraryId()}/${this.getLibraryVersion()}`;\n }\n getCommonEventProperties() {\n const commonProperties = super.getCommonEventProperties();\n if (this.options.isServer ?? true) commonProperties.$is_server = true;\n return commonProperties;\n }\n enable() {\n return super.optIn();\n }\n disable() {\n return super.optOut();\n }\n debug(enabled = true) {\n super.debug(enabled);\n this.featureFlagsPoller?.debug(enabled);\n }\n _warnIfInvalidCapture(props, stringArgumentWarning, exceptionCaptureWarning) {\n if ('string' == typeof props) this._logger.warn(stringArgumentWarning);\n if ('$exception' === props.event && !props._originatedFromCaptureException) this._logger.warn(exceptionCaptureWarning);\n }\n _sendPreparedEvent(type, props, immediate, prepareOptions) {\n return this.addPendingPromise(this._prepareEventMessage(props, prepareOptions).then(({ distinctId, event, properties, options })=>{\n const captureOptions = {\n timestamp: options.timestamp,\n disableGeoip: options.disableGeoip,\n uuid: options.uuid\n };\n const message = {\n distinctId,\n event,\n properties: {\n ...properties,\n ...this.getCommonEventProperties()\n }\n };\n return immediate ? this.sendImmediate(type, message, captureOptions) : this.enqueue(type, message, captureOptions);\n }).catch((err)=>{\n if (err) console.error(err);\n }));\n }\n _capturePreparedEvent(props, immediate) {\n return this._sendPreparedEvent('capture', props, immediate);\n }\n capture(props) {\n this._warnIfInvalidCapture(props, 'Called capture() with a string as the first argument when an object was expected.', \"Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically.\");\n this._capturePreparedEvent(props, false);\n }\n async captureImmediate(props) {\n this._warnIfInvalidCapture(props, 'Called captureImmediate() with a string as the first argument when an object was expected.', \"Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default.\");\n return this._capturePreparedEvent(props, true);\n }\n identify({ distinctId, properties = {}, disableGeoip }) {\n const { $set, $set_once, $anon_distinct_id, ...rest } = properties;\n const setProps = $set || rest;\n const setOnceProps = $set_once || {};\n const eventProperties = {\n $set: setProps,\n $set_once: setOnceProps,\n $anon_distinct_id: $anon_distinct_id ?? void 0\n };\n this._sendPreparedEvent('identify', {\n distinctId,\n event: '$identify',\n properties: eventProperties,\n disableGeoip\n }, false, {\n includeContextProperties: false\n });\n }\n async identifyImmediate({ distinctId, properties = {}, disableGeoip }) {\n const { $set, $set_once, $anon_distinct_id, ...rest } = properties;\n const setProps = $set || rest;\n const setOnceProps = $set_once || {};\n const eventProperties = {\n $set: setProps,\n $set_once: setOnceProps,\n $anon_distinct_id: $anon_distinct_id ?? void 0\n };\n await this._sendPreparedEvent('identify', {\n distinctId,\n event: '$identify',\n properties: eventProperties,\n disableGeoip\n }, true, {\n includeContextProperties: false\n });\n }\n setPersonProperties({ distinctId, properties = {}, propertiesOnce = {} }) {\n if (0 === Object.keys(properties).length && 0 === Object.keys(propertiesOnce).length) return;\n const eventProperties = {};\n if (Object.keys(properties).length > 0) eventProperties.$set = properties;\n if (Object.keys(propertiesOnce).length > 0) eventProperties.$set_once = propertiesOnce;\n this.capture({\n distinctId,\n event: '$set',\n properties: eventProperties\n });\n }\n unsetPersonProperties({ distinctId, properties }) {\n const propertyNames = normalizeUnsetPersonProperties(properties);\n if (0 === propertyNames.length) return;\n this.capture({\n distinctId,\n event: '$set',\n properties: {\n $unset: propertyNames\n }\n });\n }\n alias(data) {\n this._sendPreparedEvent('alias', {\n distinctId: data.distinctId,\n event: '$create_alias',\n properties: {\n distinct_id: data.distinctId,\n alias: data.alias\n },\n disableGeoip: data.disableGeoip\n }, false, {\n includeContextProperties: false\n });\n }\n async aliasImmediate(data) {\n await this._sendPreparedEvent('alias', {\n distinctId: data.distinctId,\n event: '$create_alias',\n properties: {\n distinct_id: data.distinctId,\n alias: data.alias\n },\n disableGeoip: data.disableGeoip\n }, true, {\n includeContextProperties: false\n });\n }\n isLocalEvaluationReady() {\n return this.featureFlagsPoller?.isLocalEvaluationReady() ?? false;\n }\n async waitForLocalEvaluationReady(timeoutMs = THIRTY_SECONDS) {\n if (this.isLocalEvaluationReady()) return true;\n if (void 0 === this.featureFlagsPoller) return false;\n return new Promise((resolve)=>{\n const timeout = setTimeout(()=>{\n cleanup();\n resolve(false);\n }, timeoutMs);\n const cleanup = this._events.on('localEvaluationFlagsLoaded', (count)=>{\n clearTimeout(timeout);\n cleanup();\n resolve(count > 0);\n });\n });\n }\n _resolveDistinctId(distinctIdOrOptions, options) {\n if ('string' == typeof distinctIdOrOptions) return {\n distinctId: distinctIdOrOptions,\n options\n };\n return {\n distinctId: this.context?.get()?.distinctId,\n options: distinctIdOrOptions\n };\n }\n async _getFeatureFlagResult(key, distinctId, options = {}, matchValue) {\n if (this.disabled) return void this._logger.warn('The client is disabled');\n const sendFeatureFlagEvents = options.sendFeatureFlagEvents ?? true;\n if (void 0 !== this._flagOverrides && key in this._flagOverrides) {\n const overrideValue = this._flagOverrides[key];\n if (void 0 === overrideValue) return;\n const overridePayload = this._payloadOverrides?.[key];\n return {\n key,\n enabled: false !== overrideValue,\n variant: 'string' == typeof overrideValue ? overrideValue : void 0,\n payload: overridePayload\n };\n }\n const { groups, disableGeoip } = options;\n let { onlyEvaluateLocally, personProperties, groupProperties } = options;\n const adjustedProperties = this.addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties);\n personProperties = adjustedProperties.allPersonProperties;\n groupProperties = adjustedProperties.allGroupProperties;\n const evaluationContext = this.createFeatureFlagEvaluationContext(distinctId, groups, this.personPropertiesForLocalEvaluation(distinctId, personProperties), groupProperties);\n if (void 0 == onlyEvaluateLocally) onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;\n let result;\n let flagWasLocallyEvaluated = false;\n let requestId;\n let evaluatedAt;\n let featureFlagError;\n let flagId;\n let flagVersion;\n let flagReason;\n let flagHasExperiment;\n const localEvaluationEnabled = void 0 !== this.featureFlagsPoller;\n if (localEvaluationEnabled) {\n await this.featureFlagsPoller?.loadFeatureFlags();\n const flag = this.featureFlagsPoller?.featureFlagsByKey[key];\n if (flag) try {\n const localResult = await this.featureFlagsPoller?.computeFlagAndPayloadLocally(flag, evaluationContext, {\n matchValue\n });\n if (localResult) {\n flagWasLocallyEvaluated = true;\n const value = localResult.value;\n flagId = flag.id;\n flagReason = 'Evaluated locally';\n flagHasExperiment = flag.has_experiment;\n result = {\n key,\n enabled: false !== value,\n variant: 'string' == typeof value ? value : void 0,\n payload: localResult.payload ?? void 0\n };\n }\n } catch (e) {\n if (e instanceof RequiresServerEvaluation || e instanceof InconclusiveMatchError) this._logger?.info(`${e.name} when computing flag locally: ${key}: ${e.message}`);\n else throw e;\n }\n }\n if (!flagWasLocallyEvaluated && !onlyEvaluateLocally) {\n const flagsResponse = await super.getFeatureFlagDetailsStateless(evaluationContext.distinctId, evaluationContext.groups, personProperties, groupProperties, disableGeoip, [\n key\n ]);\n if (void 0 === flagsResponse) featureFlagError = FeatureFlagError.UNKNOWN_ERROR;\n else {\n this._minimalFlagCalledEvents = true === flagsResponse.minimalFlagCalledEvents;\n requestId = flagsResponse.requestId;\n evaluatedAt = flagsResponse.evaluatedAt;\n const errors = [];\n if (flagsResponse.errorsWhileComputingFlags) errors.push(FeatureFlagError.ERRORS_WHILE_COMPUTING);\n if (flagsResponse.quotaLimited?.includes('feature_flags')) errors.push(FeatureFlagError.QUOTA_LIMITED);\n const flagDetail = flagsResponse.flags[key];\n if (void 0 === flagDetail) errors.push(FeatureFlagError.FLAG_MISSING);\n else {\n flagId = flagDetail.metadata?.id;\n flagVersion = flagDetail.metadata?.version;\n flagReason = flagDetail.reason?.description ?? flagDetail.reason?.code;\n flagHasExperiment = flagDetail.metadata?.has_experiment;\n let parsedPayload;\n if (flagDetail.metadata?.payload !== void 0) try {\n parsedPayload = JSON.parse(flagDetail.metadata.payload);\n } catch {\n parsedPayload = flagDetail.metadata.payload;\n }\n result = {\n key,\n enabled: flagDetail.enabled,\n variant: flagDetail.variant,\n payload: parsedPayload\n };\n }\n if (errors.length > 0) featureFlagError = errors.join(',');\n }\n }\n if (sendFeatureFlagEvents) {\n const response = void 0 === result ? void 0 : false === result.enabled ? false : result.variant ?? true;\n const properties = {\n $feature_flag: key,\n $feature_flag_response: response,\n $feature_flag_id: flagId,\n $feature_flag_version: flagVersion,\n $feature_flag_reason: flagReason,\n locally_evaluated: flagWasLocallyEvaluated,\n [`$feature/${key}`]: response,\n $feature_flag_request_id: requestId,\n $feature_flag_evaluated_at: flagWasLocallyEvaluated ? Date.now() : evaluatedAt\n };\n if (void 0 !== flagHasExperiment) properties.$feature_flag_has_experiment = flagHasExperiment;\n if (flagWasLocallyEvaluated && this.featureFlagsPoller) {\n const flagDefinitionsLoadedAt = this.featureFlagsPoller.getFlagDefinitionsLoadedAt();\n if (void 0 !== flagDefinitionsLoadedAt) properties.$feature_flag_definitions_loaded_at = flagDefinitionsLoadedAt;\n }\n if (featureFlagError) properties.$feature_flag_error = featureFlagError;\n this._captureFlagCalledEventIfNeeded({\n distinctId,\n key,\n response,\n groups,\n disableGeoip,\n properties\n });\n }\n if (void 0 !== result && void 0 !== this._payloadOverrides && key in this._payloadOverrides) result = {\n ...result,\n payload: this._payloadOverrides[key]\n };\n return result;\n }\n async getFeatureFlag(key, distinctId, options) {\n emitDeprecationWarningOnce('getFeatureFlag', \"`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.\");\n const result = await this._getFeatureFlagResult(key, distinctId, {\n ...options,\n sendFeatureFlagEvents: options?.sendFeatureFlagEvents ?? this.options.sendFeatureFlagEvent ?? true\n });\n if (void 0 === result) return;\n if (false === result.enabled) return false;\n return result.variant ?? true;\n }\n async getFeatureFlagPayload(key, distinctId, matchValue, options) {\n emitDeprecationWarningOnce('getFeatureFlagPayload', \"`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.\");\n if (void 0 !== this._payloadOverrides && key in this._payloadOverrides) return this._payloadOverrides[key];\n const result = await this._getFeatureFlagResult(key, distinctId, {\n ...options,\n sendFeatureFlagEvents: false\n }, matchValue);\n if (void 0 === result) return;\n return result.payload ?? null;\n }\n async getFeatureFlagResult(key, distinctIdOrOptions, options) {\n const { distinctId: resolvedDistinctId, options: resolvedOptions } = this._resolveDistinctId(distinctIdOrOptions, options);\n if (!resolvedDistinctId) return void this._logger.warn(\"[PostHog] distinctId is required \\u2014 pass it explicitly or use withContext()\");\n return this._getFeatureFlagResult(key, resolvedDistinctId, {\n ...resolvedOptions,\n sendFeatureFlagEvents: resolvedOptions?.sendFeatureFlagEvents ?? this.options.sendFeatureFlagEvent ?? true\n });\n }\n async getRemoteConfigPayload(flagKey) {\n if (this.disabled) return void this._logger.warn('The client is disabled');\n if (!this.options.personalApiKey) throw new Error('Personal API key is required for remote config payload decryption');\n const response = await this._requestRemoteConfigPayload(flagKey);\n if (!response) return;\n const parsed = await response.json();\n if ('string' == typeof parsed) try {\n return JSON.parse(parsed);\n } catch (e) {}\n return parsed;\n }\n async isFeatureEnabled(key, distinctId, options) {\n emitDeprecationWarningOnce('isFeatureEnabled', \"`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.\");\n const result = await this._getFeatureFlagResult(key, distinctId, {\n ...options,\n sendFeatureFlagEvents: options?.sendFeatureFlagEvents ?? this.options.sendFeatureFlagEvent ?? true\n });\n if (void 0 === result) return;\n if (false === result.enabled) return false;\n const feat = result.variant ?? true;\n return !!feat || false;\n }\n async getAllFlags(distinctIdOrOptions, options) {\n const { distinctId: resolvedDistinctId, options: resolvedOptions } = this._resolveDistinctId(distinctIdOrOptions, options);\n if (!resolvedDistinctId) {\n this._logger.warn(\"[PostHog] distinctId is required to get feature flags \\u2014 pass it explicitly or use withContext()\");\n return {};\n }\n const response = await this.getAllFlagsAndPayloads(resolvedDistinctId, resolvedOptions);\n return response.featureFlags || {};\n }\n async getAllFlagsAndPayloads(distinctIdOrOptions, options) {\n const { distinctId: resolvedDistinctId, options: resolvedOptions } = this._resolveDistinctId(distinctIdOrOptions, options);\n if (!resolvedDistinctId) {\n this._logger.warn(\"[PostHog] distinctId is required to get feature flags and payloads \\u2014 pass it explicitly or use withContext()\");\n return {\n featureFlags: {},\n featureFlagPayloads: {}\n };\n }\n if (this.disabled) {\n this._logger.warn('The client is disabled');\n return {\n featureFlags: {},\n featureFlagPayloads: {}\n };\n }\n const { groups, disableGeoip, flagKeys } = resolvedOptions || {};\n let { onlyEvaluateLocally, personProperties, groupProperties } = resolvedOptions || {};\n const adjustedProperties = this.addLocalPersonAndGroupProperties(resolvedDistinctId, groups, personProperties, groupProperties);\n personProperties = adjustedProperties.allPersonProperties;\n groupProperties = adjustedProperties.allGroupProperties;\n const evaluationContext = this.createFeatureFlagEvaluationContext(resolvedDistinctId, groups, this.personPropertiesForLocalEvaluation(resolvedDistinctId, personProperties), groupProperties);\n if (void 0 == onlyEvaluateLocally) onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;\n const localEvaluationResult = await this.featureFlagsPoller?.getAllFlagsAndPayloads(evaluationContext, flagKeys);\n let featureFlags = {};\n let featureFlagPayloads = {};\n let fallbackToFlags = true;\n if (localEvaluationResult) {\n featureFlags = localEvaluationResult.response;\n featureFlagPayloads = localEvaluationResult.payloads;\n fallbackToFlags = localEvaluationResult.fallbackToFlags;\n }\n if (fallbackToFlags && !onlyEvaluateLocally) {\n const remoteEvaluationResult = await super.getFeatureFlagsAndPayloadsStateless(evaluationContext.distinctId, evaluationContext.groups, personProperties, groupProperties, disableGeoip, flagKeys);\n featureFlags = {\n ...featureFlags,\n ...remoteEvaluationResult.flags || {}\n };\n featureFlagPayloads = {\n ...featureFlagPayloads,\n ...remoteEvaluationResult.payloads || {}\n };\n }\n if (void 0 !== this._flagOverrides) featureFlags = {\n ...featureFlags,\n ...this._flagOverrides\n };\n if (void 0 !== this._payloadOverrides) featureFlagPayloads = {\n ...featureFlagPayloads,\n ...this._payloadOverrides\n };\n return {\n featureFlags,\n featureFlagPayloads\n };\n }\n async evaluateFlags(distinctIdOrOptions, options) {\n const { distinctId: resolvedDistinctId, options: resolvedOptions } = this._resolveDistinctId(distinctIdOrOptions, options);\n if (!resolvedDistinctId) {\n this._logger.warn(\"[PostHog] distinctId is required to evaluate feature flags \\u2014 pass it explicitly or use withContext()\");\n return new FeatureFlagEvaluations({\n host: this._getFeatureFlagEvaluationsHost(),\n distinctId: '',\n flags: {}\n });\n }\n if (this.disabled) {\n this._logger.warn('The client is disabled');\n return new FeatureFlagEvaluations({\n host: this._getFeatureFlagEvaluationsHost(),\n distinctId: resolvedDistinctId,\n flags: {}\n });\n }\n const { groups, disableGeoip, flagKeys } = resolvedOptions || {};\n let { onlyEvaluateLocally, personProperties, groupProperties } = resolvedOptions || {};\n const adjustedProperties = this.addLocalPersonAndGroupProperties(resolvedDistinctId, groups, personProperties, groupProperties);\n personProperties = adjustedProperties.allPersonProperties;\n groupProperties = adjustedProperties.allGroupProperties;\n const evaluationContext = this.createFeatureFlagEvaluationContext(resolvedDistinctId, groups, this.personPropertiesForLocalEvaluation(resolvedDistinctId, personProperties), groupProperties);\n if (void 0 == onlyEvaluateLocally) onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;\n const records = {};\n let requestId;\n let evaluatedAt;\n let errorsWhileComputing = false;\n let quotaLimited = false;\n const localResult = await this.featureFlagsPoller?.getAllFlagsAndPayloads(evaluationContext, flagKeys);\n const locallyEvaluatedKeys = new Set();\n if (localResult) for (const [key, value] of Object.entries(localResult.response)){\n const flagDef = this.featureFlagsPoller?.featureFlagsByKey[key];\n records[key] = {\n key,\n enabled: false !== value,\n variant: 'string' == typeof value ? value : void 0,\n payload: localResult.payloads[key],\n id: flagDef?.id,\n version: void 0,\n reason: 'Evaluated locally',\n locallyEvaluated: true,\n hasExperiment: flagDef?.has_experiment\n };\n locallyEvaluatedKeys.add(key);\n }\n const fallbackToFlags = localResult ? localResult.fallbackToFlags : true;\n if (fallbackToFlags && !onlyEvaluateLocally) {\n const details = await super.getFeatureFlagDetailsStateless(evaluationContext.distinctId, evaluationContext.groups, personProperties, groupProperties, disableGeoip, flagKeys);\n if (details) {\n this._minimalFlagCalledEvents = true === details.minimalFlagCalledEvents;\n requestId = details.requestId;\n evaluatedAt = details.evaluatedAt;\n errorsWhileComputing = Boolean(details.errorsWhileComputingFlags);\n quotaLimited = Array.isArray(details.quotaLimited) && details.quotaLimited.includes('feature_flags');\n for (const [key, detail] of Object.entries(details.flags)){\n if (locallyEvaluatedKeys.has(key)) continue;\n let parsedPayload;\n if (detail.metadata?.payload !== void 0) try {\n parsedPayload = JSON.parse(detail.metadata.payload);\n } catch {\n parsedPayload = detail.metadata.payload;\n }\n records[key] = {\n key,\n enabled: detail.enabled,\n variant: detail.variant,\n payload: parsedPayload,\n id: detail.metadata?.id,\n version: detail.metadata?.version,\n reason: detail.reason?.description ?? detail.reason?.code,\n locallyEvaluated: false,\n hasExperiment: detail.metadata?.has_experiment\n };\n }\n }\n }\n if (void 0 !== this._flagOverrides) for (const [key, value] of Object.entries(this._flagOverrides)){\n if (void 0 === value) {\n delete records[key];\n continue;\n }\n const existing = records[key];\n records[key] = {\n key,\n enabled: false !== value,\n variant: 'string' == typeof value ? value : void 0,\n payload: existing?.payload,\n id: existing?.id,\n version: existing?.version,\n reason: existing?.reason,\n locallyEvaluated: existing?.locallyEvaluated ?? false,\n hasExperiment: existing?.hasExperiment\n };\n }\n if (void 0 !== this._payloadOverrides) for (const [key, payload] of Object.entries(this._payloadOverrides)){\n const existing = records[key];\n if (existing) records[key] = {\n ...existing,\n payload\n };\n }\n return new FeatureFlagEvaluations({\n host: this._getFeatureFlagEvaluationsHost(),\n distinctId: resolvedDistinctId,\n groups,\n disableGeoip,\n flags: records,\n requestId,\n evaluatedAt,\n flagDefinitionsLoadedAt: this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),\n errorsWhileComputing,\n quotaLimited\n });\n }\n _shouldSendMinimalFlagCalledEvent(event, properties) {\n return '$feature_flag_called' === event && this._minimalFlagCalledEvents && false === properties.$feature_flag_has_experiment;\n }\n _captureFlagCalledEventIfNeeded(params) {\n const { distinctId, key, response, groups, disableGeoip, properties } = params;\n const groupSuffix = groups && Object.keys(groups).length > 0 ? `_${JSON.stringify(Object.entries(groups).sort(([a], [b])=>a < b ? -1 : a > b ? 1 : 0))}` : '';\n const featureFlagReportedKey = `${key}_${response}${groupSuffix}`;\n if (distinctId in this.distinctIdHasSentFlagCalls && this.distinctIdHasSentFlagCalls[distinctId].has(featureFlagReportedKey)) return;\n if (Object.keys(this.distinctIdHasSentFlagCalls).length >= this.maxCacheSize) this.distinctIdHasSentFlagCalls = {};\n if (this.distinctIdHasSentFlagCalls[distinctId] instanceof Set) this.distinctIdHasSentFlagCalls[distinctId].add(featureFlagReportedKey);\n else this.distinctIdHasSentFlagCalls[distinctId] = new Set([\n featureFlagReportedKey\n ]);\n this.capture({\n distinctId,\n event: '$feature_flag_called',\n properties,\n groups,\n disableGeoip\n });\n }\n _getFeatureFlagEvaluationsHost() {\n if (!this._featureFlagEvaluationsHost) this._featureFlagEvaluationsHost = {\n captureFlagCalledEventIfNeeded: (params)=>this._captureFlagCalledEventIfNeeded(params),\n logWarning: (message)=>{\n if (false !== this.options.featureFlagsLogWarnings) console.warn(`[PostHog] ${message}`);\n }\n };\n return this._featureFlagEvaluationsHost;\n }\n groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip }) {\n this._sendPreparedEvent('capture', {\n distinctId: distinctId || `$${groupType}_${groupKey}`,\n event: '$groupidentify',\n properties: {\n $group_type: groupType,\n $group_key: groupKey,\n $group_set: properties || {}\n },\n disableGeoip\n }, false, {\n includeContextProperties: false\n });\n }\n async groupIdentifyImmediate({ groupType, groupKey, properties, distinctId, disableGeoip }) {\n await this._sendPreparedEvent('capture', {\n distinctId: distinctId || `$${groupType}_${groupKey}`,\n event: '$groupidentify',\n properties: {\n $group_type: groupType,\n $group_key: groupKey,\n $group_set: properties || {}\n },\n disableGeoip\n }, true, {\n includeContextProperties: false\n });\n }\n async reloadFeatureFlags() {\n await this.featureFlagsPoller?.loadFeatureFlags(true);\n }\n overrideFeatureFlags(overrides) {\n const flagArrayToRecord = (flags)=>Object.fromEntries(flags.map((f)=>[\n f,\n true\n ]));\n if (false === overrides) {\n this._flagOverrides = void 0;\n this._payloadOverrides = void 0;\n return;\n }\n if (Array.isArray(overrides)) {\n this._flagOverrides = flagArrayToRecord(overrides);\n return;\n }\n if (this._isFeatureFlagOverrideOptions(overrides)) {\n if ('flags' in overrides) {\n if (false === overrides.flags) this._flagOverrides = void 0;\n else if (Array.isArray(overrides.flags)) this._flagOverrides = flagArrayToRecord(overrides.flags);\n else if (void 0 !== overrides.flags) this._flagOverrides = {\n ...overrides.flags\n };\n }\n if ('payloads' in overrides) {\n if (false === overrides.payloads) this._payloadOverrides = void 0;\n else if (void 0 !== overrides.payloads) this._payloadOverrides = {\n ...overrides.payloads\n };\n }\n return;\n }\n this._flagOverrides = {\n ...overrides\n };\n }\n _isFeatureFlagOverrideOptions(overrides) {\n if ('object' != typeof overrides || null === overrides || Array.isArray(overrides)) return false;\n const obj = overrides;\n if ('flags' in obj) {\n const flagsValue = obj['flags'];\n if (false === flagsValue || Array.isArray(flagsValue) || 'object' == typeof flagsValue && null !== flagsValue) return true;\n }\n if ('payloads' in obj) {\n const payloadsValue = obj['payloads'];\n if (false === payloadsValue || 'object' == typeof payloadsValue && null !== payloadsValue) return true;\n }\n return false;\n }\n withContext(data, fn, options) {\n if (!this.context) return fn();\n return this.context.run(data, fn, options);\n }\n getContext() {\n return this.context?.get();\n }\n enterContext(data, options) {\n this.context?.enter(data, options);\n }\n async _shutdown(shutdownTimeoutMs) {\n const shutdownDeadlineMs = Date.now() + (shutdownTimeoutMs ?? 30000);\n const resolve = this._consumeWaitUntilCycle();\n await this.featureFlagsPoller?.stopPoller(shutdownTimeoutMs);\n this.errorTracking.shutdown();\n if (this._metrics) {\n await Promise.race([\n this._metrics.flush().catch(()=>{}),\n new Promise((resolve)=>safeSetTimeout(resolve, Math.max(0, shutdownDeadlineMs - Date.now())))\n ]);\n this._metrics.reset();\n }\n try {\n return await super._shutdown(Math.max(0, shutdownDeadlineMs - Date.now()));\n } finally{\n this.distinctIdHasSentFlagCalls = {};\n resolve?.();\n }\n }\n async _requestRemoteConfigPayload(flagKey) {\n if (this.disabled || !this.apiKey || !this.options.personalApiKey) return;\n const url = `${this.host}/api/projects/@current/feature_flags/${flagKey}/remote_config?token=${encodeURIComponent(this.apiKey)}`;\n const options = {\n method: 'GET',\n headers: {\n ...this.getCustomHeaders(),\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.options.personalApiKey}`\n }\n };\n let abortTimeout = null;\n if (this.options.requestTimeout && 'number' == typeof this.options.requestTimeout) {\n const controller = new AbortController();\n abortTimeout = safeSetTimeout(()=>{\n controller.abort();\n }, this.options.requestTimeout);\n options.signal = controller.signal;\n }\n try {\n return await this.fetch(url, options);\n } catch (error) {\n this._events.emit('error', error);\n return;\n } finally{\n if (abortTimeout) clearTimeout(abortTimeout);\n }\n }\n extractPropertiesFromEvent(eventProperties, groups) {\n if (!eventProperties) return {\n personProperties: {},\n groupProperties: {}\n };\n const personProperties = {};\n const groupProperties = {};\n for (const [key, value] of Object.entries(eventProperties))if (isPlainObject(value) && groups && key in groups) {\n const groupProps = {};\n for (const [groupKey, groupValue] of Object.entries(value))groupProps[String(groupKey)] = String(groupValue);\n groupProperties[String(key)] = groupProps;\n } else personProperties[String(key)] = String(value);\n return {\n personProperties,\n groupProperties\n };\n }\n async getFeatureFlagsForEvent(distinctId, groups, disableGeoip, sendFeatureFlagsOptions) {\n if (this.disabled || !this.apiKey) return void this._logger.warn('The client is disabled');\n const finalPersonProperties = sendFeatureFlagsOptions?.personProperties || {};\n const finalGroupProperties = sendFeatureFlagsOptions?.groupProperties || {};\n const flagKeys = sendFeatureFlagsOptions?.flagKeys;\n const onlyEvaluateLocally = sendFeatureFlagsOptions?.onlyEvaluateLocally ?? this.options.strictLocalEvaluation ?? false;\n if (onlyEvaluateLocally) if (!((this.featureFlagsPoller?.featureFlags?.length || 0) > 0)) return {};\n else {\n const groupsWithStringValues = {};\n for (const [key, value] of Object.entries(groups || {}))groupsWithStringValues[key] = String(value);\n return await this.getAllFlags(distinctId, {\n groups: groupsWithStringValues,\n personProperties: finalPersonProperties,\n groupProperties: finalGroupProperties,\n disableGeoip,\n onlyEvaluateLocally: true,\n flagKeys\n });\n }\n if ((this.featureFlagsPoller?.featureFlags?.length || 0) > 0) {\n const groupsWithStringValues = {};\n for (const [key, value] of Object.entries(groups || {}))groupsWithStringValues[key] = String(value);\n return await this.getAllFlags(distinctId, {\n groups: groupsWithStringValues,\n personProperties: finalPersonProperties,\n groupProperties: finalGroupProperties,\n disableGeoip,\n onlyEvaluateLocally: true,\n flagKeys\n });\n }\n return (await super.getFeatureFlagsStateless(distinctId, groups, finalPersonProperties, finalGroupProperties, disableGeoip)).flags;\n }\n addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties) {\n const allPersonProperties = {\n ...personProperties || {}\n };\n const allGroupProperties = {};\n if (groups) for (const groupName of Object.keys(groups))allGroupProperties[groupName] = {\n $group_key: groups[groupName],\n ...groupProperties?.[groupName] || {}\n };\n return {\n allPersonProperties,\n allGroupProperties\n };\n }\n personPropertiesForLocalEvaluation(distinctId, personProperties) {\n return {\n distinct_id: distinctId,\n ...personProperties || {}\n };\n }\n createFeatureFlagEvaluationContext(distinctId, groups, personProperties, groupProperties) {\n return {\n distinctId,\n groups: groups || {},\n personProperties: personProperties || {},\n groupProperties: groupProperties || {},\n evaluationCache: {}\n };\n }\n captureException(error, distinctId, additionalProperties, uuid, flags) {\n if (!error_tracking.isPreviouslyCapturedError(error)) {\n const syntheticException = new Error('PostHog syntheticException');\n this.addPendingPromise(error_tracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {\n syntheticException\n }, distinctId, additionalProperties).then((msg)=>this._capturePreparedEvent({\n ...msg,\n uuid,\n flags\n }, false)));\n }\n }\n async captureExceptionImmediate(error, distinctId, additionalProperties, flags) {\n if (!error_tracking.isPreviouslyCapturedError(error)) {\n const syntheticException = new Error('PostHog syntheticException');\n return this.addPendingPromise(error_tracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {\n syntheticException\n }, distinctId, additionalProperties).then((msg)=>this.captureImmediate({\n ...msg,\n flags\n })));\n }\n }\n async prepareEventMessage(props) {\n return this._prepareEventMessage(props);\n }\n async _prepareEventMessage(props, options = {}) {\n const { distinctId, event, properties, groups, flags, sendFeatureFlags, timestamp, disableGeoip, uuid } = props;\n const contextData = this.context?.get();\n const includeContextProperties = options.includeContextProperties ?? true;\n let mergedDistinctId = distinctId || contextData?.distinctId;\n const mergedProperties = includeContextProperties ? {\n ...this.props,\n ...contextData?.properties || {},\n ...properties || {}\n } : {\n ...properties || {}\n };\n if (!mergedDistinctId) {\n mergedDistinctId = uuidv7();\n mergedProperties.$process_person_profile = false;\n }\n if (includeContextProperties && contextData?.sessionId && !mergedProperties.$session_id) mergedProperties.$session_id = contextData.sessionId;\n const finalProperties = this._shouldSendMinimalFlagCalledEvent(event, mergedProperties) ? minimizeFlagCalledEventProperties(mergedProperties) : mergedProperties;\n const eventMessage = this._runBeforeSend({\n distinctId: mergedDistinctId,\n event,\n properties: finalProperties,\n groups,\n flags,\n sendFeatureFlags,\n timestamp,\n disableGeoip,\n uuid\n });\n if (!eventMessage) return Promise.reject(null);\n const eventProperties = await Promise.resolve().then(async ()=>{\n if (flags) {\n if (sendFeatureFlags) console.warn('[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.');\n return flags._getEventProperties();\n }\n if (sendFeatureFlags) {\n emitDeprecationWarningOnce('sendFeatureFlags', \"`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead — it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.\");\n const sendFeatureFlagsOptions = 'object' == typeof sendFeatureFlags ? sendFeatureFlags : void 0;\n const flagValues = await this.getFeatureFlagsForEvent(eventMessage.distinctId, groups, disableGeoip, sendFeatureFlagsOptions);\n return buildFlagEventProperties(flagValues);\n }\n return {};\n }).catch(()=>({})).then((additionalProperties)=>{\n const resolvedGroups = eventMessage.groups || groups;\n return {\n ...additionalProperties,\n ...eventMessage.properties || {},\n ...void 0 !== resolvedGroups && Object.keys(resolvedGroups).length > 0 ? {\n $groups: resolvedGroups\n } : {}\n };\n });\n if ('$pageview' === eventMessage.event && this.options.__preview_capture_bot_pageviews && 'string' == typeof eventProperties.$raw_user_agent) {\n if (isBlockedUA(eventProperties.$raw_user_agent, this.options.custom_blocked_useragents || [])) {\n eventMessage.event = '$bot_pageview';\n eventProperties.$browser_type = 'bot';\n }\n }\n return {\n distinctId: eventMessage.distinctId,\n event: eventMessage.event,\n properties: eventProperties,\n options: {\n timestamp: eventMessage.timestamp,\n disableGeoip: eventMessage.disableGeoip,\n uuid: eventMessage.uuid\n }\n };\n }\n _runBeforeSend(eventMessage) {\n const beforeSend = this.options.before_send;\n if (!beforeSend) return eventMessage;\n const fns = Array.isArray(beforeSend) ? beforeSend : [\n beforeSend\n ];\n let result = eventMessage;\n for (const fn of fns){\n result = fn(result);\n if (!result) {\n this._logger.info(`Event '${eventMessage.event}' was rejected in beforeSend function`);\n return null;\n }\n if (!result.properties || 0 === Object.keys(result.properties).length) {\n const message = `Event '${result.event}' has no properties after beforeSend function, this is likely an error.`;\n this._logger.warn(message);\n }\n }\n return result;\n }\n}\nexport { PostHogBackendClient, _resetDeprecationWarningsForTests };\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nclass PostHogContext {\n constructor(){\n this.storage = new AsyncLocalStorage();\n }\n get() {\n return this.storage.getStore();\n }\n run(context, fn, options) {\n return this.storage.run(this.resolve(context, options), fn);\n }\n enter(context, options) {\n this.storage.enterWith(this.resolve(context, options));\n }\n resolve(context, options) {\n if (options?.fresh === true) return context;\n const current = this.get() || {};\n return {\n distinctId: context.distinctId ?? current.distinctId,\n sessionId: context.sessionId ?? current.sessionId,\n properties: {\n ...current.properties || {},\n ...context.properties || {}\n }\n };\n }\n}\nexport { PostHogContext };\n","const NAME = 'posthog-node';\nfunction createEventProcessor(_posthog, { organization, projectId, prefix, severityAllowList = [\n 'error'\n], sendExceptionsToPostHog = true } = {}) {\n return (event)=>{\n const shouldProcessLevel = '*' === severityAllowList || severityAllowList.includes(event.level);\n if (!shouldProcessLevel) return event;\n if (!event.tags) event.tags = {};\n const userId = event.tags[PostHogSentryIntegration.POSTHOG_ID_TAG];\n if (void 0 === userId) return event;\n const uiHost = _posthog.options.host ?? 'https://us.i.posthog.com';\n const personUrl = new URL(`/project/${_posthog.apiKey}/person/${userId}`, uiHost).toString();\n event.tags['PostHog Person URL'] = personUrl;\n const exceptions = event.exception?.values || [];\n const exceptionList = exceptions.map((exception)=>({\n ...exception,\n stacktrace: exception.stacktrace ? {\n ...exception.stacktrace,\n type: 'raw',\n frames: (exception.stacktrace.frames || []).map((frame)=>({\n ...frame,\n platform: \"node:javascript\"\n }))\n } : void 0\n }));\n const properties = {\n $exception_message: exceptions[0]?.value || event.message,\n $exception_type: exceptions[0]?.type,\n $exception_level: event.level,\n $exception_list: exceptionList,\n $sentry_event_id: event.event_id,\n $sentry_exception: event.exception,\n $sentry_exception_message: exceptions[0]?.value || event.message,\n $sentry_exception_type: exceptions[0]?.type,\n $sentry_tags: event.tags\n };\n if (organization && projectId) properties['$sentry_url'] = (prefix || 'https://sentry.io/organizations/') + organization + '/issues/?project=' + projectId + '&query=' + event.event_id;\n if (sendExceptionsToPostHog) _posthog.capture({\n event: '$exception',\n distinctId: userId,\n properties\n });\n return event;\n };\n}\nfunction sentryIntegration(_posthog, options) {\n const processor = createEventProcessor(_posthog, options);\n return {\n name: NAME,\n processEvent (event) {\n return processor(event);\n }\n };\n}\nclass PostHogSentryIntegration {\n static #_ = this.POSTHOG_ID_TAG = 'posthog_distinct_id';\n constructor(_posthog, organization, prefix, severityAllowList, sendExceptionsToPostHog){\n this.name = NAME;\n this.name = NAME;\n this.setupOnce = function(addGlobalEventProcessor, getCurrentHub) {\n const projectId = getCurrentHub()?.getClient()?.getDsn()?.projectId;\n addGlobalEventProcessor(createEventProcessor(_posthog, {\n organization,\n projectId,\n prefix,\n severityAllowList,\n sendExceptionsToPostHog: sendExceptionsToPostHog ?? true\n }));\n };\n }\n}\nexport { PostHogSentryIntegration, createEventProcessor, sentryIntegration };\n","import { stripUrlHash } from \"@posthog/core\";\nfunction normalizeRequestCurrentUrl(currentUrl, disableCaptureUrlHashes) {\n return disableCaptureUrlHashes ? stripUrlHash(currentUrl) : currentUrl;\n}\nfunction normalizeRequestPath(path, disableCaptureUrlHashes) {\n const pathWithoutSearch = stripUrlSearch(path);\n return disableCaptureUrlHashes ? stripUrlHash(pathWithoutSearch) : pathWithoutSearch;\n}\nfunction stripUrlSearch(url) {\n if (!url) return url;\n const searchIndex = url.indexOf('?');\n const hashIndex = url.indexOf('#');\n if (-1 === searchIndex || -1 !== hashIndex && hashIndex < searchIndex) return url;\n return `${url.slice(0, searchIndex)}${-1 === hashIndex ? '' : url.slice(hashIndex)}`;\n}\nexport { normalizeRequestCurrentUrl, normalizeRequestPath };\n","import error_tracking from \"./error-tracking/index.mjs\";\nimport { addProperty, getFirstHeaderValue, getPostHogTracingHeaderValues } from \"./tracing-headers.mjs\";\nimport { normalizeRequestCurrentUrl, normalizeRequestPath } from \"./url-utils.mjs\";\nfunction getClientIp(req) {\n const forwarded = getFirstHeaderValue(req.headers['x-forwarded-for']);\n if (forwarded) {\n const ip = forwarded.split(',')[0].trim();\n if (ip) return ip;\n }\n return req.socket?.remoteAddress;\n}\nfunction buildRequestContextData(posthog, req) {\n const { sessionId, distinctId } = getPostHogTracingHeaderValues(req.headers);\n const properties = {};\n const disableCaptureUrlHashes = true === posthog.options.disable_capture_url_hashes;\n addProperty(properties, '$current_url', normalizeRequestCurrentUrl(req.originalUrl || req.url, disableCaptureUrlHashes));\n addProperty(properties, '$request_method', req.method);\n addProperty(properties, '$request_path', normalizeRequestPath(req.path, disableCaptureUrlHashes));\n addProperty(properties, '$user_agent', getFirstHeaderValue(req.headers['user-agent']));\n addProperty(properties, '$ip', getClientIp(req));\n return {\n ...void 0 !== sessionId ? {\n sessionId\n } : {},\n ...void 0 !== distinctId ? {\n distinctId\n } : {},\n properties\n };\n}\nfunction setupExpressRequestContext(_posthog, app) {\n app.use(posthogRequestContext(_posthog));\n}\nfunction posthogRequestContext(posthog) {\n return (req, _res, next)=>{\n posthog.withContext(buildRequestContextData(posthog, req), ()=>next());\n };\n}\nfunction setupExpressErrorHandler(_posthog, app) {\n app.use(posthogErrorHandler(_posthog));\n}\nfunction posthogErrorHandler(posthog) {\n return (error, req, res, next)=>{\n if (error_tracking.isPreviouslyCapturedError(error)) return void next(error);\n const contextData = buildRequestContextData(posthog, req);\n const syntheticException = new Error('Synthetic exception');\n const hint = {\n mechanism: {\n type: 'middleware',\n handled: false\n },\n syntheticException\n };\n const additionalProperties = {\n ...void 0 !== contextData.sessionId ? {\n $session_id: contextData.sessionId\n } : {},\n ...contextData.properties || {},\n $response_status_code: res.statusCode\n };\n posthog.addPendingPromise(error_tracking.buildEventMessage(posthog.getErrorPropertiesBuilder(), error, hint, contextData.distinctId, additionalProperties).then((msg)=>posthog._capturePreparedEvent(msg, false)));\n next(error);\n };\n}\nexport { setupExpressErrorHandler, setupExpressRequestContext };\n","import { FeatureFlagEvaluations } from \"./feature-flag-evaluations.mjs\";\nimport { FeatureFlagError, cookieStateToProperties, cookieStoreFromHeader, getPostHogCookieName, parsePostHogCookie, readPostHogCookie, serializePostHogCookie, uuidv7 } from \"@posthog/core\";\nexport * from \"./extensions/sentry-integration.mjs\";\nexport * from \"./extensions/express.mjs\";\nexport * from \"./types.mjs\";\nexport { FeatureFlagError, FeatureFlagEvaluations, cookieStateToProperties, cookieStoreFromHeader, getPostHogCookieName, parsePostHogCookie, readPostHogCookie, serializePostHogCookie, uuidv7 };\n","import { createModulerModifier } from \"../extensions/error-tracking/modifiers/module.node.mjs\";\nimport { addSourceContext } from \"../extensions/error-tracking/modifiers/context-lines.node.mjs\";\nimport { createRelativePathModifier } from \"../extensions/error-tracking/modifiers/relative-path.node.mjs\";\nimport { PostHogBackendClient } from \"../client.mjs\";\nimport { ErrorTracking } from \"@posthog/core\";\nimport { PostHogContext } from \"../extensions/context/context.mjs\";\nexport * from \"../exports.mjs\";\nclass PostHog extends PostHogBackendClient {\n getLibraryId() {\n return 'posthog-node';\n }\n initializeContext() {\n return new PostHogContext();\n }\n createErrorPropertiesBuilder() {\n return new ErrorTracking.ErrorPropertiesBuilder([\n new ErrorTracking.EventCoercer(),\n new ErrorTracking.ErrorCoercer(),\n new ErrorTracking.ObjectCoercer(),\n new ErrorTracking.StringCoercer(),\n new ErrorTracking.PrimitiveCoercer()\n ], ErrorTracking.createStackParser(\"node:javascript\", ErrorTracking.nodeStackLineParser), [\n createModulerModifier(),\n addSourceContext,\n createRelativePathModifier()\n ]);\n }\n}\nexport { PostHog };\n","import { loadConfigSync } from '../config-yaml.js';\n\nexport function telemetryEnvironmentForcesOff(): boolean {\n const envValue = process.env.OVERDECK_TELEMETRY?.trim().toLowerCase();\n return envValue === '0' || envValue === 'false';\n}\n\nexport function resolveTelemetryEnabled(): boolean {\n if (telemetryEnvironmentForcesOff()) return false;\n return loadConfigSync().config.telemetry?.enabled !== false;\n}\n","import { randomUUID } from 'node:crypto';\nimport {\n chmodSync,\n mkdirSync,\n readFileSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from 'node:fs';\nimport { join } from 'node:path';\nimport { getOverdeckHome } from '../paths.js';\n\nconst INSTALL_ID_FILE = 'telemetry-id';\nconst INSTALL_ID_REPAIR_LOCK = 'telemetry-id.repair.lock';\nconst REPAIR_WAIT_MS = 10;\nconst REPAIR_LOCK_LEASE_MS = 1_000;\nconst REPAIR_MAX_ATTEMPTS = 200;\nconst REPAIR_WAIT_ARRAY = new Int32Array(new SharedArrayBuffer(4));\nconst UUID_V4_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\nfunction readValidInstallId(path: string): string | null {\n const installId = readFileSync(path, 'utf8').trim();\n return UUID_V4_PATTERN.test(installId) ? installId : null;\n}\n\nfunction errorCode(error: unknown): string | undefined {\n return error instanceof Error && 'code' in error\n ? String(error.code)\n : undefined;\n}\n\nfunction repairOwnerIsAlive(lockPath: string): boolean {\n try {\n const rawOwner = readFileSync(lockPath, 'utf8').trim();\n let ownerPid: number;\n let createdAt: number;\n try {\n const owner = JSON.parse(rawOwner) as { pid?: unknown; createdAt?: unknown };\n ownerPid = Number(owner.pid);\n createdAt = Number(owner.createdAt);\n } catch {\n ownerPid = Number(rawOwner);\n createdAt = statSync(lockPath).mtimeMs;\n }\n if (\n !Number.isInteger(ownerPid) ||\n ownerPid <= 0 ||\n !Number.isFinite(createdAt) ||\n Date.now() - createdAt >= REPAIR_LOCK_LEASE_MS\n ) return false;\n process.kill(ownerPid, 0);\n return true;\n } catch (error) {\n return errorCode(error) === 'EPERM';\n }\n}\n\nfunction replaceInvalidInstallId(path: string): void {\n const installId = randomUUID();\n const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;\n try {\n writeFileSync(temporaryPath, `${installId}\\n`, {\n encoding: 'utf8',\n mode: 0o600,\n flag: 'wx',\n });\n renameSync(temporaryPath, path);\n chmodSync(path, 0o600);\n } finally {\n rmSync(temporaryPath, { force: true });\n }\n}\n\nfunction repairInvalidInstallId(path: string, overdeckHome: string): string {\n const lockPath = join(overdeckHome, INSTALL_ID_REPAIR_LOCK);\n for (let attempt = 0; attempt < REPAIR_MAX_ATTEMPTS; attempt += 1) {\n try {\n writeFileSync(lockPath, `${JSON.stringify({\n pid: process.pid,\n createdAt: Date.now(),\n })}\\n`, {\n encoding: 'utf8',\n mode: 0o600,\n flag: 'wx',\n });\n } catch (error) {\n if (errorCode(error) !== 'EEXIST') throw error;\n const winner = readValidInstallId(path);\n if (winner) return winner;\n if (!repairOwnerIsAlive(lockPath)) {\n rmSync(lockPath, { force: true });\n continue;\n }\n Atomics.wait(REPAIR_WAIT_ARRAY, 0, 0, REPAIR_WAIT_MS);\n continue;\n }\n\n try {\n const winner = readValidInstallId(path);\n if (winner) return winner;\n replaceInvalidInstallId(path);\n const repaired = readValidInstallId(path);\n if (!repaired) throw new Error(`Failed to repair ${path}`);\n return repaired;\n } finally {\n rmSync(lockPath, { force: true });\n }\n }\n throw new Error(`Timed out waiting to repair ${path}`);\n}\n\nexport function getOrCreateInstallId(): string {\n const overdeckHome = getOverdeckHome();\n const installIdPath = join(overdeckHome, INSTALL_ID_FILE);\n\n try {\n const existing = readValidInstallId(installIdPath);\n return existing ?? repairInvalidInstallId(installIdPath, overdeckHome);\n } catch (error) {\n if (!(error instanceof Error) || !('code' in error) || error.code !== 'ENOENT') throw error;\n }\n\n mkdirSync(overdeckHome, { recursive: true });\n const installId = randomUUID();\n\n try {\n writeFileSync(installIdPath, `${installId}\\n`, { encoding: 'utf8', mode: 0o600, flag: 'wx' });\n return installId;\n } catch (error) {\n if (!(error instanceof Error) || !('code' in error) || error.code !== 'EEXIST') throw error;\n const existing = readValidInstallId(installIdPath);\n return existing ?? repairInvalidInstallId(installIdPath, overdeckHome);\n }\n}\n","import { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { inspect } from 'node:util';\nimport { PostHog } from 'posthog-node';\nimport type { TelemetryEventName, TelemetryPropertiesFor } from '@overdeck/contracts';\nimport { packageRoot } from '../paths.js';\nimport { resolveTelemetryEnabled } from './config.js';\nimport { getOrCreateInstallId } from './install-id.js';\n\nconst DEFAULT_POSTHOG_API_KEY = 'phc_pwvHeDutnCmAm8tZh5hRaQ7mMoho3T9gb4t4qRjK2Zjt';\nconst DEFAULT_POSTHOG_HOST = 'https://us.i.posthog.com';\nconst SHUTDOWN_TIMEOUT_MS = 2_000;\nconst FLAG_TIMEOUT_MS = 500;\n\nexport type AnalyticsClientType = 'cli' | 'server';\n\nexport interface AnalyticsServiceOptions {\n captureProcessExceptions?: boolean;\n fatalProcessExit?: (code: number) => never;\n featureFlagOverrides?: Readonly<Record<string, boolean>>;\n}\n\nexport type TelemetryExceptionAction =\n | 'cli_command'\n | 'pipeline_transition'\n | 'server_boot'\n | 'uncaught_exception'\n | 'unhandled_rejection';\n\nexport interface TelemetryExceptionContext {\n action: TelemetryExceptionAction;\n}\n\nlet cachedOverdeckVersion: string | undefined;\nlet processAnalyticsClientType: AnalyticsClientType = 'server';\nconst sharedAnalyticsServices = new Map<AnalyticsClientType, AnalyticsService>();\nconst pendingAnalyticsTasks = new Set<Promise<unknown>>();\n\nfunction getOverdeckVersion(): string {\n if (cachedOverdeckVersion) return cachedOverdeckVersion;\n try {\n const manifest = JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8')) as { version?: unknown };\n cachedOverdeckVersion = typeof manifest.version === 'string' ? manifest.version : 'unknown';\n } catch {\n cachedOverdeckVersion = 'unknown';\n }\n return cachedOverdeckVersion;\n}\n\nfunction telemetryBlockedForProcess(): boolean {\n return Boolean(process.env.VITEST) || process.env.NODE_ENV === 'test';\n}\n\nexport class AnalyticsService {\n private client: PostHog | undefined;\n private processExceptionHandlers: {\n uncaughtException: (error: Error) => void;\n unhandledRejection: (reason: unknown) => void;\n } | undefined;\n private fatalExceptionInFlight = false;\n\n constructor(\n private readonly clientType: AnalyticsClientType,\n private readonly options: AnalyticsServiceOptions = {},\n ) {}\n\n capture<Event extends TelemetryEventName>(\n event: Event,\n properties: TelemetryPropertiesFor<Event>,\n ): void {\n const client = this.getClient();\n if (!client) return;\n\n try {\n client.capture({\n distinctId: getOrCreateInstallId(),\n event,\n properties: {\n ...properties,\n $process_person_profile: false,\n platform: process.platform,\n arch: process.arch,\n overdeckVersion: getOverdeckVersion(),\n clientType: this.clientType,\n },\n });\n } catch {\n // Analytics must never fail the caller.\n }\n }\n\n captureException(_error: unknown, context: TelemetryExceptionContext): void {\n const client = this.getClient();\n if (!client) return;\n\n const sanitized = new Error(`Overdeck ${context.action} operation failed`);\n sanitized.name = 'OverdeckTelemetryException';\n sanitized.stack = undefined;\n\n try {\n client.captureException(\n sanitized,\n getOrCreateInstallId(),\n {\n action: context.action,\n $process_person_profile: false,\n platform: process.platform,\n arch: process.arch,\n overdeckVersion: getOverdeckVersion(),\n clientType: this.clientType,\n },\n );\n } catch {\n // Analytics must never fail the caller.\n }\n }\n\n async isFeatureEnabled(flag: string, fallback: boolean): Promise<boolean> {\n const override = this.options.featureFlagOverrides?.[flag];\n if (typeof override === 'boolean') return override;\n\n const client = this.getClient();\n if (!client) return fallback;\n\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n const result = await Promise.race([\n client.isFeatureEnabled(flag, getOrCreateInstallId(), {\n sendFeatureFlagEvents: false,\n }),\n new Promise<boolean>((resolve) => {\n timeout = setTimeout(() => resolve(fallback), FLAG_TIMEOUT_MS);\n }),\n ]);\n return typeof result === 'boolean' ? result : fallback;\n } catch {\n return fallback;\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n }\n\n async shutdown(timeoutMs = SHUTDOWN_TIMEOUT_MS): Promise<void> {\n this.detachProcessExceptionHandlers();\n const client = this.client;\n if (!client) return;\n this.client = undefined;\n\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n const shutdown = Promise.resolve(client.shutdown(Math.max(0, timeoutMs)));\n if (timeoutMs <= 0) return;\n await Promise.race([\n shutdown,\n new Promise<void>((resolve) => { timeout = setTimeout(resolve, timeoutMs); }),\n ]);\n } catch {\n // Analytics must never fail shutdown.\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n }\n\n private attachProcessExceptionHandlers(): void {\n if (!this.options.captureProcessExceptions || this.processExceptionHandlers) return;\n const uncaughtException = (error: Error): void => {\n this.captureFatalProcessException(error, 'uncaught_exception');\n };\n const unhandledRejection = (reason: unknown): void => {\n this.captureFatalProcessException(reason, 'unhandled_rejection');\n };\n this.processExceptionHandlers = { uncaughtException, unhandledRejection };\n process.on('uncaughtException', uncaughtException);\n process.on('unhandledRejection', unhandledRejection);\n }\n\n private captureFatalProcessException(\n error: unknown,\n action: Extract<TelemetryExceptionAction, 'uncaught_exception' | 'unhandled_rejection'>,\n ): void {\n if (this.fatalExceptionInFlight) return;\n this.fatalExceptionInFlight = true;\n process.exitCode = 1;\n try {\n const detail = error instanceof Error\n ? error.stack ?? `${error.name}: ${error.message}`\n : inspect(error);\n process.stderr.write(`${detail}\\n`);\n } catch {\n // Local logging failure must not prevent the bounded fatal flush and exit.\n }\n this.captureException(error, { action });\n void this.shutdown().finally(() => {\n const exit = this.options.fatalProcessExit ?? process.exit;\n exit(1);\n });\n }\n\n private detachProcessExceptionHandlers(): void {\n const handlers = this.processExceptionHandlers;\n if (!handlers) return;\n process.off('uncaughtException', handlers.uncaughtException);\n process.off('unhandledRejection', handlers.unhandledRejection);\n this.processExceptionHandlers = undefined;\n }\n\n private getClient(): PostHog | undefined {\n let enabled = false;\n try {\n enabled = !telemetryBlockedForProcess() && resolveTelemetryEnabled();\n } catch {\n // A configuration read failure must fail closed.\n }\n\n if (!enabled) {\n void this.shutdown();\n return undefined;\n }\n if (this.client) return this.client;\n\n try {\n this.client = new PostHog(\n process.env.POSTHOG_API_KEY ?? DEFAULT_POSTHOG_API_KEY,\n {\n host: process.env.POSTHOG_HOST ?? DEFAULT_POSTHOG_HOST,\n enableExceptionAutocapture: false,\n },\n );\n this.attachProcessExceptionHandlers();\n return this.client;\n } catch {\n return undefined;\n }\n }\n}\n\nexport function setAnalyticsClientTypeForProcess(clientType: AnalyticsClientType): void {\n processAnalyticsClientType = clientType;\n}\n\nexport function getAnalyticsClientTypeForProcess(): AnalyticsClientType {\n return processAnalyticsClientType;\n}\n\nexport function getAnalyticsService(clientType: AnalyticsClientType): AnalyticsService {\n const existing = sharedAnalyticsServices.get(clientType);\n if (existing) return existing;\n\n const analytics = new AnalyticsService(clientType, {\n captureProcessExceptions: clientType === 'server',\n });\n sharedAnalyticsServices.set(clientType, analytics);\n return analytics;\n}\n\nexport function trackAnalyticsTask<Task extends Promise<unknown>>(task: Task): Task {\n pendingAnalyticsTasks.add(task);\n const remove = (): void => { pendingAnalyticsTasks.delete(task); };\n void task.then(remove, remove);\n return task;\n}\n\nasync function waitForPendingAnalyticsTasks(timeoutMs: number): Promise<void> {\n if (pendingAnalyticsTasks.size === 0 || timeoutMs <= 0) return;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n Promise.allSettled([...pendingAnalyticsTasks]),\n new Promise<void>((resolve) => {\n timeout = setTimeout(resolve, timeoutMs);\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\nexport async function shutdownAnalyticsServices(): Promise<void> {\n const deadline = Date.now() + SHUTDOWN_TIMEOUT_MS;\n await waitForPendingAnalyticsTasks(SHUTDOWN_TIMEOUT_MS);\n const remainingMs = Math.max(0, deadline - Date.now());\n await Promise.all(\n [...sharedAnalyticsServices.values()].map((analytics) =>\n analytics.shutdown(remainingMs)),\n );\n}\n\nexport async function synchronizeAnalyticsServices(): Promise<void> {\n let enabled = false;\n try {\n enabled = resolveTelemetryEnabled();\n } catch {\n // A configuration read failure must fail closed.\n }\n if (enabled) return;\n await shutdownAnalyticsServices();\n}\n","import type {\n Harness,\n PipelineStageChangedProperties,\n TelemetryModelFamily,\n} from '@overdeck/contracts';\nimport {\n readPipelineTelemetryAgentState,\n type PipelineTelemetryAgentState,\n} from './pipeline-agent-reader.js';\nimport {\n getAnalyticsClientTypeForProcess,\n getAnalyticsService,\n trackAnalyticsTask,\n} from './service.js';\nconst HARNESSES = new Set<Harness>(['claude-code', 'ohmypi', 'codex', 'acp', 'kimi-code', 'opencode', 'muse']);\n\nexport interface PipelineTelemetryContext {\n harness: Harness;\n model: TelemetryModelFamily;\n}\n\ntype PipelineMembershipReader = (issueId: string) => Promise<boolean>;\n\nasync function readCanonicalPipelineMembership(issueId: string): Promise<boolean> {\n const [membershipModule, gatherModule, recordModule] = await Promise.all([\n import('../pipeline-membership.js'),\n import('../pipeline-membership-gather.js'),\n import('../pan-dir/record.js'),\n ]);\n const project = recordModule.resolveProjectForIssue(issueId);\n if (!project) return false;\n const signals = await gatherModule.gatherProjectLensSignals(project);\n const issueSignals = signals.find(\n (candidate) => candidate.issueId.toUpperCase() === issueId.toUpperCase(),\n );\n return issueSignals\n ? membershipModule.resolvePipelineMembership(issueSignals).inPipeline\n : false;\n}\n\nexport function toTelemetryModelFamily(model: string): TelemetryModelFamily {\n const normalized = model.toLowerCase();\n if (normalized.includes('claude')) return 'claude';\n if (normalized.includes('gpt') || /^o\\d/.test(normalized)) return 'gpt';\n if (normalized.includes('gemini')) return 'gemini';\n if (normalized.includes('kimi')) return 'kimi';\n if (normalized.includes('minimax')) return 'minimax';\n if (normalized.includes('glm')) return 'glm';\n if (normalized.includes('mimo')) return 'mimo';\n return 'other';\n}\n\nexport async function resolvePipelineTelemetryContext(\n issueId: string,\n readAgent: (agentId: string) => PipelineTelemetryAgentState | null = readPipelineTelemetryAgentState,\n readMembership: PipelineMembershipReader = readCanonicalPipelineMembership,\n): Promise<PipelineTelemetryContext | null> {\n if (!await readMembership(issueId)) return null;\n const state = readAgent(`agent-${issueId.toLowerCase()}`);\n if (\n !state?.harness ||\n !HARNESSES.has(state.harness) ||\n typeof state.model !== 'string' ||\n state.model.trim().length === 0\n ) return null;\n return {\n harness: state.harness,\n model: toTelemetryModelFamily(state.model),\n };\n}\n\nexport function capturePipelineStage(\n stage: PipelineStageChangedProperties['stage'],\n context: PipelineTelemetryContext | null,\n analytics: {\n capture: (\n event: 'pipeline_stage_changed',\n properties: PipelineStageChangedProperties,\n ) => void;\n } = getAnalyticsService(getAnalyticsClientTypeForProcess()),\n): void {\n if (!context) return;\n try {\n analytics.capture('pipeline_stage_changed', { stage, ...context });\n } catch {\n // Telemetry must never affect a pipeline transition.\n }\n}\n\nexport function capturePipelineStageForIssue(\n issueId: string,\n stage: PipelineStageChangedProperties['stage'],\n): Promise<void> {\n return trackAnalyticsTask((async () => {\n try {\n capturePipelineStage(stage, await resolvePipelineTelemetryContext(issueId));\n } catch {\n // Membership and agent context are best-effort and must not affect the transition.\n }\n })());\n}\n","interface ReviewGuardStatus {\n stuck?: boolean;\n stuckReason?: string;\n stuckAt?: string;\n stuckDetails?: string;\n reviewedAtCommit?: string;\n lastVerifiedCommit?: string;\n}\n\ninterface ReviewGuardUpdate {\n reviewStatus?: string;\n testStatus?: string;\n reviewedAtCommit?: string;\n lastVerifiedCommit?: string;\n}\n\ntype StuckFields = Pick<ReviewGuardStatus, 'stuck' | 'stuckReason' | 'stuckAt' | 'stuckDetails'>;\n\nexport function clearSupersededReviewInfrastructureFailure(\n status: ReviewGuardStatus | null,\n): Partial<StuckFields> {\n if (status?.stuckReason !== 'review_infrastructure_failure') return {};\n return {\n stuck: false,\n stuckReason: undefined,\n stuckAt: undefined,\n stuckDetails: undefined,\n };\n}\n\ninterface VerdictEvidenceHeadMismatch {\n gate: 'review' | 'test';\n evidenceHead: string;\n targetHead: string;\n}\n\nfunction findVerdictEvidenceHeadMismatch(\n status: ReviewGuardStatus,\n update: ReviewGuardUpdate,\n): VerdictEvidenceHeadMismatch | null {\n const terminalTest = update.testStatus !== undefined\n && ['passed', 'failed'].includes(update.testStatus);\n if (\n terminalTest\n && update.lastVerifiedCommit\n && status.reviewedAtCommit\n && update.lastVerifiedCommit !== status.reviewedAtCommit\n ) {\n return { gate: 'test', evidenceHead: update.lastVerifiedCommit, targetHead: status.reviewedAtCommit };\n }\n return null;\n}\n\nexport function rejectVerdictEvidenceHeadMismatch(\n issueId: string,\n status: ReviewGuardStatus,\n update: ReviewGuardUpdate,\n onReject: () => void,\n): boolean {\n const mismatch = findVerdictEvidenceHeadMismatch(status, update);\n if (!mismatch) return false;\n console.warn(\n `[review-status] Rejecting ${mismatch.gate} verdict for ${issueId}: `\n + `evidence HEAD ${mismatch.evidenceHead} does not match target HEAD ${mismatch.targetHead}.`,\n );\n onReject();\n return true;\n}\n","import { join } from 'path';\nimport { homedir } from 'os';\nimport { Data, Effect } from 'effect';\nimport { notifyPipelineSync } from './pipeline-notifier.js';\nimport { emitActivityEntrySync, emitActivityTtsSync } from './activity-logger.js';\nimport {\n upsertReviewStatusSync as dbUpsert,\n deleteReviewStatus as dbDelete,\n getReviewStatusFromDbSync,\n getAllReviewStatusesFromDb,\n getReviewStatusesFromDb,\n markWorkspaceStuck as dbMarkStuck,\n clearWorkspaceStuck as dbClearStuck,\n clearWorkspaceStuckAndResetHistory as dbClearStuckAndResetHistory,\n} from './overdeck/review-status-sync.js';\nimport {\n registerCanonicalReviewStatusResolver,\n registerReviewStatusMapReader,\n} from './cloister/review-status-source.js';\nimport { normalizeReviewStatusSync } from './review-status-normalize.js';\nimport { updateIssueRecordForReviewStatusSync, readJournalStatusSync } from './overdeck/review-status-record-sync.js';\nimport { carriesNewTerminalVerdict } from './pan-dir/pipeline-verdict-merge.js';\nimport {\n reviewGatesPassedSync,\n verificationSatisfied, settleMergedVerification,\n type BlockerReason, type ReviewStatus, type StatusHistoryEntry,\n} from './review-status-reconcile.js';\nimport { isReviewRequestStale, needsReviewDispatch } from './review-dispatch-decision.js';\nimport { REVIEW_STATUS_HISTORY_LIMIT } from './review-status-reconcile.js';\nimport { truncateReviewStatusNote } from './review-status-limits.js';\nimport { resolveJournalReconciledReviewStatusSync } from './review-status-read.js';\nimport { capturePipelineStageForIssue } from './telemetry/pipeline.js';\nimport type { ReviewStatusUpdate } from './workspace-anchor-drift.js';\nimport type { HeadAnchor } from './git-utils.js';\nimport { rejectVerdictEvidenceHeadMismatch } from './review-verdict-guards.js';\nimport { registerVerdictPreservationStatusReader, registerWorkStartVerdictAdapter } from './cloister/work-start-verdicts.js';\n\nexport { reviewGatesPassedSync, verificationSatisfied, MERGED_VERIFICATION_REASON } from './review-status-reconcile.js';\nexport type { BlockerReason, ReviewStatus, StatusHistoryEntry } from './review-status-reconcile.js';\nexport type { ReviewStatusUpdate } from './workspace-anchor-drift.js';\n\nexport interface MergeGateEligibility {\n eligible: boolean;\n reason?: string;\n}\n\n/**\n * Authoritative \"allowed to merge\" predicate (PAN-1759). The flywheel\n * orchestrator's pipeline verb says it INTENDS to merge an issue; this record\n * says the pipeline ALLOWS it. Both must hold before an issue enters the merge\n * queue or a UAT batch — RUN-20 tagged a mid-review issue with a merge verb\n * and it rode into a promotable batch. Same criteria as the\n * fixStuckReadyForMerge repair sweep: review passed, test passed/skipped,\n * verification not failed, not already merged.\n */\nexport function mergeGateEligibility(\n status: Pick<ReviewStatus, 'reviewStatus' | 'testStatus' | 'verificationStatus' | 'mergeStatus' | 'retiredAt'> | null,\n): MergeGateEligibility {\n if (!status) return { eligible: false, reason: 'no review record' };\n if (status.retiredAt) return { eligible: false, reason: 'retired' };\n if (status.reviewStatus !== 'passed' && status.reviewStatus !== 'skipped') {\n return { eligible: false, reason: `review is ${status.reviewStatus}` };\n }\n if (status.testStatus !== 'passed' && status.testStatus !== 'skipped') {\n return { eligible: false, reason: `test is ${status.testStatus}` };\n }\n if (!verificationSatisfied(status)) return { eligible: false, reason: 'verification failed' };\n if (status.mergeStatus === 'merged') return { eligible: false, reason: 'already merged' };\n return { eligible: true };\n}\n// PAN-2579: register the cycle-free status-map reader used by concurrency.ts for\n// warm-idle advancing classification (see cloister/review-status-source.ts).\nregisterReviewStatusMapReader(() => getAllReviewStatusesFromDb());\nregisterCanonicalReviewStatusResolver((issueId) => getReviewStatusSync(issueId));\nregisterVerdictPreservationStatusReader((issueId) => { const status = getReviewStatusSync(issueId); return status ? { ...status, reviewedAtCommit: status.reviewedAtCommit as HeadAnchor | undefined } : null; });\nregisterWorkStartVerdictAdapter({ refreshReviewedAnchor: (issueId, anchor) => setReviewStatusSync(issueId, { reviewedAtCommit: anchor }), resetPipelineVerdicts: (issueId) => resetPipelineVerdictsForWorkStartSync(issueId) !== null });\n\nconst DEFAULT_STATUS_FILE = join(homedir(), '.overdeck', 'review-status.json');\n\nexport function loadReviewStatuses(filePath = DEFAULT_STATUS_FILE): Record<string, ReviewStatus> {\n // SQLite is the authoritative store for the default (server) path.\n // Non-default JSON paths have been moved to review-status-json.ts so that\n // dashboard-reachable code never imports sync FS operations.\n if (filePath !== DEFAULT_STATUS_FILE) {\n throw new Error(\n `Non-default review-status paths are not supported in review-status.ts. ` +\n `Import from review-status-json.ts for JSON file operations.`\n );\n }\n return getAllReviewStatusesFromDb();\n}\n\nexport function loadReviewStatusesForIssues(issueIds: string[]): Record<string, ReviewStatus> {\n return getReviewStatusesFromDb(issueIds);\n}\n\nexport function loadReadyForMergeFlags(issueIds: string[]): Map<string, boolean> {\n const normalizedIds = [...new Set(issueIds.map((id) => id.toUpperCase()).filter(Boolean))];\n const dbStatuses = loadReviewStatusesForIssues(normalizedIds);\n const flags = new Map<string, boolean>();\n\n for (const issueId of normalizedIds) {\n const dbStatus = dbStatuses[issueId] ?? null;\n const journal = readJournalStatusSync(issueId);\n let status = dbStatus;\n\n if (journal) {\n if ((journal.durable as { closedOut?: boolean }).closedOut === true) {\n flags.set(issueId, false);\n continue;\n }\n\n if (!dbStatus || (dbStatus.updatedAt ?? '') < journal.updatedAt) {\n const merged: ReviewStatus = {\n ...(dbStatus ?? {\n issueId,\n reviewStatus: 'pending' as const,\n testStatus: 'pending' as const,\n updatedAt: journal.updatedAt,\n readyForMerge: false,\n }),\n };\n for (const [key, value] of Object.entries(journal.durable)) if (value !== undefined) (merged as unknown as Record<string, unknown>)[key] = value;\n for (const key of journal.clearedFields ?? []) delete (merged as unknown as Record<string, unknown>)[key];\n merged.issueId = issueId;\n merged.updatedAt = journal.updatedAt;\n const hasBlockers = (merged.blockerReasons?.length ?? 0) > 0;\n merged.readyForMerge = merged.retiredAt || hasBlockers ? false : reviewGatesPassedSync(merged);\n status = normalizeReviewStatusSync(merged);\n }\n }\n\n flags.set(issueId, status?.readyForMerge ?? false);\n }\n\n return flags;\n}\n\nexport function saveReviewStatuses(statuses: Record<string, ReviewStatus>, filePath = DEFAULT_STATUS_FILE): void {\n // SQLite is the authoritative store for the default (server) path.\n // Mirrors the old JSON overwrite semantics: upsert every entry in the map and\n // delete any SQLite rows whose keys are absent from the map (replace-all).\n if (filePath !== DEFAULT_STATUS_FILE) {\n throw new Error(\n `Non-default review-status paths are not supported in review-status.ts. ` +\n `Import from review-status-json.ts for JSON file operations.`\n );\n }\n const incoming = new Set(Object.keys(statuses));\n const existing = getAllReviewStatusesFromDb();\n for (const id of Object.keys(existing)) {\n if (!incoming.has(id)) {\n dbDelete(id);\n }\n }\n for (const status of Object.values(statuses)) {\n dbUpsert(status);\n }\n}\n\nexport function setReviewStatusSync(\n issueId: string,\n update: ReviewStatusUpdate,\n existing?: ReviewStatus,\n): ReviewStatus {\n // Guard: bare numeric IDs (no alphabetic prefix) must never reach the DB.\n // They would create orphaned rows that pollute pending lists and metrics.\n if (/^\\d+$/.test(issueId)) {\n console.warn(\n `[review-status] Rejecting setReviewStatus for bare numeric ID \"${issueId}\" — ` +\n `issue IDs must include a project prefix (e.g. PAN-${issueId}).`\n );\n return {\n issueId,\n reviewStatus: 'pending' as const,\n testStatus: 'pending' as const,\n updatedAt: new Date().toISOString(),\n readyForMerge: false,\n };\n }\n\n issueId = issueId.toUpperCase();\n\n // Read only the single row we're updating (avoids TOCTOU: bulk read-modify-write\n // races when two concurrent calls for different issue IDs run concurrently).\n // If `existing` is provided (e.g. from mutateBlockers), skip the read to\n // avoid double-read on the webhook ingestion path (PAN-905).\n // PAN-1988: the merge base goes through getReviewStatusSync (journal-reconciled +\n // notes-enriched), NOT the raw DB read. Otherwise a partial update (e.g. a testStatus\n // change carrying no review notes) would merge against a DB row whose notes/flags lag\n // the journal and silently erase the journal's feedback. A write triggered by reconciliation\n // must pass that reconciled status as `existing` so it does not recurse through this read.\n const status: ReviewStatus = existing ?? getReviewStatusSync(issueId) ?? {\n issueId,\n reviewStatus: 'pending' as const,\n testStatus: 'pending' as const,\n updatedAt: new Date().toISOString(),\n readyForMerge: false,\n };\n\n if (rejectVerdictEvidenceHeadMismatch(\n issueId, status, update, () => notifyPipelineSync({ type: 'status_changed', issueId, status }),\n )) return status;\n\n // Guard: reject reviewStatus regression from 'passed' to 'reviewing' unless the caller\n // is explicitly resetting the merge lifecycle (update includes mergeStatus).\n // This is belt-and-suspenders — endpoint-level guards should catch this first.\n if (update.reviewStatus === 'reviewing' && status.reviewStatus === 'passed' && update.mergeStatus === undefined) {\n console.warn(`[review-status] Rejecting reviewStatus regression from 'passed' to 'reviewing' for ${issueId} (mergeStatus not being reset)`);\n notifyPipelineSync({ type: 'status_changed', issueId, status: status as ReviewStatus });\n return status as ReviewStatus;\n }\n\n // PAN-2578: a bare 'reviewing' write must never clobber a terminal blocked/failed verdict.\n // A review agent can finish FASTER than the dispatch path that spawned it (PAN-399: the\n // verification gate completed 2 minutes after the agent recorded BLOCKED, and the dispatch\n // route's redundant `{ reviewStatus: 'reviewing' }` write destroyed the verdict in both the\n // DB and the journal). Blocked/failed → reviewing is legal ONLY when the caller explicitly\n // starts a NEW review cycle by carrying reviewSpawnedAt (spawnReviewRoleForIssue does).\n if (\n update.reviewStatus === 'reviewing' &&\n (status.reviewStatus === 'blocked' || status.reviewStatus === 'failed') &&\n update.reviewSpawnedAt === undefined\n ) {\n console.warn(\n `[review-status] Rejecting stale 'reviewing' write for ${issueId} — a terminal ` +\n `'${status.reviewStatus}' verdict is already recorded for this review cycle. Only a ` +\n `new dispatch (carrying reviewSpawnedAt) may re-enter 'reviewing'.`\n );\n notifyPipelineSync({ type: 'status_changed', issueId, status: status as ReviewStatus });\n return status as ReviewStatus;\n }\n\n // PAN-424: Reject testStatus regression from 'passed' to 'dispatch_failed' or 'failed'.\n // Once tests pass, duplicate dispatch failures must not overwrite the result.\n if (\n (update.testStatus === 'dispatch_failed' || update.testStatus === 'failed') &&\n status.testStatus === 'passed'\n ) {\n console.warn(`[review-status] Rejecting testStatus regression from 'passed' to '${update.testStatus}' for ${issueId}`);\n delete update.testStatus;\n delete update.testNotes;\n }\n\n const freshPrIdentity =\n (update.prNumber !== undefined && update.prNumber !== status.prNumber)\n || (update.prUrl !== undefined && update.prUrl !== status.prUrl);\n const merged = settleMergedVerification({ ...status, ...update });\n if (freshPrIdentity) merged.retiredAt = undefined;\n\n // Terminal verdicts consume the request that spawned this review. Preserve a newer request\n // because it represents an explicit re-review requested while the current review was running.\n const terminalReviewVerdict = update.reviewStatus !== status.reviewStatus &&\n ['passed', 'blocked', 'failed', 'skipped'].includes(update.reviewStatus ?? '');\n if (terminalReviewVerdict && merged.reviewRequestedAt &&\n (!merged.reviewSpawnedAt || Date.parse(merged.reviewRequestedAt) <= new Date(merged.reviewSpawnedAt).getTime())) {\n merged.reviewRequestedAt = undefined;\n }\n\n // Track status transitions in history — preserve raw notes for database storage (PAN-3253)\n // rawHistory starts with the already-hydrated bounded tail and receives one new transition\n // Truncation happens at hydration time and in event payloads, not here at composition.\n const now = new Date().toISOString();\n const rawHistory = [...(status.history || [])];\n if (update.reviewStatus && update.reviewStatus !== status.reviewStatus) {\n rawHistory.push({ type: 'review', status: update.reviewStatus, timestamp: now, ...(update.reviewNotes ? { notes: update.reviewNotes } : {}) });\n }\n if (update.testStatus && update.testStatus !== status.testStatus) {\n rawHistory.push({ type: 'test', status: update.testStatus, timestamp: now, ...(update.testNotes ? { notes: update.testNotes } : {}) });\n }\n if (update.uatStatus && update.uatStatus !== status.uatStatus) {\n rawHistory.push({ type: 'uat', status: update.uatStatus, timestamp: now, ...(update.uatNotes ? { notes: update.uatNotes } : {}) });\n }\n if (update.mergeStatus && update.mergeStatus !== status.mergeStatus) {\n rawHistory.push({ type: 'merge', status: update.mergeStatus, timestamp: now });\n }\n if (update.releaseStatus && update.releaseStatus !== status.releaseStatus) {\n rawHistory.push({ type: 'release', status: update.releaseStatus, timestamp: now, ...(update.releaseNotes ? { notes: update.releaseNotes } : {}) });\n }\n // Hydration bounds raw history before it reaches event payloads.\n\n // readyForMerge is event-driven and derived from gate state on every\n // write, so it flips the instant review+test+verification pass instead of waiting\n // for a deacon patrol or a startup `fixStuckReadyForMerge` reconcile (those become\n // redundant safety nets). This supersedes the PAN-1048 explicit-only model.\n //\n // Deriving from gates here does NOT bypass the \"rebased onto main + verified\"\n // guarantee: `triggerMerge()` performs the authoritative post-rebase quality gate\n // before it actually merges (see verificationSatisfied's note). The gate predicate\n // mirrors `fixStuckReadyForMerge` so behaviour is identical — just immediate.\n //\n // Explicit caller intent still wins (the merge flow sets readyForMerge=false when a\n // merge starts; mergeStatus then leaves pending/queued so the derive agrees).\n // PAN-905/PAN-3365: merge blockers and failed required UAT override explicit readiness.\n const hasBlockers = Boolean(merged.retiredAt) || (merged.blockerReasons?.length ?? 0) > 0 || merged.uatStatus === 'failed';\n const readyForMerge = hasBlockers\n ? false\n : (update.readyForMerge !== undefined\n ? update.readyForMerge\n : reviewGatesPassedSync(merged));\n\n const boundedHistory = rawHistory.slice(-REVIEW_STATUS_HISTORY_LIMIT).map((entry) => ({\n ...entry,\n notes: entry.notes ? truncateReviewStatusNote(entry.notes) : undefined,\n }));\n\n const dbStatus = normalizeReviewStatusSync({\n ...merged,\n issueId,\n updatedAt: now,\n readyForMerge,\n history: rawHistory,\n });\n\n const updated: ReviewStatus = normalizeReviewStatusSync({\n ...merged,\n issueId,\n updatedAt: now,\n readyForMerge,\n history: boundedHistory, // Return bounded (truncated) history in the event payload\n });\n\n // Report commit statuses to GitHub when readyForMerge transitions to true (PAN-536)\n if (readyForMerge && !status.readyForMerge && !updated.retiredAt && updated.prUrl) {\n (async () => {\n try {\n const { isGitHubAppConfigured, reportCommitStatus } = await import('./github-app.js');\n if (!isGitHubAppConfigured()) return;\n const prMatch = updated.prUrl!.match(/github\\.com\\/([^/]+)\\/([^/]+)\\/pull/);\n if (!prMatch) return;\n const [, owner, repo] = prMatch;\n // Get HEAD SHA of the PR branch\n const { exec } = await import('child_process');\n const { promisify } = await import('util');\n const execAsync = promisify(exec);\n const { stdout } = await execAsync(\n `gh pr view ${updated.prUrl!.match(/\\/pull\\/(\\d+)/)?.[1]} --json headRefOid --jq .headRefOid`,\n { encoding: 'utf-8', timeout: 10000 }\n );\n const sha = stdout.trim();\n if (sha) {\n // overdeck/review is honest here — review just transitioned to readyForMerge.\n // The overdeck/tests status is posted separately at the actual test-completion\n // site (verification-runner success, test-agent POST in workspaces routes) so it\n // accurately reflects which commit was tested.\n await reportCommitStatus(owner, repo, sha, 'success', 'overdeck/review', 'Review passed');\n console.log(`[review-status] Reported overdeck/review for ${issueId} (${sha.slice(0, 8)})`);\n }\n } catch (err: any) {\n console.warn(`[review-status] Failed to report commit status: ${err.message}`);\n }\n })();\n }\n\n // PAN-1908 + PAN-1988: the journal record is the SOURCE OF TRUTH for the verdict; the SQLite\n // row is a rebuildable cache. Write the journal FIRST. Since PAN-2541 it lives in\n // ${OVERDECK_HOME}/state/<project>/records/ — unwritable in a sandbox, so the writer falls back\n // to <workspace>/.overdeck/pipeline-verdict.json (PAN-2583). Fire-and-forget: a short-lived CLI\n // MUST drain via flushReviewStatusJournalWrites() before exit (PAN-2689). No xBRIEF mirror (PAN-1124).\n // PAN-3092: a NEW terminal verdict is the write the agent cannot cheaply retry,\n // so it gets the journal writer's backoff instead of an immediate fallback drop.\n const verdictWrite = carriesNewTerminalVerdict(status as unknown as Record<string, unknown>, update);\n updateIssueRecordForReviewStatusSync(issueId, updated, { verdictWrite });\n\n // The DB cache write is best-effort. A sandboxed agent's write throws SQLITE_READONLY, but\n // the verdict is already durable in the journal above, and the host reconciles the cache on\n // read (getReviewStatusSync's journal→DB reconcile). Tolerating this is what removes the\n // sandbox-escalation \"smoke and mirrors\" — the agent never has to break out of its jail to\n // record a verdict.\n // Write the raw (full) history to the database for archival (PAN-3253)\n try {\n dbUpsert(dbStatus);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.warn(`[review-status] DB cache write skipped for ${issueId} (${msg}); journal holds the verdict, host will reconcile on read.`);\n }\n\n notifyPipelineSync({ type: 'status_changed', issueId, status: updated });\n\n // Emit activity log entries for meaningful pipeline state transitions.\n // Each transition produces one entry so the ActivityPanel shows live pipeline progress.\n if (update.verificationStatus && update.verificationStatus !== status.verificationStatus) {\n const vMap: Record<string, { level: 'info' | 'warn' | 'error' | 'success'; msg: string; tts?: string; ttsPriority?: number }> = {\n running: { level: 'info', msg: `${issueId} — verification running`, tts: `${issueId} verification running` },\n passed: { level: 'success', msg: `${issueId} — verification passed`, tts: `${issueId} verification passed` },\n failed: { level: 'error', msg: `${issueId} — verification failed`, tts: `${issueId} verification failed` },\n skipped: { level: 'info', msg: `${issueId} — verification skipped`, tts: `${issueId} verification skipped`, ttsPriority: 2 },\n };\n const entry = vMap[update.verificationStatus];\n if (entry) emitActivityEntrySync({ source: 'cloister', level: entry.level, message: entry.msg, details: update.verificationNotes, issueId });\n if (entry?.tts) emitActivityTtsSync({\n utterance: entry.tts,\n priority: entry.ttsPriority ?? (entry.level === 'error' ? 0 : 1),\n issueId,\n source: 'cloister',\n eventType: `verificationStatus.${update.verificationStatus}`,\n });\n }\n if (update.reviewStatus && update.reviewStatus !== status.reviewStatus) {\n if (update.reviewStatus === 'passed') void capturePipelineStageForIssue(issueId, 'review_passed');\n let reviewMsg = `${issueId} — review started`;\n if (update.reviewStatus === 'reviewing') {\n const retryCount = updated.reviewRetryCount ?? 0;\n reviewMsg = retryCount > 0\n ? `${issueId} — review re-dispatched (retry ${retryCount})`\n : `${issueId} — review started`;\n }\n const rMap: Record<string, { level: 'info' | 'warn' | 'error' | 'success'; msg: string; tts?: string }> = {\n reviewing: { level: 'info', msg: reviewMsg, tts: `${issueId} review started` },\n passed: { level: 'success', msg: `${issueId} — review passed`, tts: `${issueId} review passed` },\n failed: { level: 'error', msg: `${issueId} — review failed`, tts: `${issueId} review failed` },\n blocked: { level: 'warn', msg: `${issueId} — review blocked (changes requested)`, tts: `${issueId} review blocked` },\n };\n const entry = rMap[update.reviewStatus];\n if (entry) emitActivityEntrySync({ source: 'review', level: entry.level, message: entry.msg, details: update.reviewNotes, issueId });\n if (entry?.tts) emitActivityTtsSync({\n utterance: entry.tts,\n priority: entry.level === 'error' ? 0 : 1,\n issueId,\n source: 'review-specialist',\n eventType: `reviewStatus.${update.reviewStatus}`,\n });\n }\n if (update.testStatus && update.testStatus !== status.testStatus) {\n const tMap: Record<string, { level: 'info' | 'warn' | 'error' | 'success'; msg: string; tts?: string; ttsPriority?: number }> = {\n testing: { level: 'info', msg: `${issueId} — tests running`, tts: `${issueId} tests running`, ttsPriority: 2 },\n passed: { level: 'success', msg: `${issueId} — tests passed`, tts: `${issueId} tests passed` },\n failed: { level: 'error', msg: `${issueId} — tests failed`, tts: `${issueId} tests failed` },\n skipped: { level: 'info', msg: `${issueId} — tests skipped`, tts: `${issueId} tests skipped`, ttsPriority: 2 },\n dispatch_failed: { level: 'warn', msg: `${issueId} — test dispatch failed`, tts: `${issueId} test dispatch failed`, ttsPriority: 1 },\n };\n const entry = tMap[update.testStatus];\n if (entry) emitActivityEntrySync({ source: 'test', level: entry.level, message: entry.msg, details: update.testNotes, issueId });\n if (entry?.tts) emitActivityTtsSync({\n utterance: entry.tts,\n priority: entry.ttsPriority ?? (entry.level === 'error' ? 0 : 1),\n issueId,\n source: 'test-specialist',\n eventType: `testStatus.${update.testStatus}`,\n });\n }\n if (update.mergeStatus && update.mergeStatus !== status.mergeStatus) {\n const mMap: Record<string, { level: 'info' | 'warn' | 'error' | 'success'; msg: string; tts?: string; ttsPriority?: number }> = {\n queued: { level: 'info', msg: `${issueId} — queued for merge`, tts: `${issueId} queued for merge`, ttsPriority: 2 },\n merging: { level: 'info', msg: `${issueId} — merge in progress`, tts: `${issueId} merge in progress`, ttsPriority: 2 },\n verifying: { level: 'info', msg: `${issueId} — post-merge verification`, tts: `${issueId} post-merge verification running`, ttsPriority: 2 },\n merged: { level: 'success', msg: `${issueId} — merged`, tts: `${issueId} merged to main` },\n failed: { level: 'error', msg: `${issueId} — merge failed`, tts: `${issueId} merge failed` },\n };\n const entry = mMap[update.mergeStatus];\n if (entry) emitActivityEntrySync({ source: 'ship', level: entry.level, message: entry.msg, details: update.mergeNotes, issueId });\n if (entry?.tts) emitActivityTtsSync({\n utterance: entry.tts,\n priority: entry.ttsPriority ?? (entry.level === 'error' ? 0 : 1),\n issueId,\n source: 'merge-agent',\n eventType: `mergeStatus.${update.mergeStatus}`,\n });\n }\n if (updated.readyForMerge && !status.readyForMerge) {\n emitActivityEntrySync({ source: 'cloister', level: 'success', message: `${issueId} — ready for merge`, issueId });\n emitActivityTtsSync({\n utterance: `${issueId} ready for merge`,\n priority: 1,\n issueId,\n source: 'cloister',\n eventType: 'readyForMerge',\n });\n }\n\n // Reactive Cloister owns review→test and test→ship scheduling. setReviewStatus\n // emits the lifecycle event here so API and direct-import callers share one path.\n // PAN-1862 (FR-14): reviewStatus 'skipped' (review mode none) advances the\n // lifecycle exactly like an approved review — same event, same downstream.\n if (\n (update.reviewStatus === 'passed' || update.reviewStatus === 'skipped') &&\n status.reviewStatus !== 'passed' && status.reviewStatus !== 'skipped' &&\n updated.testStatus === 'pending'\n ) {\n const canSkipTests =\n updated.reviewedAtCommit &&\n updated.lastVerifiedCommit &&\n updated.reviewedAtCommit === updated.lastVerifiedCommit;\n\n if (canSkipTests) {\n console.log(`[review-status] Skipping test role for ${issueId} — no code drift since verification (HEAD=${updated.reviewedAtCommit!.slice(0, 8)})`);\n emitActivityEntrySync({ source: 'cloister', level: 'info', message: `${issueId} — tests skipped (no code change since verification gate)`, issueId });\n setReviewStatusSync(issueId, {\n testStatus: 'passed',\n testNotes: 'Skipped: no code changed since pre-review verification gate',\n verificationStatus: 'passed',\n verificationNotes: 'Pre-review verification already covered the reviewed commit',\n });\n void emitReactiveLifecycleEvent('test.passed', issueId);\n } else {\n void emitReactiveLifecycleEvent('review.approved', issueId);\n }\n }\n\n if (update.testStatus === 'passed' && status.testStatus !== 'passed') {\n void emitReactiveLifecycleEvent('test.passed', issueId);\n }\n\n // PAN-1988: test FAILED → hand it straight back to the work agent (host-side). The dead-end\n // requeue that does this is deacon-only, so without this a failure strands until the (possibly\n // frozen) deacon nudges. Fires once per transition into failed — both the agent's direct POST and\n // the host's .pan/test/result.json recovery flow through this same transition.\n if (\n (update.testStatus === 'failed' || update.testStatus === 'dispatch_failed') &&\n status.testStatus !== 'failed' && status.testStatus !== 'dispatch_failed'\n ) {\n void deliverTestFailureToWorkAgentHostSide(issueId, updated);\n }\n\n // A UAT failure can enter through the REST route, specialist completion, or\n // deacon recovery. Route from this write door so every entry point reaches the\n // same feedback-target resurrection and needs-you escalation path.\n if (update.uatStatus === 'failed') {\n void deliverUatFailureToWorkAgentHostSide(issueId, updated);\n } else if (update.uatStatus) {\n void clearUatFailureAnchorHostSide(issueId);\n }\n\n return updated;\n}\n\nfunction emitReactiveLifecycleEvent(\n type: 'review.approved' | 'test.passed',\n issueId: string,\n): void {\n try {\n notifyPipelineSync({ type, issueId });\n } catch (error) {\n console.warn(`[review-status] Failed to emit ${type} for ${issueId}:`, error);\n }\n}\n\nexport type ReviewVerdictFeedbackDelivery = (\n issueId: string,\n status: ReviewStatus,\n) => Promise<void>;\n\nlet reviewVerdictFeedbackDelivery: ReviewVerdictFeedbackDelivery | null = null;\n\nexport function registerReviewVerdictFeedbackDelivery(\n delivery: ReviewVerdictFeedbackDelivery,\n): void {\n reviewVerdictFeedbackDelivery = delivery;\n}\n\nasync function deliverReviewVerdictFeedbackHostSide(\n issueId: string,\n status: ReviewStatus,\n): Promise<void> {\n if (!reviewVerdictFeedbackDelivery) {\n console.warn(`[review-status] review feedback delivery is not registered for ${issueId}; preserving durable feedback state for a host retry`);\n return;\n }\n try {\n await reviewVerdictFeedbackDelivery(issueId, status);\n } catch (err) {\n console.warn(`[review-status] host-side review feedback delivery for ${issueId} did not complete (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nconst reviewDispatchAttemptAt = new Map<string, number>();\nconst staleReviewRequestClearAttemptedAt = new Map<string, number>();\nconst REVIEW_AUTO_DISPATCH_THROTTLE_MS = 30_000;\nconst STRANDED_REVIEW_SPAWN_AGE_MS = 20 * 60_000;\nconst STRANDED_REDISPATCH_COOLDOWN_MS = 10 * 60_000;\nconst strandedReviewRedispatchAt = new Map<string, number>();\nlet loggedMissingPipelineHandler = false;\n\n/**\n * PAN-3674: a pending review whose dispatch already ran (reviewSpawnedAt set)\n * but produced no live reviewer sessions is stranded by a failed spawn — the\n * 2026-08-13 PAN-3668 incident sat like this for 5h while the dashboard showed\n * a benign 'Pending'. needsReviewDispatch stands down once spawnedAt covers the\n * request, so without this repair nothing ever retries.\n */\nfunction isStrandedPendingReview(status: ReviewStatus, now = Date.now()): boolean {\n if (status.reviewStatus !== 'pending') return false;\n if (status.readyForMerge === true || status.mergeStatus === 'merged') return false;\n // Verification must have passed — a pending row with failed or absent\n // verification waits on the work agent, not on a review re-dispatch.\n if (status.verificationStatus !== 'passed' && status.verificationStatus !== 'skipped') return false;\n const spawned = status.reviewSpawnedAt;\n if (spawned === undefined || spawned === null) return false;\n const spawnedMs = typeof spawned === 'number' ? spawned : Date.parse(spawned);\n if (!Number.isFinite(spawnedMs)) return false;\n return now - spawnedMs >= STRANDED_REVIEW_SPAWN_AGE_MS;\n}\n\n/** @internal Test-only export — the stranded predicate is the safety gate for the repair. */\nexport function _isStrandedPendingReviewForTest(status: ReviewStatus, now?: number): boolean {\n return isStrandedPendingReview(status, now);\n}\n\nfunction maybeRedispatchStrandedReviewHostSide(issueId: string, status: ReviewStatus): void {\n if (!isStrandedPendingReview(status)) return;\n const last = strandedReviewRedispatchAt.get(issueId) ?? 0;\n if (Date.now() - last < STRANDED_REDISPATCH_COOLDOWN_MS) return;\n strandedReviewRedispatchAt.set(issueId, Date.now());\n void redispatchStrandedReviewHostSide(issueId, status);\n}\n\nasync function redispatchStrandedReviewHostSide(issueId: string, status: ReviewStatus): Promise<void> {\n try {\n const { listSessions } = await import('./tmux.js');\n const { isReviewSessionForIssue } = await import('./cloister/specialists-registry.js');\n const sessions = await Effect.runPromise(listSessions()).catch(() => [] as readonly { name: string }[]);\n // A live reviewer session means the row — not the pipeline — is stale;\n // there is nothing to repair.\n if (sessions.some((s) => isReviewSessionForIssue(s.name, undefined, issueId))) return;\n const { resolveProjectFromIssueSync } = await import('./projects.js');\n const resolved = resolveProjectFromIssueSync(issueId);\n if (!resolved) return;\n const { existsSync } = await import('fs');\n const workspace = join(resolved.projectPath, 'workspaces', `feature-${issueId.toLowerCase()}`);\n if (!existsSync(workspace)) return;\n const { dispatchRegisteredReviewHostSide } = await import('./cloister/durable-review-pipeline.js');\n // Dispatch-only: verification already passed at this HEAD (the predicate\n // requires it), so the full pipeline's gate re-run would be pure waste.\n const result = await dispatchRegisteredReviewHostSide({\n issueId,\n workspace,\n branch: `feature/${issueId.toLowerCase()}`,\n ...(status.prUrl ? { prUrl: status.prUrl } : {}),\n });\n if (!result) return; // No dispatcher registered (CLI process) — stay silent.\n const message = result.success\n ? `${issueId} — stranded pending review re-dispatched after a failed spawn (PAN-3674): ${result.message ?? 'ok'}`\n : `${issueId} — stranded pending review re-dispatch failed (PAN-3674): ${result.error ?? result.message ?? 'unknown'}`;\n console.log(`[review-status] ${message}`);\n emitActivityEntrySync({ source: 'review', level: result.success ? 'info' : 'warn', issueId, message });\n } catch (err) {\n console.warn(`[review-status] stranded review re-dispatch for ${issueId} did not complete (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nfunction maybeAutoDispatchReviewHostSide(issueId: string, status: ReviewStatus): void {\n if (!needsReviewDispatch({\n reviewRequestedAt: status.reviewRequestedAt,\n reviewSpawnedAt: status.reviewSpawnedAt,\n reviewStatus: status.reviewStatus,\n mergeStatus: status.mergeStatus,\n readyForMerge: status.readyForMerge,\n })) {\n // PAN-3674: the dispatch gate has nothing to do, but a stale spawn with no\n // live reviewers means the last dispatch died — repair it.\n maybeRedispatchStrandedReviewHostSide(issueId, status);\n if (!isReviewRequestStale({ reviewRequestedAt: status.reviewRequestedAt }) ||\n staleReviewRequestClearAttemptedAt.has(issueId)) return;\n staleReviewRequestClearAttemptedAt.set(issueId, Date.now());\n try {\n setReviewStatusSync(issueId, { reviewRequestedAt: undefined }, status);\n const message = `${issueId} — cleared stale review request older than 7 days`;\n console.warn(`[review-status] ${message}`);\n emitActivityEntrySync({ source: 'cloister', level: 'warn', issueId, message });\n } catch {\n // Sandboxed read-only callers cannot repair durable state; a host process will retry.\n }\n return;\n }\n const last = reviewDispatchAttemptAt.get(issueId) ?? 0;\n if (Date.now() - last < REVIEW_AUTO_DISPATCH_THROTTLE_MS) return;\n reviewDispatchAttemptAt.set(issueId, Date.now());\n void dispatchReviewHostSide(issueId, status.prUrl);\n}\nexport async function dispatchReviewHostSide(issueId: string, prUrl?: string): Promise<void> {\n try {\n const {\n hasDurableReviewPipelineDispatch,\n startRegisteredDurableReviewPipelineHostSide,\n } = await import('./cloister/durable-review-pipeline.js');\n if (!hasDurableReviewPipelineDispatch()) {\n if (!loggedMissingPipelineHandler) {\n loggedMissingPipelineHandler = true;\n console.debug('[review-status] durable review pipeline handler is not registered; skipping host-side review auto-dispatch');\n }\n return;\n }\n const started = await startRegisteredDurableReviewPipelineHostSide({\n issueId,\n ...(prUrl ? { prUrl } : {}),\n setReviewPending: (update) => setReviewStatusSync(issueId, update),\n });\n if (!started) {\n console.log(`[review-status] durable review pipeline unavailable or already in flight for ${issueId} (host-side)`);\n }\n } catch (err) {\n console.warn(`[review-status] host-side review auto-dispatch for ${issueId} did not complete (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nconst testVerdictRecoveryAt = new Map<string, number>();\nconst TEST_VERDICT_RECOVERY_THROTTLE_MS = 60_000;\n\nfunction maybeRecoverTestVerdictHostSide(issueId: string, status: ReviewStatus): void {\n if (status.reviewStatus !== 'passed') return;\n if (status.mergeStatus === 'merged' || status.readyForMerge) return;\n if (status.testStatus !== 'testing' && status.testStatus !== 'pending' && status.testStatus !== 'dispatch_failed') return;\n const last = testVerdictRecoveryAt.get(issueId) ?? 0;\n if (Date.now() - last < TEST_VERDICT_RECOVERY_THROTTLE_MS) return;\n testVerdictRecoveryAt.set(issueId, Date.now());\n void recoverTestVerdictHostSide(issueId);\n}\n\nasync function recoverTestVerdictHostSide(issueId: string): Promise<void> {\n try {\n const { resolveProjectFromIssueSync } = await import('./projects.js');\n const resolved = resolveProjectFromIssueSync(issueId);\n if (!resolved) return;\n const { existsSync } = await import('fs');\n const workspace = join(resolved.projectPath, 'workspaces', `feature-${issueId.toLowerCase()}`);\n if (!existsSync(workspace)) return;\n const { readTestVerdictArtifact } = await import('./cloister/test-verdict.js');\n const artifact = readTestVerdictArtifact(workspace);\n if (!artifact) return;\n setReviewStatusSync(issueId, {\n testStatus: artifact.status,\n testNotes: artifact.notes ??\n `Recovered from .pan/test/result.json (${artifact.status}) — the test agent wrote the verdict but never signaled`,\n });\n console.log(`[review-status] recovered unsignaled test verdict for ${issueId}: ${artifact.status} (host-side, from .pan/test/result.json)`);\n } catch (err) {\n console.warn(`[review-status] host-side test verdict recovery for ${issueId} did not complete (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nexport function resetPipelineVerdictsForWorkStartSync(issueId: string, options: { force?: boolean } = {}): ReviewStatus | null {\n const status = getReviewStatusSync(issueId);\n if (!status) return null;\n const isPending =\n status.reviewStatus === 'pending' &&\n status.testStatus === 'pending' &&\n (status.mergeStatus === undefined || status.mergeStatus === 'pending') &&\n (status.verificationStatus === undefined || status.verificationStatus === 'pending') &&\n !status.readyForMerge &&\n status.autoRequeueCount === 0 &&\n status.verificationCycleCount === 0 &&\n status.reviewRetryCount === 0 &&\n status.testRetryCount === 0 &&\n status.mergeRetryCount === 0 &&\n status.recoveryStartedAt === undefined &&\n status.reviewedAtCommit === undefined &&\n status.lastVerifiedCommit === undefined;\n\n if (isPending && !options.force) return null;\n\n return setReviewStatusSync(issueId, {\n reviewStatus: 'pending',\n testStatus: 'pending',\n mergeStatus: 'pending',\n reviewNotes: undefined,\n testNotes: undefined,\n mergeNotes: undefined,\n readyForMerge: false,\n autoRequeueCount: 0,\n verificationStatus: 'pending',\n verificationNotes: undefined,\n verificationCycleCount: 0,\n stuck: false,\n stuckReason: undefined,\n stuckAt: undefined,\n stuckDetails: undefined,\n reviewRetryCount: 0,\n testRetryCount: 0,\n mergeRetryCount: 0,\n recoveryStartedAt: undefined,\n reviewedAtCommit: undefined,\n lastVerifiedCommit: undefined,\n reviewRequestedAt: undefined, reviewSpawnedAt: undefined,\n conflictResolutionDispatchedAt: undefined, blockerReasons: undefined,\n retiredAt: undefined,\n });\n}\n\nasync function deliverUatFailureToWorkAgentHostSide(issueId: string, status: ReviewStatus): Promise<void> {\n try {\n const { relayUatFailureFeedbackPromise } = await import('./cloister/uat-failure-feedback.js');\n await relayUatFailureFeedbackPromise({\n issueId,\n uatNotes: status.uatNotes,\n anchor: status.reviewedAtCommit,\n });\n } catch (err) {\n console.warn(`[review-status] host-side UAT-failure delivery for ${issueId} did not complete (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nasync function clearUatFailureAnchorHostSide(issueId: string): Promise<void> {\n try {\n const { clearUatFailureFeedbackAnchor } = await import('./cloister/uat-failure-feedback.js');\n clearUatFailureFeedbackAnchor(issueId);\n } catch (err) {\n console.warn(`[review-status] host-side UAT-failure anchor clear for ${issueId} did not complete (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nasync function deliverTestFailureToWorkAgentHostSide(issueId: string, status: ReviewStatus): Promise<void> {\n try {\n const { resolveProjectFromIssueSync } = await import('./projects.js');\n const resolved = resolveProjectFromIssueSync(issueId);\n const workspace = resolved ? join(resolved.projectPath, 'workspaces', `feature-${issueId.toLowerCase()}`) : undefined;\n const notes = status.testNotes; let feedbackPath: string | undefined;\n try {\n const { writeFeedbackFile } = await import('./cloister/feedback-writer.js');\n const r = await Effect.runPromise(writeFeedbackFile({\n issueId, workspacePath: workspace, specialist: 'test-agent', outcome: 'failed', summary: `Tests FAILED for ${issueId}`,\n markdownBody: `# Test failure\\n\\n${notes ?? 'The test gate reported failures. See .pan/test/result.json and re-run the project test suite.'}\\n\\n## Required\\nFix the failing tests, commit and push, then re-run \\`pan done ${issueId}\\`.`,\n }));\n if (r.success) feedbackPath = r.filePath;\n } catch { /* non-fatal — the message below still carries the summary */ }\n\n const message = `SPECIALIST FEEDBACK: test-agent reported FAILED for ${issueId}.\\n\\n${feedbackPath ? `MUST READ: ${feedbackPath}\\n\\n` : ''}${notes ? `${notes.slice(0, 400)}\\n\\n` : ''}Fix the failing tests, commit and push, then re-run pan done ${issueId}. Do NOT stop at the prompt.`;\n const { resolveIssueFeedbackTarget, surfaceIssueFeedbackNeedsYou } = await import('./cloister/feedback-target.js');\n const target = await resolveIssueFeedbackTarget(issueId);\n if ('agentId' in target) {\n const { messageAgent } = await import('./agents.js');\n await messageAgent(target.agentId, message, 'internal', { owesRework: true });\n console.log(`[review-status] delivered test failure to ${target.agentId} for ${issueId} (host-side)`);\n } else {\n await surfaceIssueFeedbackNeedsYou(issueId, target.reason, { specialist: 'test-agent', feedbackPath });\n }\n } catch (err) {\n console.warn(`[review-status] host-side test-failure delivery for ${issueId} did not complete (non-fatal): ${err instanceof Error ? err.message : String(err)}`);\n }\n}\n\nfunction resolveReviewStatusSync(issueId: string, dbStatus: ReviewStatus | null | undefined): ReviewStatus | null {\n return resolveJournalReconciledReviewStatusSync(issueId, dbStatus, {\n deleteStatus: dbDelete,\n notifyStatusChanged: (id, status) => notifyPipelineSync({ type: 'status_changed', issueId: id, status }),\n deliverReviewVerdictFeedbackHostSide,\n emitReactiveLifecycleEvent,\n maybeAutoDispatchReviewHostSide,\n maybeRecoverTestVerdictHostSide,\n });\n}\n\nexport function getReviewStatusSync(issueId: string): ReviewStatus | null {\n return resolveReviewStatusSync(issueId, getReviewStatusFromDbSync(issueId));\n}\n\nexport function getReviewStatusesSync(issueIds: string[]): Record<string, ReviewStatus> {\n const ids = [...new Set(issueIds.map((issueId) => issueId.trim().toUpperCase()).filter(Boolean))];\n const dbStatuses = getReviewStatusesFromDb(ids);\n return Object.fromEntries(ids.flatMap((id) => {\n const status = resolveReviewStatusSync(id, dbStatuses[id]);\n return status ? [[id, status]] : [];\n }));\n}\n\n/**\n * On server startup, clear any mergeStatus stuck at 'merging'.\n * Pending merge operations are in-memory only — they don't survive a restart.\n * Any 'merging' status after boot is definitionally stuck (PAN-490).\n */\nexport function clearStuckMergeStatuses(): void {\n const statuses = loadReviewStatuses();\n // Don't clear 'queued' — the SQLite merge queue handles that (PAN-632).\n // Only clear truly stuck transient states.\n const stuck = Object.values(statuses).filter(s =>\n s.mergeStatus === 'merging' || s.mergeStatus === 'verifying'\n );\n if (stuck.length === 0) return;\n console.log(`[review-status] Clearing ${stuck.length} stuck merge status(es) on startup (merging/verifying)`);\n for (const s of stuck) {\n // Reset to pending so MERGE button reappears — the in-memory queue was lost on restart.\n // Preserve readyForMerge if review+test both passed — the merge just needs to be retried.\n const shouldBeReady =\n s.reviewStatus === 'passed' &&\n (s.testStatus === 'passed' || s.testStatus === 'skipped') &&\n verificationSatisfied(s) &&\n (s.uatStatus === undefined || s.uatStatus === 'passed');\n setReviewStatusSync(s.issueId, {\n mergeStatus: 'pending',\n ...(shouldBeReady ? { readyForMerge: true } : {}),\n });\n }\n}\n\n/**\n * Restore merge eligibility after a restart only when every gate passes and\n * canonical pipeline membership confirms that the issue still has an open PR.\n */\nexport async function fixStuckReadyForMerge(\n gatherEligibility?: typeof import('./cloister/merge-eligibility.js').gatherMergeEligibility,\n): Promise<void> {\n const statuses = loadReviewStatuses();\n const stuck = Object.values(statuses).filter(s =>\n !s.retiredAt &&\n s.readyForMerge === false &&\n s.reviewStatus === 'passed' &&\n (s.testStatus === 'passed' || s.testStatus === 'skipped') &&\n verificationSatisfied(s) &&\n // Failed and merged attempts are terminal; only pending/queued rows are repairable.\n (s.mergeStatus === 'pending' || s.mergeStatus === 'queued' || s.mergeStatus === undefined || s.mergeStatus === null) &&\n (s.uatStatus === undefined || s.uatStatus === 'passed')\n );\n if (stuck.length === 0) return;\n const mergeEligibility = await import('./cloister/merge-eligibility.js');\n const memberships = await (gatherEligibility ?? mergeEligibility.gatherMergeEligibility)(stuck.map((status) => status.issueId));\n console.log(`[review-status] Restoring readyForMerge for ${stuck.length} issue(s) with passed review+test`);\n for (const s of stuck) {\n const membership = memberships.get(s.issueId.toUpperCase());\n if (!membership || !mergeEligibility.isMergeEligible(membership)) {\n if (membership) setReviewStatusSync(s.issueId, { readyForMerge: false, retiredAt: new Date().toISOString() });\n console.log(`[review-status] skipping ${s.issueId} — pipeline membership is ${membership?.bucket ?? 'unavailable'}, not merge-eligible`);\n continue;\n }\n console.log(`[review-status] Restoring readyForMerge=true for ${s.issueId} (verif=${s.verificationStatus}, merge=${s.mergeStatus})`);\n setReviewStatusSync(s.issueId, { readyForMerge: true });\n }\n}\n\n/**\n * PAN-869: On server startup, fix any issues where reviewStatus was incorrectly\n * set to 'failed' due to the old COMMENTED → 'failed' mapping bug.\n *\n * This identifies records where:\n * - reviewStatus = 'failed'\n * - testStatus = 'passed' (CI green, so review wasn't genuinely bad)\n * - mergeStatus is not terminal ('merged', 'failed')\n * - readyForMerge = false\n * - The last review history entry is type='review', status='failed'\n *\n * The old reviewResultToReviewStatus() mapped COMMENTED (regardless of success)\n * to 'failed', so the history stores 'failed' for old COMMENTED reviews.\n * We use testStatus='passed' as the signal that this was a successful review\n * (CI was green), distinguishing it from genuinely failed reviews.\n */\nexport function fixStuckCommentedReviews(): void {\n const statuses = loadReviewStatuses();\n const candidates = Object.values(statuses).filter(s =>\n s.reviewStatus === 'failed' &&\n (s.testStatus === 'passed' || s.testStatus === 'skipped') &&\n s.mergeStatus !== 'merged' &&\n s.mergeStatus !== 'failed' &&\n s.readyForMerge === false &&\n s.verificationStatus !== 'failed'\n );\n\n if (candidates.length === 0) return;\n\n const toFix: string[] = [];\n for (const s of candidates) {\n // Check if the last review history entry is 'failed' (the old COMMENTED mapping\n // stored 'failed' in history). testStatus='passed' signals CI was green,\n // so this was a successful review incorrectly stored as 'failed'.\n const lastReviewEntry = [...(s.history || [])]\n .reverse()\n .find(h => h.type === 'review');\n if (lastReviewEntry?.status === 'failed') {\n toFix.push(s.issueId);\n }\n }\n\n if (toFix.length === 0) return;\n console.log(`[review-status] Restoring reviewStatus='passed' for ${toFix.length} issue(s) with COMMENTED reviews (PAN-869 backfill)`);\n for (const issueId of toFix) {\n console.log(`[review-status] Restoring reviewStatus='passed' for ${issueId}`);\n // reviewStatus='passed' will trigger readyForMerge recomputation in setReviewStatus\n setReviewStatusSync(issueId, { reviewStatus: 'passed' });\n }\n}\n\nexport function clearReviewStatus(issueId: string): void {\n // Terminal lifecycle owns removal of the UAT feedback dedup entry. The relay\n // stays dynamically imported to preserve the Node ESM boot graph.\n void clearUatFailureAnchorHostSide(issueId);\n try {\n dbDelete(issueId);\n } catch (err) {\n console.error('[review-status] SQLite delete failed:', err);\n }\n}\n\n// ============== Stuck state helpers (PAN-653) ==============\n\n/**\n * Mark a workspace as stuck with a reason and optional JSON details.\n * Persists across dashboard restarts. Deacon will skip stuck workspaces.\n *\n * @param issueId - Issue ID (e.g. \"PAN-653\")\n * @param reason - Short reason code (e.g. \"main_diverged\")\n * @param details - Optional structured details (e.g. {localSha, remoteSha})\n */\n// PAN-1988: `stuck` is EPHEMERAL runtime state (set when patrol detects a wedged workspace),\n// NOT a durable verdict — projectPipeline deliberately does not journal it, and it is rebuilt\n// from runtime on a cache rebuild. So markWorkspaceStuck/clearWorkspaceStuck write the DB cache\n// directly and do not go through the journal door. The getReviewStatusSync journal→DB reconcile\n// preserves it (a strict overlay that never clobbers DB-only fields the journal doesn't carry).\nexport function markWorkspaceStuck(\n issueId: string,\n reason: string,\n details?: Record<string, unknown>,\n): void {\n try {\n dbMarkStuck(issueId, reason, details);\n console.log(`[review-status] Marked ${issueId} as stuck: ${reason}`);\n const updated = getReviewStatusSync(issueId);\n if (updated) notifyPipelineSync({ type: 'status_changed', issueId, status: updated });\n } catch (err) {\n console.error(`[review-status] Failed to mark ${issueId} as stuck:`, err);\n }\n}\n\n/**\n * Clear the stuck flag for a workspace.\n * Called when the human clicks \"Unstick\" in the dashboard.\n * Re-enables Deacon patrol for this workspace.\n */\nexport function clearWorkspaceStuck(issueId: string): void {\n try {\n dbClearStuck(issueId);\n console.log(`[review-status] Cleared stuck state for ${issueId}`);\n const updated = getReviewStatusSync(issueId);\n if (updated) notifyPipelineSync({ type: 'status_changed', issueId, status: updated });\n } catch (err) {\n console.error(`[review-status] Failed to clear stuck state for ${issueId}:`, err);\n }\n}\n\n/** PAN-3151: clear stuck and reset review cycle history when unsticking from review-not-converging. */\nexport function clearWorkspaceStuckAndResetHistory(issueId: string): void {\n try {\n dbClearStuckAndResetHistory(issueId);\n console.log(`[review-status] Cleared stuck state and reset cycle history for ${issueId}`);\n const updated = getReviewStatusSync(issueId);\n if (updated) notifyPipelineSync({ type: 'status_changed', issueId, status: updated });\n } catch (err) {\n console.error(`[review-status] Failed to clear stuck state for ${issueId}:`, err);\n }\n}\n\n/** Stuck reason recorded when specialist feedback could not reach a live agent (feedback-target.ts). */\nexport const FEEDBACK_DELIVERY_STUCK_REASON = 'feedback_delivery_needs_you';\n\n/**\n * PAN-3074: clear a feedback-delivery stuck flag once the condition it recorded\n * no longer holds — the feedback reached a live agent, or the agent completed\n * the fix-and-resubmit loop (`pan review request`). Any other stuck reason is\n * operator territory and stays put.\n */\nexport function clearFeedbackDeliveryStuck(issueId: string): void {\n const status = getReviewStatusSync(issueId);\n if (status?.stuck !== true || status.stuckReason !== FEEDBACK_DELIVERY_STUCK_REASON) return;\n clearWorkspaceStuck(issueId);\n}\n\n/**\n * Set or clear the operator-requested deacon-ignore flag. When set, Deacon\n * patrol skips the issue entirely on every cycle. Distinct from `stuck`, which\n * is a system-set failure marker that also suppresses patrol.\n */\nexport function setDeaconIgnored(\n issueId: string,\n ignored: boolean,\n reason?: string,\n): void {\n try {\n // PAN-1988: route through the single write door. deaconIgnored is a DURABLE field that\n // projectPipeline journals — a DB-only write (the old dbSetDeaconIgnored) lands in the\n // cache but not the journal, so it vanishes on a cache rebuild. setReviewStatusSync writes\n // both (and emits the status_changed event), keeping DB and journal in sync.\n setReviewStatusSync(issueId, {\n deaconIgnored: ignored,\n deaconIgnoredAt: ignored ? new Date().toISOString() : undefined,\n deaconIgnoredReason: ignored ? reason : undefined,\n });\n console.log(`[review-status] deaconIgnored=${ignored} for ${issueId}${reason ? ` (${reason})` : ''}`);\n } catch (err) {\n console.error(`[review-status] Failed to set deaconIgnored for ${issueId}:`, err);\n }\n}\n\n/**\n * PAN-1691: set the per-issue auto-merge routing key and broadcast the change.\n * `autoMerge === null` clears it back to the project default. Emits a\n * status_changed pipeline event so open dashboards reflect the toggle live.\n */\nexport function setAutoMerge(issueId: string, autoMerge: boolean | null): void {\n try {\n // PAN-1988: route through the single write door. autoMerge is a DURABLE field journaled by\n // projectPipeline; a DB-only write would be lost on cache rebuild. `null` clears it back to\n // the project default (stored as undefined). setReviewStatusSync writes DB + journal and\n // emits the status_changed event.\n setReviewStatusSync(issueId, { autoMerge: autoMerge === null ? undefined : autoMerge });\n console.log(`[review-status] autoMerge=${autoMerge === null ? 'default' : autoMerge} for ${issueId}`);\n } catch (err) {\n console.error(`[review-status] Failed to set autoMerge for ${issueId}:`, err);\n }\n}\n\n/** Tagged error for review-status Effect variants. */\nexport class ReviewStatusError extends Data.TaggedError('ReviewStatusError')<{\n readonly issueId: string;\n readonly operation: string;\n readonly message: string;\n readonly cause?: unknown;\n}> {}\n\nexport const setReviewStatus = (\n issueId: string,\n update: ReviewStatusUpdate,\n existing?: ReviewStatus,\n): Effect.Effect<ReviewStatus, ReviewStatusError> =>\n Effect.tryPromise({\n try: () => new Promise<ReviewStatus>((resolve, reject) => {\n setImmediate(() => {\n try {\n resolve(setReviewStatusSync(issueId, update, existing));\n } catch (err) {\n reject(err);\n }\n });\n }),\n catch: (cause) =>\n new ReviewStatusError({\n issueId,\n operation: 'setReviewStatus',\n message: cause instanceof Error ? cause.message : String(cause),\n cause,\n }),\n });\n\nexport const getReviewStatus = (\n issueId: string,\n): Effect.Effect<ReviewStatus | null, ReviewStatusError> =>\n Effect.try({\n try: () => getReviewStatusFromDbSync(issueId),\n catch: (cause) =>\n new ReviewStatusError({\n issueId,\n operation: 'getReviewStatus',\n message: cause instanceof Error ? cause.message : String(cause),\n cause,\n }),\n });\n"],"x_google_ignoreList":[9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASA,eAAsB,oBACpB,SACA,IACY;CACZ,MAAM,MAAM,QAAQ,aAAa;CACjC,MAAM,WAAW,iBAAiB,IAAI,IAAI,IAAI,QAAQ,SAAS;CAC/D,IAAI,gBAA4B;CAChC,MAAM,UAAU,IAAI,SAAe,YAAY;AAC7C,YAAU;GACV;CACF,MAAM,QAAQ,SAAS,YAAY,KAAA,EAAU,CAAC,WAAW,QAAQ;AACjE,kBAAiB,IAAI,KAAK,MAAM;AAEhC,OAAM,SAAS,YAAY,KAAA,EAAU;AAErC,KAAI;AACF,SAAO,MAAM,IAAI;WACT;AACR,WAAS;AACT,MAAI,iBAAiB,IAAI,IAAI,KAAK,MAChC,kBAAiB,OAAO,IAAI;;;;;AA7B5B,oCAAmB,IAAI,K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