oh-my-opencode 5.0.0-beta.5 → 5.0.0-beta.50

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 (952) hide show
  1. package/.agents/command/publish.md +44 -16
  2. package/.agents/skills/codex-qa/scripts/lsp-e2e.sh +1 -3
  3. package/.agents/skills/opencode-qa/scripts/lsp-e2e.sh +1 -1
  4. package/.agents/skills/pre-publish-review/SKILL.md +9 -12
  5. package/.agents/skills/publish/SKILL.md +44 -16
  6. package/.agents/skills/senpi-qa/SKILL.md +80 -0
  7. package/.agents/skills/senpi-qa/scripts/resolve-evidence-dir.mjs +65 -0
  8. package/.agents/skills/senpi-qa/scripts/resolve-evidence-dir.test.mjs +171 -0
  9. package/.agents/skills/tech-debt-audit/SKILL.md +6 -76
  10. package/.agents/skills/work-with-pr/SKILL.md +37 -23
  11. package/.opencode/command/publish.md +44 -16
  12. package/.opencode/skills/pre-publish-review/SKILL.md +9 -12
  13. package/.opencode/skills/work-with-pr/SKILL.md +37 -23
  14. package/README.ja.md +58 -46
  15. package/README.ko.md +60 -48
  16. package/README.md +58 -58
  17. package/README.ru.md +55 -46
  18. package/README.zh-cn.md +54 -46
  19. package/THIRD-PARTY-NOTICES.md +27 -99
  20. package/dist/agents/atlas/agent.d.ts +0 -1
  21. package/dist/agents/gpt-prompt-identity.d.ts +1 -1
  22. package/dist/agents/sisyphus/grok-4.d.ts +20 -0
  23. package/dist/agents/sisyphus/index.d.ts +2 -0
  24. package/dist/agents/sisyphus-agent-config.d.ts +6 -0
  25. package/dist/agents/sisyphus-agent-factory.d.ts +1 -1
  26. package/dist/agents/sisyphus-runtime-prompt-reconciler.d.ts +15 -4
  27. package/dist/agents/types.d.ts +4 -2
  28. package/dist/cli/config-manager/parse-opencode-config-file.d.ts +2 -1
  29. package/dist/cli/doctor/checks/system-plugin.d.ts +4 -3
  30. package/dist/cli/fallback-lane-policy.d.ts +1 -0
  31. package/dist/cli/index.js +51536 -59608
  32. package/dist/cli/install-codex/install-codex-test-fixtures.d.ts +1 -1
  33. package/dist/cli/run/on-complete-hook.d.ts +2 -0
  34. package/dist/cli/runtime-commands.d.ts +1 -1
  35. package/dist/cli/worktree-sweep/classify.d.ts +16 -0
  36. package/dist/cli/worktree-sweep/format.d.ts +8 -0
  37. package/dist/cli/worktree-sweep/git.d.ts +19 -0
  38. package/dist/cli/worktree-sweep/index.d.ts +7 -0
  39. package/dist/cli/worktree-sweep/options.d.ts +2 -0
  40. package/dist/cli/worktree-sweep/parse-worktree-list.d.ts +8 -0
  41. package/dist/cli/worktree-sweep/sweep.d.ts +2 -0
  42. package/dist/cli/worktree-sweep/types.d.ts +65 -0
  43. package/dist/cli/worktree-sweep/worktree-sweep.d.ts +2 -0
  44. package/dist/cli-node/index.js +51554 -59603
  45. package/dist/config/index.d.ts +1 -1
  46. package/dist/config/schema/background-task.d.ts +1 -0
  47. package/dist/config/schema/commands.d.ts +1 -1
  48. package/dist/config/schema/hooks.d.ts +1 -2
  49. package/dist/config/schema/oh-my-opencode-config.d.ts +5 -11
  50. package/dist/config/schema/ulw-execute.d.ts +5 -0
  51. package/dist/config/schema.d.ts +0 -1
  52. package/dist/config/validate.d.ts +2 -0
  53. package/dist/create-hooks.d.ts +3 -2
  54. package/dist/features/background-agent/compaction-aware-message-resolver.d.ts +1 -0
  55. package/dist/features/background-agent/constants.d.ts +0 -7
  56. package/dist/features/background-agent/error-classifier.d.ts +1 -0
  57. package/dist/features/background-agent/manager.d.ts +2 -1
  58. package/dist/features/background-agent/parent-wake-dispatched-tracker.d.ts +0 -1
  59. package/dist/features/background-agent/parent-wake-notifier-types.d.ts +1 -1
  60. package/dist/features/background-agent/parent-wake-prompt-dispatch.d.ts +1 -1
  61. package/dist/features/background-agent/parent-wake-session-inspector.d.ts +1 -1
  62. package/dist/features/background-agent/subagent-spawn-limits.d.ts +8 -0
  63. package/dist/features/btw-side/btw-command-draft.d.ts +7 -0
  64. package/dist/features/btw-side/context-injector.d.ts +15 -0
  65. package/dist/features/btw-side/index.d.ts +8 -0
  66. package/dist/features/btw-side/metadata.d.ts +15 -0
  67. package/dist/features/btw-side/parent-context-budget.d.ts +9 -0
  68. package/dist/features/btw-side/server-session-registry.d.ts +8 -0
  69. package/dist/features/btw-side/tui-adoption-cache.d.ts +13 -0
  70. package/dist/features/btw-side/tui-adoption-guard.d.ts +5 -0
  71. package/dist/features/btw-side/tui-controller-types.d.ts +68 -0
  72. package/dist/features/btw-side/tui-controller.d.ts +19 -0
  73. package/dist/features/btw-side/tui-escape-return.d.ts +12 -0
  74. package/dist/features/btw-side/tui-keymap.d.ts +17 -0
  75. package/dist/features/btw-side/tui-parent-validator.d.ts +6 -0
  76. package/dist/features/btw-side/tui-picker-options.d.ts +20 -0
  77. package/dist/features/btw-side/tui-picker.d.ts +9 -0
  78. package/dist/features/btw-side/tui-prompt-queue.d.ts +8 -0
  79. package/dist/features/btw-side/tui-session-bridge.d.ts +11 -0
  80. package/dist/features/btw-side/tui-session-catalog.d.ts +35 -0
  81. package/dist/features/btw-side/tui-side-removal.d.ts +11 -0
  82. package/dist/features/btw-side/tui-side-start.d.ts +9 -0
  83. package/dist/features/btw-side/tui-wiring.d.ts +8 -0
  84. package/dist/features/builtin-commands/templates/ulw-execute.d.ts +1 -0
  85. package/dist/features/builtin-commands/types.d.ts +1 -1
  86. package/dist/features/monitor/manager-internals.d.ts +1 -1
  87. package/dist/features/monitor/output-injector-types.d.ts +1 -1
  88. package/dist/features/opengateway-provider/index.d.ts +13 -0
  89. package/dist/features/task-toast-manager/manager.d.ts +0 -24
  90. package/dist/features/team-mode/tools/messaging-fallback-wake.d.ts +17 -0
  91. package/dist/features/team-mode/tools/messaging-live-delivery-recipient.d.ts +3 -0
  92. package/dist/features/team-mode/tools/messaging-runtime.d.ts +7 -0
  93. package/dist/hooks/anthropic-context-window-limit-recovery/message-storage-directory.d.ts +0 -3
  94. package/dist/hooks/anthropic-context-window-limit-recovery/state.d.ts +1 -0
  95. package/dist/hooks/anthropic-context-window-limit-recovery/storage/empty-messages.d.ts +0 -1
  96. package/dist/hooks/anthropic-context-window-limit-recovery/tool-result-storage.d.ts +11 -0
  97. package/dist/hooks/atlas/atlas-hook.d.ts +1 -0
  98. package/dist/hooks/atlas/atlas-lifecycle-store.d.ts +50 -0
  99. package/dist/hooks/atlas/event-handler.d.ts +1 -0
  100. package/dist/hooks/atlas/final-wave-approval-gate.test-support.d.ts +50 -0
  101. package/dist/hooks/atlas/system-reminder-templates.d.ts +0 -1
  102. package/dist/hooks/atlas/tool-execute-before.d.ts +3 -0
  103. package/dist/hooks/atlas/types.d.ts +1 -0
  104. package/dist/hooks/claude-code-hooks/session-hook-state.d.ts +1 -0
  105. package/dist/hooks/claude-code-hooks/stop.d.ts +2 -0
  106. package/dist/hooks/claude-code-hooks/todo.d.ts +0 -1
  107. package/dist/hooks/claude-code-hooks/transcript.d.ts +2 -0
  108. package/dist/hooks/compaction-context-injector/validated-model.d.ts +2 -0
  109. package/dist/hooks/fsync-skip-warning/index.d.ts +4 -0
  110. package/dist/hooks/hashline-edit-diff-enhancer/hook.d.ts +1 -0
  111. package/dist/hooks/hashline-edit-diff-enhancer/pending-captures.d.ts +13 -0
  112. package/dist/hooks/index.d.ts +1 -2
  113. package/dist/hooks/keyword-detector/hook.d.ts +7 -0
  114. package/dist/hooks/keyword-detector/ultrawork/source-detector.d.ts +0 -1
  115. package/dist/hooks/model-fallback/hook.d.ts +1 -1
  116. package/dist/hooks/prometheus-md-only/agent-resolution.d.ts +2 -2
  117. package/dist/hooks/runtime-fallback/chat-message-handler.d.ts +2 -0
  118. package/dist/hooks/runtime-fallback/retry-model-payload.d.ts +1 -0
  119. package/dist/hooks/runtime-fallback/runtime-model-settings.d.ts +6 -0
  120. package/dist/hooks/runtime-fallback/session-status-handler.d.ts +1 -1
  121. package/dist/hooks/runtime-fallback/types.d.ts +3 -1
  122. package/dist/hooks/sisyphus-junior-notepad/constants.d.ts +1 -1
  123. package/dist/hooks/todo-continuation-enforcer/types.d.ts +1 -0
  124. package/dist/hooks/{start-work → ulw-execute}/context-info-builder.d.ts +1 -1
  125. package/dist/hooks/{start-work → ulw-execute}/index.d.ts +1 -1
  126. package/dist/hooks/ulw-execute/ulw-execute-hook.d.ts +23 -0
  127. package/dist/index.js +28955 -25346
  128. package/dist/mcp/index.d.ts +0 -4
  129. package/dist/mcp/types.d.ts +0 -1
  130. package/dist/oh-my-opencode.schema.json +21 -47
  131. package/dist/plugin/chat-message/types.d.ts +3 -3
  132. package/dist/plugin/chat-message/ulw-execute-message.d.ts +5 -0
  133. package/dist/plugin/event-session-lifecycle.d.ts +1 -0
  134. package/dist/plugin/hooks/create-core-hooks.d.ts +2 -2
  135. package/dist/plugin/hooks/create-session-hooks.d.ts +2 -3
  136. package/dist/plugin/hooks/create-transform-hooks.d.ts +2 -0
  137. package/dist/plugin/messages-transform.d.ts +1 -0
  138. package/dist/plugin-dispose.d.ts +3 -0
  139. package/dist/shared/agent-tool-restrictions.d.ts +0 -1
  140. package/dist/shared/compaction-agent-config-checkpoint.d.ts +1 -0
  141. package/dist/shared/index.d.ts +2 -0
  142. package/dist/shared/legacy-plugin-warning.d.ts +2 -1
  143. package/dist/shared/normalize-sdk-response.d.ts +1 -0
  144. package/dist/shared/omo-process-sweep.d.ts +2 -4
  145. package/dist/shared/plugin-entry-migrator.d.ts +4 -3
  146. package/dist/shared/plugin-entry-shape.d.ts +6 -0
  147. package/dist/shared/runtime-fallback-retry-marker.d.ts +16 -0
  148. package/dist/shared/shell-env.d.ts +1 -1
  149. package/dist/skills/ast-grep/AGENTS.md +51 -0
  150. package/dist/skills/ast-grep/SKILL.md +1 -1
  151. package/dist/skills/coding-agent-sessions/AGENTS.md +62 -0
  152. package/dist/skills/coding-agent-sessions/SKILL.md +3 -2
  153. package/dist/skills/coding-agent-sessions/references/all-platforms.md +1 -1
  154. package/dist/skills/coding-agent-sessions/references/senpi.md +4 -4
  155. package/dist/skills/coding-agent-sessions/scripts/agent_sessions/pi_family.py +1 -1
  156. package/dist/skills/data-scientist/SKILL.md +99 -239
  157. package/dist/skills/data-scientist/references/execution-surfaces.md +91 -0
  158. package/dist/skills/data-scientist/references/placement.md +74 -0
  159. package/dist/skills/data-scientist/references/polars-lane.md +95 -0
  160. package/dist/skills/data-scientist/references/uv-setup.md +1 -1
  161. package/dist/skills/data-scientist/references/visualization.md +64 -0
  162. package/dist/skills/data-scientist/scripts/ensure-js-deps.sh +28 -0
  163. package/dist/skills/data-scientist/scripts/ensure-py-deps.sh +37 -0
  164. package/dist/skills/debugging/SKILL.md +3 -1
  165. package/dist/skills/debugging/references/methodology/00-setup.md +12 -0
  166. package/dist/skills/debugging/references/methodology/02-investigate.md +21 -0
  167. package/dist/skills/debugging/references/runtimes/go.md +15 -1
  168. package/dist/skills/debugging/references/runtimes/native-binary.md +38 -0
  169. package/dist/skills/debugging/references/runtimes/node.md +25 -0
  170. package/dist/skills/debugging/references/runtimes/python.md +13 -0
  171. package/dist/skills/debugging/references/runtimes/rust.md +41 -0
  172. package/dist/skills/debugging/references/scripts/dap.mjs +267 -0
  173. package/dist/skills/debugging/references/scripts/dap.test.ts +86 -0
  174. package/dist/skills/debugging/references/scripts/fixture-adapter.mjs +59 -0
  175. package/dist/skills/debugging/references/tools/dap.md +103 -0
  176. package/dist/skills/debugging/references/tools/frida.md +193 -0
  177. package/dist/skills/frontend/SKILL.md +12 -8
  178. package/dist/skills/frontend/references/design/_INDEX.md +1 -0
  179. package/dist/skills/frontend/references/design/print-paged-media.md +76 -0
  180. package/dist/skills/frontend/references/design/stylegallery.md +80 -0
  181. package/dist/skills/frontend/references/designpowers/README.md +1 -1
  182. package/dist/skills/frontend/references/designpowers/lane-a-direction.md +1 -1
  183. package/dist/skills/frontend/references/designpowers/lane-b-execution.md +11 -11
  184. package/dist/skills/frontend/references/designpowers/lane-d-memory.md +3 -3
  185. package/dist/skills/frontend/references/designpowers/orchestration.md +1 -1
  186. package/dist/skills/frontend/references/designpowers/routing.md +5 -5
  187. package/dist/skills/git-master/SKILL.md +1 -1
  188. package/dist/skills/init-deep/SKILL.md +14 -14
  189. package/dist/skills/lsp-setup/SKILL.md +1 -1
  190. package/dist/skills/programming/SKILL.md +1 -1
  191. package/dist/skills/refactor/SKILL.md +1 -1
  192. package/dist/skills/remove-ai-slops/SKILL.md +1 -1
  193. package/dist/skills/review-work/SKILL.md +100 -418
  194. package/dist/skills/ultimate-browsing/ATTRIBUTION.md +38 -11
  195. package/dist/skills/ultimate-browsing/SKILL.md +26 -9
  196. package/dist/skills/ultimate-browsing/engine/AGENTS.md +110 -0
  197. package/dist/skills/ultimate-browsing/engine/templates/package.json +1 -1
  198. package/dist/skills/ultimate-browsing/references/chrome-stealth.md +23 -18
  199. package/dist/skills/ultimate-browsing/references/insane-search/README.md +9 -2
  200. package/dist/skills/{start-work → ulw-execute}/SKILL.md +17 -16
  201. package/dist/skills/ulw-plan/SKILL.md +7 -8
  202. package/dist/skills/ulw-plan/references/full-workflow.md +31 -7
  203. package/dist/skills/ulw-plan/references/intent-clear.md +2 -1
  204. package/dist/skills/ulw-plan/references/intent-unclear.md +5 -5
  205. package/dist/skills/ulw-research/SKILL.md +8 -3
  206. package/dist/skills/visual-qa/AGENTS.md +58 -0
  207. package/dist/skills/visual-qa/SKILL.md +4 -3
  208. package/dist/tools/delegate-task/builtin-categories.d.ts +3 -1
  209. package/dist/tools/delegate-task/builtin-category-definition.d.ts +2 -1
  210. package/dist/tools/delegate-task/constants.d.ts +2 -2
  211. package/dist/tools/delegate-task/openai-categories.d.ts +7 -2
  212. package/dist/tools/delegate-task/sync-session-cleanup.d.ts +3 -0
  213. package/dist/tools/delegate-task/sync-session-poller.d.ts +1 -0
  214. package/dist/tools/delegate-task/tool-description.d.ts +3 -1
  215. package/dist/tools/delegate-task/types.d.ts +4 -0
  216. package/dist/tools/session-manager/directory-filter.d.ts +2 -0
  217. package/dist/tui.d.ts +12 -0
  218. package/dist/tui.js +37066 -46704
  219. package/package.json +47 -41
  220. package/packages/git-bash-mcp/dist/cli.js +6 -1
  221. package/packages/git-bash-mcp/package.json +1 -1
  222. package/packages/lsp-core/src/index.ts +1 -0
  223. package/packages/lsp-core/src/lsp/client-diagnostics-concurrency.integration.test.ts +44 -0
  224. package/packages/lsp-core/src/lsp/client-diagnostics-freshness.integration.test.ts +57 -48
  225. package/packages/lsp-core/src/lsp/client-diagnostics-pull-timeout.test.ts +64 -0
  226. package/packages/lsp-core/src/lsp/client-wrapper-outside-cwd.test.ts +78 -0
  227. package/packages/lsp-core/src/lsp/client-wrapper.test.ts +163 -13
  228. package/packages/lsp-core/src/lsp/client-wrapper.ts +110 -23
  229. package/packages/lsp-core/src/lsp/client.ts +32 -3
  230. package/packages/lsp-core/src/lsp/connection.ts +16 -0
  231. package/packages/lsp-core/src/lsp/constants.ts +6 -0
  232. package/packages/lsp-core/src/lsp/controlled-clock-test-support.ts +61 -0
  233. package/packages/lsp-core/src/lsp/errors.ts +15 -0
  234. package/packages/lsp-core/src/lsp/fixtures/workspace-edit-server.mjs +10 -3
  235. package/packages/lsp-core/src/lsp/format-document.test.ts +143 -0
  236. package/packages/lsp-core/src/lsp/format-document.ts +90 -0
  237. package/packages/lsp-core/src/lsp/json-rpc-connection.ts +11 -6
  238. package/packages/lsp-core/src/lsp/manager-lifecycle.test.ts +262 -0
  239. package/packages/lsp-core/src/lsp/manager-max-clients.test.ts +151 -0
  240. package/packages/lsp-core/src/lsp/manager.ts +138 -12
  241. package/packages/lsp-core/src/lsp/outside-context-workspace.ts +33 -0
  242. package/packages/lsp-core/src/lsp/server-definitions.ts +29 -0
  243. package/packages/lsp-core/src/lsp/server-installation.test.ts +376 -0
  244. package/packages/lsp-core/src/lsp/server-installation.ts +200 -27
  245. package/packages/lsp-core/src/lsp/server-resolution-local-binary.test.ts +170 -0
  246. package/packages/lsp-core/src/lsp/server-resolution.ts +18 -5
  247. package/packages/lsp-core/src/lsp/timer-provider.ts +13 -0
  248. package/packages/lsp-core/src/lsp/transport-request-timeout.test.ts +73 -0
  249. package/packages/lsp-core/src/lsp/transport.ts +16 -2
  250. package/packages/lsp-core/src/lsp/types.ts +8 -0
  251. package/packages/lsp-core/src/lsp/workspace-apply-edit-test-support.ts +29 -1
  252. package/packages/lsp-core/src/lsp/workspace-document-state.test.ts +84 -1
  253. package/packages/lsp-core/src/lsp/workspace-document-state.ts +30 -11
  254. package/packages/lsp-core/src/lsp/workspace-edit-adversarial.test.ts +20 -1
  255. package/packages/lsp-core/src/lsp/workspace-markers.ts +18 -0
  256. package/packages/lsp-core/src/mcp.ts +3 -0
  257. package/packages/lsp-core/src/request-context.test.ts +29 -0
  258. package/packages/lsp-core/src/request-context.ts +1 -1
  259. package/packages/lsp-core/src/tool-surface.test.ts +13 -1
  260. package/packages/lsp-core/src/tools/definitions.ts +14 -0
  261. package/packages/lsp-core/src/tools/diagnostics.ts +3 -3
  262. package/packages/lsp-core/src/tools/format.test.ts +56 -0
  263. package/packages/lsp-core/src/tools/format.ts +56 -0
  264. package/packages/lsp-core/src/tools/index.ts +1 -0
  265. package/packages/lsp-core/src/tools/navigation.ts +4 -2
  266. package/packages/lsp-core/src/tools/parameters.test.ts +51 -0
  267. package/packages/lsp-core/src/tools/rename.ts +4 -2
  268. package/packages/lsp-core/src/tools/symbols.ts +1 -1
  269. package/packages/lsp-core/src/tools/types.ts +10 -0
  270. package/packages/lsp-daemon/dist/cli.js +961 -483
  271. package/packages/lsp-daemon/dist/client.d.ts +10 -0
  272. package/packages/lsp-daemon/dist/client.js +976 -495
  273. package/packages/lsp-daemon/dist/daemon-client.d.ts +1 -0
  274. package/packages/lsp-daemon/dist/daemon-client.js +3 -0
  275. package/packages/lsp-daemon/dist/ensure-daemon.d.ts +6 -1
  276. package/packages/lsp-daemon/dist/ensure-daemon.js +10 -2
  277. package/packages/lsp-daemon/dist/index.js +881 -405
  278. package/packages/lsp-daemon/dist/proxy.js +3 -0
  279. package/packages/lsp-daemon/dist/version-reap.js +1 -1
  280. package/packages/lsp-daemon/package.json +1 -1
  281. package/packages/lsp-tools-mcp/dist/cli.js +820 -345
  282. package/packages/lsp-tools-mcp/dist/lsp/manager.js +272 -138
  283. package/packages/lsp-tools-mcp/dist/mcp.js +845 -372
  284. package/packages/lsp-tools-mcp/dist/request-context.js +12 -13
  285. package/packages/lsp-tools-mcp/dist/tools.js +775 -306
  286. package/packages/lsp-tools-mcp/package.json +1 -1
  287. package/packages/omo-codex/THIRD-PARTY-NOTICES.md +4 -21
  288. package/packages/omo-codex/plugin/.codex-plugin/plugin.json +4 -6
  289. package/packages/omo-codex/plugin/.mcp.json +0 -6
  290. package/packages/omo-codex/plugin/AGENTS.md +47 -0
  291. package/packages/omo-codex/plugin/README.md +6 -2
  292. package/packages/omo-codex/plugin/components/bootstrap/dist/cli.js +193 -148
  293. package/packages/omo-codex/plugin/components/bootstrap/hooks/hooks.json +1 -1
  294. package/packages/omo-codex/plugin/components/bootstrap/package.json +1 -1
  295. package/packages/omo-codex/plugin/components/bootstrap/src/hook.ts +1 -0
  296. package/packages/omo-codex/plugin/components/comment-checker/AGENTS.md +9 -0
  297. package/packages/omo-codex/plugin/components/comment-checker/biome.json +2 -2
  298. package/packages/omo-codex/plugin/components/comment-checker/dist/cli.js +2 -1
  299. package/packages/omo-codex/plugin/components/comment-checker/hooks/hooks.json +1 -1
  300. package/packages/omo-codex/plugin/components/comment-checker/package.json +5 -5
  301. package/packages/omo-codex/plugin/components/comment-checker/src/apply-patch.ts +2 -8
  302. package/packages/omo-codex/plugin/components/comment-checker/src/core.ts +1 -2
  303. package/packages/omo-codex/plugin/components/comment-checker/src/request-extractor.ts +1 -1
  304. package/packages/omo-codex/plugin/components/comment-checker/src/runner.ts +1 -0
  305. package/packages/omo-codex/plugin/components/git-bash/AGENTS.md +1 -1
  306. package/packages/omo-codex/plugin/components/git-bash/hooks/hooks.json +2 -2
  307. package/packages/omo-codex/plugin/components/git-bash/package.json +3 -4
  308. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/AGENTS.md +2 -2
  309. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/biome.json +2 -2
  310. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/directive.md +2 -0
  311. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/dist/cli.js +36 -29
  312. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/dist/codex-hook.js +32 -26
  313. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/dist/types.d.ts +3 -0
  314. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/hooks/hooks.json +1 -1
  315. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/package.json +5 -5
  316. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/src/codex-hook.ts +32 -28
  317. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/src/types.ts +3 -0
  318. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/test/cli.test.ts +1 -1
  319. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/test/codex-hook.test.ts +137 -28
  320. package/packages/omo-codex/plugin/components/lcx/skills/lcx-doctor/SKILL.md +4 -2
  321. package/packages/omo-codex/plugin/components/lsp/AGENTS.md +30 -15
  322. package/packages/omo-codex/plugin/components/lsp/biome.json +2 -2
  323. package/packages/omo-codex/plugin/components/lsp/dist/.omo-runtime-manifest.json +4 -4
  324. package/packages/omo-codex/plugin/components/lsp/dist/cli.js +999 -544
  325. package/packages/omo-codex/plugin/components/lsp/dist/daemon-cli-path.js +1 -1
  326. package/packages/omo-codex/plugin/components/lsp/hooks/hooks.json +2 -2
  327. package/packages/omo-codex/plugin/components/lsp/package.json +5 -5
  328. package/packages/omo-codex/plugin/components/lsp/src/cli.ts +1 -1
  329. package/packages/omo-codex/plugin/components/lsp/src/codex-hook.ts +1 -1
  330. package/packages/omo-codex/plugin/components/lsp/src/daemon-cli-path.ts +1 -5
  331. package/packages/omo-codex/plugin/components/lsp/test/codex-hook-unavailable.test.ts +6 -7
  332. package/packages/omo-codex/plugin/components/lsp/test/codex-hook.test.ts +1 -2
  333. package/packages/omo-codex/plugin/components/lsp/test/package-smoke.test.ts +11 -1
  334. package/packages/omo-codex/plugin/components/rules/AGENTS.md +12 -0
  335. package/packages/omo-codex/plugin/components/rules/README.md +2 -0
  336. package/packages/omo-codex/plugin/components/rules/biome.json +2 -2
  337. package/packages/omo-codex/plugin/components/rules/bundled-rules/hephaestus/gpt-6.md +123 -0
  338. package/packages/omo-codex/plugin/components/rules/dist/cli.js +91 -68
  339. package/packages/omo-codex/plugin/components/rules/hooks/hooks.json +4 -4
  340. package/packages/omo-codex/plugin/components/rules/package.json +7 -7
  341. package/packages/omo-codex/plugin/components/rules/src/config.ts +1 -2
  342. package/packages/omo-codex/plugin/components/rules/src/persistent-cache.ts +1 -2
  343. package/packages/omo-codex/plugin/components/rules/src/post-compact-budget.ts +15 -5
  344. package/packages/omo-codex/plugin/components/rules/src/rules-engine-factory.ts +1 -4
  345. package/packages/omo-codex/plugin/components/rules/src/static-injection.ts +4 -9
  346. package/packages/omo-codex/plugin/components/rules/test/bundled-rules-priority.test.ts +11 -16
  347. package/packages/omo-codex/plugin/components/rules/test/bundled-rules.test.ts +17 -25
  348. package/packages/omo-codex/plugin/components/rules/test/codex-hook-post-compact-budget.test.ts +9 -7
  349. package/packages/omo-codex/plugin/components/rules/test/codex-hook-post-compact-context.test.ts +0 -6
  350. package/packages/omo-codex/plugin/components/rules/test/codex-hook-post-compact-dedup.test.ts +6 -4
  351. package/packages/omo-codex/plugin/components/rules/test/codex-hook-post-compact-directive.test.ts +12 -9
  352. package/packages/omo-codex/plugin/components/rules/test/codex-hook.test.ts +28 -37
  353. package/packages/omo-codex/plugin/components/rules/test/dynamic-target-fingerprints.test.ts +1 -2
  354. package/packages/omo-codex/plugin/components/rules/test/engine.test.ts +7 -4
  355. package/packages/omo-codex/plugin/components/rules/test/finder.test.ts +2 -3
  356. package/packages/omo-codex/plugin/components/rules/test/formatter.test.ts +39 -72
  357. package/packages/omo-codex/plugin/components/rules/test/hephaestus-model-variant.test.ts +38 -3
  358. package/packages/omo-codex/plugin/components/rules/test/hook-output.test.ts +2 -3
  359. package/packages/omo-codex/plugin/components/rules/test/matcher.test.ts +2 -3
  360. package/packages/omo-codex/plugin/components/rules/test/package-smoke.test.ts +1 -1
  361. package/packages/omo-codex/plugin/components/rules/test/parser.test.ts +1 -2
  362. package/packages/omo-codex/plugin/components/rules/test/post-compact-budget.test.ts +29 -6
  363. package/packages/omo-codex/plugin/components/rules/test/rules-engine-consumption.test.ts +3 -6
  364. package/packages/omo-codex/plugin/components/rules/test/scanner.test.ts +1 -2
  365. package/packages/omo-codex/plugin/components/rules/test/sources.test.ts +2 -5
  366. package/packages/omo-codex/plugin/components/rules/test/windows-git-bash-bundled-rule.test.ts +2 -17
  367. package/packages/omo-codex/plugin/components/teammode/hooks/hooks.json +1 -1
  368. package/packages/omo-codex/plugin/components/teammode/package.json +5 -5
  369. package/packages/omo-codex/plugin/components/teammode/test/thread-title-hook.test.ts +4 -10
  370. package/packages/omo-codex/plugin/components/telemetry/AGENTS.md +8 -0
  371. package/packages/omo-codex/plugin/components/telemetry/biome.json +2 -2
  372. package/packages/omo-codex/plugin/components/telemetry/dist/cli.js +2435 -700
  373. package/packages/omo-codex/plugin/components/telemetry/dist/posthog.js +2439 -705
  374. package/packages/omo-codex/plugin/components/telemetry/hooks/hooks.json +1 -1
  375. package/packages/omo-codex/plugin/components/telemetry/package.json +5 -5
  376. package/packages/omo-codex/plugin/components/telemetry/src/codex-hook.ts +1 -4
  377. package/packages/omo-codex/plugin/components/telemetry/src/posthog.ts +4 -14
  378. package/packages/omo-codex/plugin/components/telemetry/src/product-identity.ts +1 -1
  379. package/packages/omo-codex/plugin/components/telemetry/test/diagnostics.test.ts +2 -5
  380. package/packages/omo-codex/plugin/components/ultrawork/AGENTS.md +10 -4
  381. package/packages/omo-codex/plugin/components/ultrawork/README.md +2 -0
  382. package/packages/omo-codex/plugin/components/ultrawork/agents/explorer.toml +1 -1
  383. package/packages/omo-codex/plugin/components/ultrawork/agents/lazycodex-clone-fidelity-reviewer.toml +1 -1
  384. package/packages/omo-codex/plugin/components/ultrawork/agents/lazycodex-code-reviewer.toml +1 -1
  385. package/packages/omo-codex/plugin/components/ultrawork/agents/lazycodex-gate-reviewer.toml +1 -1
  386. package/packages/omo-codex/plugin/components/ultrawork/agents/lazycodex-qa-executor.toml +1 -1
  387. package/packages/omo-codex/plugin/components/ultrawork/agents/lazycodex-worker-high.toml +1 -1
  388. package/packages/omo-codex/plugin/components/ultrawork/agents/lazycodex-worker-low.toml +1 -1
  389. package/packages/omo-codex/plugin/components/ultrawork/agents/lazycodex-worker-medium.toml +1 -1
  390. package/packages/omo-codex/plugin/components/ultrawork/agents/librarian.toml +1 -1
  391. package/packages/omo-codex/plugin/components/ultrawork/agents/metis.toml +1 -1
  392. package/packages/omo-codex/plugin/components/ultrawork/agents/momus.toml +1 -1
  393. package/packages/omo-codex/plugin/components/ultrawork/agents/plan.toml +1 -1
  394. package/packages/omo-codex/plugin/components/ultrawork/biome.json +2 -2
  395. package/packages/omo-codex/plugin/components/ultrawork/dist/cli.js +490 -4
  396. package/packages/omo-codex/plugin/components/ultrawork/hooks/hooks.json +1 -1
  397. package/packages/omo-codex/plugin/components/ultrawork/package.json +5 -6
  398. package/packages/omo-codex/plugin/components/ultrawork/scripts/sync-directive.mjs +30 -14
  399. package/packages/omo-codex/plugin/components/ultrawork/skills/ulw-plan/SKILL.md +6 -7
  400. package/packages/omo-codex/plugin/components/ultrawork/skills/ulw-plan/references/full-workflow.md +31 -7
  401. package/packages/omo-codex/plugin/components/ultrawork/skills/ulw-plan/references/intent-clear.md +2 -1
  402. package/packages/omo-codex/plugin/components/ultrawork/skills/ulw-plan/references/intent-unclear.md +5 -5
  403. package/packages/omo-codex/plugin/components/ultrawork/src/directive-content.ts +4 -0
  404. package/packages/omo-codex/plugin/components/ultrawork/src/directive.ts +5 -2
  405. package/packages/omo-codex/plugin/components/ultrawork/test/codex-hook-trigger-policy.test.ts +9 -1
  406. package/packages/omo-codex/plugin/components/ultrawork/test/codex-hook.test.ts +0 -136
  407. package/packages/omo-codex/plugin/components/ultrawork/test/directive-source.test.ts +14 -8
  408. package/packages/omo-codex/plugin/components/ultrawork/test/package-smoke.test.ts +12 -1
  409. package/packages/omo-codex/plugin/components/ultrawork/test/skill-pointer.test.ts +0 -2
  410. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/AGENTS.md +4 -4
  411. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/NOTICE +1 -1
  412. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/README.md +6 -6
  413. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/biome.json +2 -2
  414. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/directive.md +10 -10
  415. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/dist/cli.js +16 -16
  416. package/packages/omo-codex/plugin/components/ulw-execute-continuation/hooks/hooks.json +16 -0
  417. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/package.json +12 -12
  418. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/boulder-reader.ts +1 -1
  419. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/cli.ts +1 -1
  420. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/codex-hook.ts +4 -4
  421. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/directive.ts +1 -1
  422. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/index.ts +1 -1
  423. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/types.ts +1 -1
  424. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/boulder-reader.test.ts +3 -3
  425. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/cli.test.ts +4 -11
  426. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/codex-hook.test.ts +24 -22
  427. package/packages/omo-codex/plugin/components/ulw-loop/AGENTS.md +19 -0
  428. package/packages/omo-codex/plugin/components/ulw-loop/CHANGELOG.md +1 -1
  429. package/packages/omo-codex/plugin/components/ulw-loop/README.md +12 -1
  430. package/packages/omo-codex/plugin/components/ulw-loop/biome.json +2 -2
  431. package/packages/omo-codex/plugin/components/ulw-loop/directive.md +26 -13
  432. package/packages/omo-codex/plugin/components/ulw-loop/dist/checkpoint-codex-validation.d.ts +12 -0
  433. package/packages/omo-codex/plugin/components/ulw-loop/dist/checkpoint-codex-validation.js +45 -0
  434. package/packages/omo-codex/plugin/components/ulw-loop/dist/checkpoint-continuation.js +9 -0
  435. package/packages/omo-codex/plugin/components/ulw-loop/dist/checkpoint-reconciliation.d.ts +15 -0
  436. package/packages/omo-codex/plugin/components/ulw-loop/dist/checkpoint-reconciliation.js +15 -1
  437. package/packages/omo-codex/plugin/components/ulw-loop/dist/checkpoint-template.d.ts +8 -0
  438. package/packages/omo-codex/plugin/components/ulw-loop/dist/checkpoint-template.js +113 -0
  439. package/packages/omo-codex/plugin/components/ulw-loop/dist/checkpoint.js +40 -39
  440. package/packages/omo-codex/plugin/components/ulw-loop/dist/cli-commands.js +21 -8
  441. package/packages/omo-codex/plugin/components/ulw-loop/dist/cli-output.d.ts +2 -1
  442. package/packages/omo-codex/plugin/components/ulw-loop/dist/cli-output.js +12 -1
  443. package/packages/omo-codex/plugin/components/ulw-loop/dist/cli-subcommands.js +2 -0
  444. package/packages/omo-codex/plugin/components/ulw-loop/dist/cli.js +1264 -429
  445. package/packages/omo-codex/plugin/components/ulw-loop/dist/codex-goal-instruction.d.ts +2 -0
  446. package/packages/omo-codex/plugin/components/ulw-loop/dist/codex-goal-instruction.js +28 -8
  447. package/packages/omo-codex/plugin/components/ulw-loop/dist/codex-goal-snapshot.d.ts +13 -0
  448. package/packages/omo-codex/plugin/components/ulw-loop/dist/codex-goal-snapshot.js +15 -1
  449. package/packages/omo-codex/plugin/components/ulw-loop/dist/constants.d.ts +1 -0
  450. package/packages/omo-codex/plugin/components/ulw-loop/dist/constants.js +1 -0
  451. package/packages/omo-codex/plugin/components/ulw-loop/dist/domain-types.d.ts +17 -9
  452. package/packages/omo-codex/plugin/components/ulw-loop/dist/paths.d.ts +1 -0
  453. package/packages/omo-codex/plugin/components/ulw-loop/dist/paths.js +13 -4
  454. package/packages/omo-codex/plugin/components/ulw-loop/dist/plan-io.d.ts +1 -0
  455. package/packages/omo-codex/plugin/components/ulw-loop/dist/plan-io.js +34 -4
  456. package/packages/omo-codex/plugin/components/ulw-loop/dist/plan-missing-recovery.d.ts +14 -0
  457. package/packages/omo-codex/plugin/components/ulw-loop/dist/plan-missing-recovery.js +29 -0
  458. package/packages/omo-codex/plugin/components/ulw-loop/dist/quality-gate-aggregate.d.ts +7 -0
  459. package/packages/omo-codex/plugin/components/ulw-loop/dist/quality-gate-aggregate.js +9 -0
  460. package/packages/omo-codex/plugin/components/ulw-loop/dist/quality-gate-artifacts.d.ts +12 -0
  461. package/packages/omo-codex/plugin/components/ulw-loop/dist/quality-gate-artifacts.js +104 -0
  462. package/packages/omo-codex/plugin/components/ulw-loop/dist/quality-gate-fields.d.ts +13 -1
  463. package/packages/omo-codex/plugin/components/ulw-loop/dist/quality-gate-fields.js +65 -9
  464. package/packages/omo-codex/plugin/components/ulw-loop/dist/quality-gate-verdicts.js +5 -1
  465. package/packages/omo-codex/plugin/components/ulw-loop/dist/quality-gate.d.ts +4 -2
  466. package/packages/omo-codex/plugin/components/ulw-loop/dist/quality-gate.js +72 -117
  467. package/packages/omo-codex/plugin/components/ulw-loop/dist/review-blockers.js +4 -2
  468. package/packages/omo-codex/plugin/components/ulw-loop/dist/spawn-guard.d.ts +6 -1
  469. package/packages/omo-codex/plugin/components/ulw-loop/dist/spawn-guard.js +189 -29
  470. package/packages/omo-codex/plugin/components/ulw-loop/dist/state-lock.d.ts +9 -0
  471. package/packages/omo-codex/plugin/components/ulw-loop/dist/state-lock.js +227 -0
  472. package/packages/omo-codex/plugin/components/ulw-loop/dist/status-next-actions.d.ts +6 -0
  473. package/packages/omo-codex/plugin/components/ulw-loop/dist/status-next-actions.js +33 -0
  474. package/packages/omo-codex/plugin/components/ulw-loop/dist/stop-resume-hook.js +20 -6
  475. package/packages/omo-codex/plugin/components/ulw-loop/dist/surface.d.ts +19 -0
  476. package/packages/omo-codex/plugin/components/ulw-loop/dist/surface.js +75 -0
  477. package/packages/omo-codex/plugin/components/ulw-loop/hooks/hooks.json +17 -4
  478. package/packages/omo-codex/plugin/components/ulw-loop/package.json +6 -6
  479. package/packages/omo-codex/plugin/components/ulw-loop/skills/ulw-loop/SKILL.md +6 -4
  480. package/packages/omo-codex/plugin/components/ulw-loop/skills/ulw-loop/references/define-goal.md +108 -0
  481. package/packages/omo-codex/plugin/components/ulw-loop/skills/ulw-loop/references/full-workflow.md +32 -8
  482. package/packages/omo-codex/plugin/components/ulw-loop/src/checkpoint-codex-validation.ts +81 -0
  483. package/packages/omo-codex/plugin/components/ulw-loop/src/checkpoint-continuation.ts +7 -0
  484. package/packages/omo-codex/plugin/components/ulw-loop/src/checkpoint-reconciliation.ts +31 -1
  485. package/packages/omo-codex/plugin/components/ulw-loop/src/checkpoint-template.ts +128 -0
  486. package/packages/omo-codex/plugin/components/ulw-loop/src/checkpoint.ts +38 -71
  487. package/packages/omo-codex/plugin/components/ulw-loop/src/cli-commands.ts +24 -8
  488. package/packages/omo-codex/plugin/components/ulw-loop/src/cli-output.ts +14 -1
  489. package/packages/omo-codex/plugin/components/ulw-loop/src/cli-subcommands.ts +2 -0
  490. package/packages/omo-codex/plugin/components/ulw-loop/src/cli.ts +8 -6
  491. package/packages/omo-codex/plugin/components/ulw-loop/src/codex-goal-instruction.ts +35 -7
  492. package/packages/omo-codex/plugin/components/ulw-loop/src/codex-goal-snapshot.ts +26 -1
  493. package/packages/omo-codex/plugin/components/ulw-loop/src/codex-hook.ts +3 -1
  494. package/packages/omo-codex/plugin/components/ulw-loop/src/constants.ts +1 -0
  495. package/packages/omo-codex/plugin/components/ulw-loop/src/domain-types.ts +19 -9
  496. package/packages/omo-codex/plugin/components/ulw-loop/src/paths.ts +25 -4
  497. package/packages/omo-codex/plugin/components/ulw-loop/src/plan-io.ts +39 -4
  498. package/packages/omo-codex/plugin/components/ulw-loop/src/plan-missing-recovery.ts +38 -0
  499. package/packages/omo-codex/plugin/components/ulw-loop/src/quality-gate-aggregate.ts +11 -0
  500. package/packages/omo-codex/plugin/components/ulw-loop/src/quality-gate-artifacts.ts +123 -0
  501. package/packages/omo-codex/plugin/components/ulw-loop/src/quality-gate-fields.ts +71 -15
  502. package/packages/omo-codex/plugin/components/ulw-loop/src/quality-gate-verdicts.ts +6 -1
  503. package/packages/omo-codex/plugin/components/ulw-loop/src/quality-gate.ts +92 -136
  504. package/packages/omo-codex/plugin/components/ulw-loop/src/review-blockers.ts +4 -2
  505. package/packages/omo-codex/plugin/components/ulw-loop/src/spawn-guard.ts +200 -28
  506. package/packages/omo-codex/plugin/components/ulw-loop/src/state-lock.ts +239 -0
  507. package/packages/omo-codex/plugin/components/ulw-loop/src/status-next-actions.ts +36 -0
  508. package/packages/omo-codex/plugin/components/ulw-loop/src/stop-resume-hook.ts +19 -6
  509. package/packages/omo-codex/plugin/components/ulw-loop/src/surface.ts +107 -0
  510. package/packages/omo-codex/plugin/components/ulw-loop/test/checkpoint-continuation.test.ts +0 -1
  511. package/packages/omo-codex/plugin/components/ulw-loop/test/checkpoint-final.test.ts +132 -1
  512. package/packages/omo-codex/plugin/components/ulw-loop/test/checkpoint-template.test.ts +147 -0
  513. package/packages/omo-codex/plugin/components/ulw-loop/test/cli-checkpoint-continuation.test.ts +4 -2
  514. package/packages/omo-codex/plugin/components/ulw-loop/test/cli-checkpoint.test.ts +4 -2
  515. package/packages/omo-codex/plugin/components/ulw-loop/test/cli-commands.test.ts +2 -0
  516. package/packages/omo-codex/plugin/components/ulw-loop/test/cli-complete-goals.test.ts +3 -1
  517. package/packages/omo-codex/plugin/components/ulw-loop/test/cli-create-goals.test.ts +35 -8
  518. package/packages/omo-codex/plugin/components/ulw-loop/test/cli-entrypoint.test.ts +38 -4
  519. package/packages/omo-codex/plugin/components/ulw-loop/test/cli-json-errors.test.ts +2 -0
  520. package/packages/omo-codex/plugin/components/ulw-loop/test/cli-scope-required.test.ts +144 -0
  521. package/packages/omo-codex/plugin/components/ulw-loop/test/cli-status-next-actions.test.ts +185 -0
  522. package/packages/omo-codex/plugin/components/ulw-loop/test/cli-steering-batch.test.ts +8 -3
  523. package/packages/omo-codex/plugin/components/ulw-loop/test/cli-validation-batch.test.ts +6 -0
  524. package/packages/omo-codex/plugin/components/ulw-loop/test/codex-goal-instruction.test.ts +37 -2
  525. package/packages/omo-codex/plugin/components/ulw-loop/test/codex-goal-snapshot.test.ts +18 -0
  526. package/packages/omo-codex/plugin/components/ulw-loop/test/codex-hook.test.ts +0 -3
  527. package/packages/omo-codex/plugin/components/ulw-loop/test/fixtures/cli-session.ts +4 -0
  528. package/packages/omo-codex/plugin/components/ulw-loop/test/fixtures/quality-gate-builder.ts +9 -4
  529. package/packages/omo-codex/plugin/components/ulw-loop/test/guided-recovery.test.ts +105 -0
  530. package/packages/omo-codex/plugin/components/ulw-loop/test/package-smoke.test.ts +5 -37
  531. package/packages/omo-codex/plugin/components/ulw-loop/test/paths.test.ts +9 -0
  532. package/packages/omo-codex/plugin/components/ulw-loop/test/plan-io-cross-process.test.ts +106 -0
  533. package/packages/omo-codex/plugin/components/ulw-loop/test/plan-io.test.ts +36 -2
  534. package/packages/omo-codex/plugin/components/ulw-loop/test/quality-gate-aggregate-basics.test.ts +258 -0
  535. package/packages/omo-codex/plugin/components/ulw-loop/test/quality-gate-cap-and-dedupe.test.ts +22 -0
  536. package/packages/omo-codex/plugin/components/ulw-loop/test/quality-gate-fields-messages.test.ts +98 -0
  537. package/packages/omo-codex/plugin/components/ulw-loop/test/quality-gate-lazycodex-surface.test.ts +93 -0
  538. package/packages/omo-codex/plugin/components/ulw-loop/test/quality-gate-poisoning-cascades.test.ts +97 -0
  539. package/packages/omo-codex/plugin/components/ulw-loop/test/quality-gate-roles.test.ts +51 -2
  540. package/packages/omo-codex/plugin/components/ulw-loop/test/quality-gate-senpi-surface.test.ts +131 -0
  541. package/packages/omo-codex/plugin/components/ulw-loop/test/quality-gate-single-report.test.ts +241 -0
  542. package/packages/omo-codex/plugin/components/ulw-loop/test/quality-gate.test.ts +58 -3
  543. package/packages/omo-codex/plugin/components/ulw-loop/test/spawn-guard.test.ts +423 -6
  544. package/packages/omo-codex/plugin/components/ulw-loop/test/state-lock.test.ts +218 -0
  545. package/packages/omo-codex/plugin/components/ulw-loop/test/steering.test.ts +8 -5
  546. package/packages/omo-codex/plugin/components/ulw-loop/test/stop-resume-hook.test.ts +1 -1
  547. package/packages/omo-codex/plugin/components/ulw-loop/test/surface.test.ts +74 -0
  548. package/packages/omo-codex/plugin/components/ulw-loop/test/ultrawork-directive.test.ts +13 -8
  549. package/packages/omo-codex/plugin/components/ulw-loop/vitest.config.ts +1 -0
  550. package/packages/omo-codex/plugin/hooks/post-compact-resetting-git-bash-mcp-reminder.json +1 -1
  551. package/packages/omo-codex/plugin/hooks/post-compact-resetting-lsp-diagnostics-cache.json +1 -1
  552. package/packages/omo-codex/plugin/hooks/post-compact-resetting-project-rule-cache.json +1 -1
  553. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-comments.json +1 -1
  554. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-lsp-diagnostics.json +1 -1
  555. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-thread-title-hygiene.json +1 -1
  556. package/packages/omo-codex/plugin/hooks/post-tool-use-matching-project-rules.json +1 -1
  557. package/packages/omo-codex/plugin/hooks/post-tool-use-recording-spawn-admission.json +18 -0
  558. package/packages/omo-codex/plugin/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json +1 -1
  559. package/packages/omo-codex/plugin/hooks/pre-tool-use-guarding-ulw-loop-spawns.json +1 -1
  560. package/packages/omo-codex/plugin/hooks/pre-tool-use-recommending-git-bash-mcp.json +1 -1
  561. package/packages/omo-codex/plugin/hooks/session-start-checking-auto-update.json +1 -1
  562. package/packages/omo-codex/plugin/hooks/session-start-checking-bootstrap-provisioning.json +1 -1
  563. package/packages/omo-codex/plugin/hooks/session-start-loading-project-rules.json +1 -1
  564. package/packages/omo-codex/plugin/hooks/session-start-recording-session-telemetry.json +1 -1
  565. package/packages/omo-codex/plugin/hooks/stop-checking-ulw-execute-continuation.json +17 -0
  566. package/packages/omo-codex/plugin/hooks/stop-checking-ulw-loop-resume.json +1 -1
  567. package/packages/omo-codex/plugin/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json +1 -1
  568. package/packages/omo-codex/plugin/hooks/user-prompt-submit-checking-ultrawork-trigger.json +1 -1
  569. package/packages/omo-codex/plugin/hooks/user-prompt-submit-checking-ulw-loop-steering.json +1 -1
  570. package/packages/omo-codex/plugin/hooks/user-prompt-submit-loading-project-rules.json +1 -1
  571. package/packages/omo-codex/plugin/model-catalog.json +16 -7
  572. package/packages/omo-codex/plugin/package-lock.json +676 -524
  573. package/packages/omo-codex/plugin/package.json +2 -3
  574. package/packages/omo-codex/plugin/scripts/AGENTS.md +39 -0
  575. package/packages/omo-codex/plugin/scripts/auto-update-plan.mjs +1 -2
  576. package/packages/omo-codex/plugin/scripts/auto-update.mjs +0 -9
  577. package/packages/omo-codex/plugin/scripts/canonical-ultrawork-directive.mjs +17 -0
  578. package/packages/omo-codex/plugin/scripts/hook-status-message.mjs +0 -1
  579. package/packages/omo-codex/plugin/scripts/migrate-codex-config/catalog.mjs +16 -7
  580. package/packages/omo-codex/plugin/scripts/migrate-codex-config/multi-agent-v2-guard.mjs +8 -4
  581. package/packages/omo-codex/plugin/scripts/migrate-codex-config/subagent-limit-guard.mjs +18 -90
  582. package/packages/omo-codex/plugin/scripts/migrate-codex-config/toml-section-editor.mjs +1 -1
  583. package/packages/omo-codex/plugin/scripts/sync-skills.mjs +94 -55
  584. package/packages/omo-codex/plugin/shared/package.json +3 -4
  585. package/packages/omo-codex/plugin/shared/src/config-loader.ts +2 -102
  586. package/packages/omo-codex/plugin/shared/src/config-migration.ts +0 -1
  587. package/packages/omo-codex/plugin/shared/test/config-loader.test.ts +41 -130
  588. package/packages/omo-codex/plugin/skills/ast-grep/AGENTS.md +51 -0
  589. package/packages/omo-codex/plugin/skills/ast-grep/SKILL.md +1 -1
  590. package/packages/omo-codex/plugin/skills/coding-agent-sessions/AGENTS.md +62 -0
  591. package/packages/omo-codex/plugin/skills/coding-agent-sessions/SKILL.md +3 -2
  592. package/packages/omo-codex/plugin/skills/coding-agent-sessions/references/all-platforms.md +1 -1
  593. package/packages/omo-codex/plugin/skills/coding-agent-sessions/references/senpi.md +4 -4
  594. package/packages/omo-codex/plugin/skills/coding-agent-sessions/scripts/agent_sessions/pi_family.py +1 -1
  595. package/packages/omo-codex/plugin/skills/data-scientist/SKILL.md +99 -239
  596. package/packages/omo-codex/plugin/skills/data-scientist/references/execution-surfaces.md +91 -0
  597. package/packages/omo-codex/plugin/skills/data-scientist/references/placement.md +74 -0
  598. package/packages/omo-codex/plugin/skills/data-scientist/references/polars-lane.md +95 -0
  599. package/packages/omo-codex/plugin/skills/data-scientist/references/uv-setup.md +1 -1
  600. package/packages/omo-codex/plugin/skills/data-scientist/references/visualization.md +64 -0
  601. package/packages/omo-codex/plugin/skills/data-scientist/scripts/ensure-js-deps.sh +28 -0
  602. package/packages/omo-codex/plugin/skills/data-scientist/scripts/ensure-py-deps.sh +37 -0
  603. package/packages/omo-codex/plugin/skills/debugging/SKILL.md +3 -1
  604. package/packages/omo-codex/plugin/skills/debugging/references/methodology/00-setup.md +12 -0
  605. package/packages/omo-codex/plugin/skills/debugging/references/methodology/02-investigate.md +21 -0
  606. package/packages/omo-codex/plugin/skills/debugging/references/runtimes/go.md +15 -1
  607. package/packages/omo-codex/plugin/skills/debugging/references/runtimes/native-binary.md +38 -0
  608. package/packages/omo-codex/plugin/skills/debugging/references/runtimes/node.md +25 -0
  609. package/packages/omo-codex/plugin/skills/debugging/references/runtimes/python.md +13 -0
  610. package/packages/omo-codex/plugin/skills/debugging/references/runtimes/rust.md +41 -0
  611. package/packages/omo-codex/plugin/skills/debugging/references/scripts/dap.mjs +267 -0
  612. package/packages/omo-codex/plugin/skills/debugging/references/scripts/fixture-adapter.mjs +59 -0
  613. package/packages/omo-codex/plugin/skills/debugging/references/tools/dap.md +103 -0
  614. package/packages/omo-codex/plugin/skills/debugging/references/tools/frida.md +193 -0
  615. package/packages/omo-codex/plugin/skills/frontend/SKILL.md +12 -8
  616. package/packages/omo-codex/plugin/skills/frontend/references/design/_INDEX.md +1 -0
  617. package/packages/omo-codex/plugin/skills/frontend/references/design/print-paged-media.md +76 -0
  618. package/packages/omo-codex/plugin/skills/frontend/references/design/stylegallery.md +80 -0
  619. package/packages/omo-codex/plugin/skills/frontend/references/designpowers/README.md +1 -1
  620. package/packages/omo-codex/plugin/skills/frontend/references/designpowers/lane-a-direction.md +1 -1
  621. package/packages/omo-codex/plugin/skills/frontend/references/designpowers/lane-b-execution.md +11 -11
  622. package/packages/omo-codex/plugin/skills/frontend/references/designpowers/lane-d-memory.md +3 -3
  623. package/packages/omo-codex/plugin/skills/frontend/references/designpowers/orchestration.md +1 -1
  624. package/packages/omo-codex/plugin/skills/frontend/references/designpowers/routing.md +5 -5
  625. package/packages/omo-codex/plugin/skills/git-master/SKILL.md +1 -1
  626. package/packages/omo-codex/plugin/skills/init-deep/SKILL.md +18 -16
  627. package/packages/omo-codex/plugin/skills/lcx-doctor/SKILL.md +4 -2
  628. package/packages/omo-codex/plugin/skills/lsp-setup/SKILL.md +1 -1
  629. package/packages/omo-codex/plugin/skills/programming/SKILL.md +1 -1
  630. package/packages/omo-codex/plugin/skills/refactor/SKILL.md +5 -3
  631. package/packages/omo-codex/plugin/skills/remove-ai-slops/SKILL.md +5 -3
  632. package/packages/omo-codex/plugin/skills/review-work/SKILL.md +114 -422
  633. package/packages/omo-codex/plugin/skills/ultimate-browsing/ATTRIBUTION.md +38 -11
  634. package/packages/omo-codex/plugin/skills/ultimate-browsing/SKILL.md +26 -9
  635. package/packages/omo-codex/plugin/skills/ultimate-browsing/engine/AGENTS.md +110 -0
  636. package/packages/omo-codex/plugin/skills/ultimate-browsing/engine/templates/package.json +1 -1
  637. package/packages/omo-codex/plugin/skills/ultimate-browsing/references/chrome-stealth.md +23 -18
  638. package/packages/omo-codex/plugin/skills/ultimate-browsing/references/insane-search/README.md +9 -2
  639. package/packages/omo-codex/plugin/skills/ultrawork/SKILL.md +26 -13
  640. package/packages/omo-codex/plugin/skills/{start-work → ulw-execute}/SKILL.md +26 -28
  641. package/packages/omo-codex/plugin/skills/ulw-execute/agents/openai.yaml +2 -0
  642. package/packages/omo-codex/plugin/skills/ulw-loop/SKILL.md +30 -4
  643. package/packages/omo-codex/plugin/skills/ulw-loop/references/define-goal.md +108 -0
  644. package/packages/omo-codex/plugin/skills/ulw-loop/references/full-workflow.md +32 -8
  645. package/packages/omo-codex/plugin/skills/ulw-plan/SKILL.md +6 -7
  646. package/packages/omo-codex/plugin/skills/ulw-plan/references/full-workflow.md +31 -7
  647. package/packages/omo-codex/plugin/skills/ulw-plan/references/intent-clear.md +2 -1
  648. package/packages/omo-codex/plugin/skills/ulw-plan/references/intent-unclear.md +5 -5
  649. package/packages/omo-codex/plugin/skills/ulw-research/SKILL.md +12 -5
  650. package/packages/omo-codex/plugin/skills/visual-qa/AGENTS.md +58 -0
  651. package/packages/omo-codex/plugin/skills/visual-qa/SKILL.md +8 -5
  652. package/packages/omo-codex/plugin/test/AGENTS.md +47 -0
  653. package/packages/omo-codex/plugin/test/aggregate-agents.test.mjs +19 -173
  654. package/packages/omo-codex/plugin/test/aggregate-hooks.test.mjs +16 -51
  655. package/packages/omo-codex/plugin/test/aggregate-manifest.test.mjs +2 -3
  656. package/packages/omo-codex/plugin/test/aggregate-mcp.test.mjs +2 -7
  657. package/packages/omo-codex/plugin/test/aggregate-model-catalog.test.mjs +14 -4
  658. package/packages/omo-codex/plugin/test/aggregate-plugin-fixture.mjs +175 -13
  659. package/packages/omo-codex/plugin/test/aggregate.test.mjs +78 -2
  660. package/packages/omo-codex/plugin/test/auto-update-release-notes.test.mjs +19 -33
  661. package/packages/omo-codex/plugin/test/auto-update.test.mjs +4 -29
  662. package/packages/omo-codex/plugin/test/bootstrap-setup.test.mjs +0 -31
  663. package/packages/omo-codex/plugin/test/canonical-ultrawork-directive.test.mjs +53 -0
  664. package/packages/omo-codex/plugin/test/component-bin-names.test.mjs +2 -2
  665. package/packages/omo-codex/plugin/test/component-bundled-cli.test.mjs +1 -51
  666. package/packages/omo-codex/plugin/test/component-hook-contract-cases.mjs +88 -2
  667. package/packages/omo-codex/plugin/test/hook-status-message.test.mjs +5 -6
  668. package/packages/omo-codex/plugin/test/lcx-contribute-bug-fix-template.test.mjs +21 -27
  669. package/packages/omo-codex/plugin/test/mcp-research-servers.test.mjs +1 -3
  670. package/packages/omo-codex/plugin/test/migrate-codex-config.test.mjs +35 -35
  671. package/packages/omo-codex/plugin/test/multi-agent-v2-regression.test.mjs +1 -1
  672. package/packages/omo-codex/plugin/test/scaffold-plan.test.mjs +0 -36
  673. package/packages/omo-codex/plugin/test/subagent-limit-migration.test.mjs +107 -15
  674. package/packages/omo-codex/plugin/test/sync-skills-codex-compatibility.test.mjs +168 -0
  675. package/packages/omo-codex/plugin/test/sync-skills-test-support.mjs +54 -24
  676. package/packages/omo-codex/plugin/test/sync-skills.test.mjs +18 -119
  677. package/packages/omo-codex/plugin/test/teammode-archive-ambiguity.test.mjs +0 -40
  678. package/packages/omo-codex/plugin/test/teammode-communication.test.mjs +6 -62
  679. package/packages/omo-codex/plugin/test/teammode-thread-links.test.mjs +3 -36
  680. package/packages/omo-codex/plugin/test/teammode-transport.test.mjs +0 -44
  681. package/packages/omo-codex/plugin/test/teammode-worktree.test.mjs +2 -6
  682. package/packages/omo-codex/plugin/test/ultrawork-skill-pointer.test.mjs +5 -5
  683. package/packages/omo-codex/plugin/test/ulw-plan-review-state-contract.test.mjs +0 -3
  684. package/packages/omo-codex/scripts/AGENTS.md +36 -0
  685. package/packages/omo-codex/scripts/check-model-catalog-parity.mjs +42 -0
  686. package/packages/omo-codex/scripts/install-cache-copy.test.mjs +27 -1
  687. package/packages/omo-codex/scripts/install-config-autonomous-features.test.mjs +1 -1
  688. package/packages/omo-codex/scripts/install-config-autonomous.test.mjs +2 -1
  689. package/packages/omo-codex/scripts/install-config-git-bash.test.mjs +0 -23
  690. package/packages/omo-codex/scripts/install-config-reasoning.test.mjs +5 -5
  691. package/packages/omo-codex/scripts/install-config.test.mjs +15 -17
  692. package/packages/omo-codex/scripts/install-dist/install-local.mjs +3028 -1392
  693. package/packages/omo-codex/scripts/install-generated-bundle.test.mjs +3 -4
  694. package/packages/omo-codex/scripts/install-git-bash-mcp-env.test.mjs +1 -25
  695. package/packages/omo-codex/scripts/install-lazycodex-version-stamp.test.mjs +7 -2
  696. package/packages/omo-codex/scripts/install-mcp-runtime.test.mjs +0 -36
  697. package/packages/omo-codex/scripts/install-packaged-local.test.mjs +1 -6
  698. package/packages/{omo-codex/plugin/components/ultrawork/skills/ultrawork/SKILL.md → prompts-core/prompts/ultrawork/codex.md} +26 -20
  699. package/packages/shared-skills/package.json +7 -1
  700. package/packages/shared-skills/skill-source-filter.d.ts +16 -0
  701. package/packages/shared-skills/skill-source-filter.mjs +44 -0
  702. package/packages/shared-skills/skills/ast-grep/AGENTS.md +51 -0
  703. package/packages/shared-skills/skills/ast-grep/SKILL.md +1 -1
  704. package/packages/shared-skills/skills/coding-agent-sessions/AGENTS.md +62 -0
  705. package/packages/shared-skills/skills/coding-agent-sessions/SKILL.md +3 -2
  706. package/packages/shared-skills/skills/coding-agent-sessions/references/all-platforms.md +1 -1
  707. package/packages/shared-skills/skills/coding-agent-sessions/references/senpi.md +4 -4
  708. package/packages/shared-skills/skills/coding-agent-sessions/scripts/agent_sessions/pi_family.py +1 -1
  709. package/packages/shared-skills/skills/data-scientist/SKILL.md +99 -239
  710. package/packages/shared-skills/skills/data-scientist/references/execution-surfaces.md +91 -0
  711. package/packages/shared-skills/skills/data-scientist/references/placement.md +74 -0
  712. package/packages/shared-skills/skills/data-scientist/references/polars-lane.md +95 -0
  713. package/packages/shared-skills/skills/data-scientist/references/uv-setup.md +1 -1
  714. package/packages/shared-skills/skills/data-scientist/references/visualization.md +64 -0
  715. package/packages/shared-skills/skills/data-scientist/scripts/ensure-js-deps.sh +28 -0
  716. package/packages/shared-skills/skills/data-scientist/scripts/ensure-py-deps.sh +37 -0
  717. package/packages/shared-skills/skills/debugging/SKILL.md +3 -1
  718. package/packages/shared-skills/skills/debugging/references/methodology/00-setup.md +12 -0
  719. package/packages/shared-skills/skills/debugging/references/methodology/02-investigate.md +21 -0
  720. package/packages/shared-skills/skills/debugging/references/runtimes/go.md +15 -1
  721. package/packages/shared-skills/skills/debugging/references/runtimes/native-binary.md +38 -0
  722. package/packages/shared-skills/skills/debugging/references/runtimes/node.md +25 -0
  723. package/packages/shared-skills/skills/debugging/references/runtimes/python.md +13 -0
  724. package/packages/shared-skills/skills/debugging/references/runtimes/rust.md +41 -0
  725. package/packages/shared-skills/skills/debugging/references/scripts/dap.mjs +267 -0
  726. package/packages/shared-skills/skills/debugging/references/scripts/dap.test.ts +86 -0
  727. package/packages/shared-skills/skills/debugging/references/scripts/fixture-adapter.mjs +59 -0
  728. package/packages/shared-skills/skills/debugging/references/tools/dap.md +103 -0
  729. package/packages/shared-skills/skills/debugging/references/tools/frida.md +193 -0
  730. package/packages/shared-skills/skills/frontend/SKILL.md +12 -8
  731. package/packages/shared-skills/skills/frontend/references/design/_INDEX.md +1 -0
  732. package/packages/shared-skills/skills/frontend/references/design/print-paged-media.md +76 -0
  733. package/packages/shared-skills/skills/frontend/references/design/stylegallery.md +80 -0
  734. package/packages/shared-skills/skills/frontend/references/designpowers/README.md +1 -1
  735. package/packages/shared-skills/skills/frontend/references/designpowers/lane-a-direction.md +1 -1
  736. package/packages/shared-skills/skills/frontend/references/designpowers/lane-b-execution.md +11 -11
  737. package/packages/shared-skills/skills/frontend/references/designpowers/lane-d-memory.md +3 -3
  738. package/packages/shared-skills/skills/frontend/references/designpowers/orchestration.md +1 -1
  739. package/packages/shared-skills/skills/frontend/references/designpowers/routing.md +5 -5
  740. package/packages/shared-skills/skills/git-master/SKILL.md +1 -1
  741. package/packages/shared-skills/skills/init-deep/SKILL.md +14 -14
  742. package/packages/shared-skills/skills/lsp-setup/SKILL.md +1 -1
  743. package/packages/shared-skills/skills/programming/SKILL.md +1 -1
  744. package/packages/shared-skills/skills/refactor/SKILL.md +1 -1
  745. package/packages/shared-skills/skills/remove-ai-slops/SKILL.md +1 -1
  746. package/packages/shared-skills/skills/review-work/SKILL.md +100 -418
  747. package/packages/shared-skills/skills/ultimate-browsing/ATTRIBUTION.md +38 -11
  748. package/packages/shared-skills/skills/ultimate-browsing/SKILL.md +26 -9
  749. package/packages/shared-skills/skills/ultimate-browsing/engine/AGENTS.md +110 -0
  750. package/packages/shared-skills/skills/ultimate-browsing/engine/templates/package.json +1 -1
  751. package/packages/shared-skills/skills/ultimate-browsing/references/chrome-stealth.md +23 -18
  752. package/packages/shared-skills/skills/ultimate-browsing/references/insane-search/README.md +9 -2
  753. package/packages/shared-skills/skills/{start-work → ulw-execute}/SKILL.md +17 -16
  754. package/packages/shared-skills/skills/ulw-plan/SKILL.md +7 -8
  755. package/packages/shared-skills/skills/ulw-plan/references/full-workflow.md +31 -7
  756. package/packages/shared-skills/skills/ulw-plan/references/intent-clear.md +2 -1
  757. package/packages/shared-skills/skills/ulw-plan/references/intent-unclear.md +5 -5
  758. package/packages/shared-skills/skills/ulw-research/SKILL.md +8 -3
  759. package/packages/shared-skills/skills/visual-qa/AGENTS.md +58 -0
  760. package/packages/shared-skills/skills/visual-qa/SKILL.md +4 -3
  761. package/postinstall.mjs +2 -0
  762. package/script/qa/web-terminal-visual-qa.mjs +2 -0
  763. package/script/qa/xterm-live-terminal.mjs +18 -2
  764. package/dist/config/schema/codegraph.d.ts +0 -12
  765. package/dist/config/schema/start-work.d.ts +0 -5
  766. package/dist/features/builtin-commands/templates/start-work.d.ts +0 -1
  767. package/dist/features/builtin-skills/index.d.ts +0 -1
  768. package/dist/features/builtin-skills/skill-file-loader.d.ts +0 -1
  769. package/dist/features/builtin-skills/skills/agent-browser-skill.d.ts +0 -1
  770. package/dist/features/builtin-skills/skills/agent-browser-template.d.ts +0 -1
  771. package/dist/features/builtin-skills/skills/debugging.d.ts +0 -1
  772. package/dist/features/builtin-skills/skills/dev-browser.d.ts +0 -1
  773. package/dist/features/builtin-skills/skills/frontend.d.ts +0 -1
  774. package/dist/features/builtin-skills/skills/git-master-sections/commit-atomic-planning.d.ts +0 -1
  775. package/dist/features/builtin-skills/skills/git-master-sections/commit-context-analysis.d.ts +0 -1
  776. package/dist/features/builtin-skills/skills/git-master-sections/commit-execution-verification.d.ts +0 -1
  777. package/dist/features/builtin-skills/skills/git-master-sections/commit-workflow.d.ts +0 -1
  778. package/dist/features/builtin-skills/skills/git-master-sections/history-search-workflow.d.ts +0 -1
  779. package/dist/features/builtin-skills/skills/git-master-sections/overview.d.ts +0 -1
  780. package/dist/features/builtin-skills/skills/git-master-sections/quick-reference.d.ts +0 -1
  781. package/dist/features/builtin-skills/skills/git-master-sections/rebase-workflow.d.ts +0 -1
  782. package/dist/features/builtin-skills/skills/git-master-skill-metadata.d.ts +0 -1
  783. package/dist/features/builtin-skills/skills/git-master.d.ts +0 -1
  784. package/dist/features/builtin-skills/skills/index.d.ts +0 -1
  785. package/dist/features/builtin-skills/skills/init-deep.d.ts +0 -1
  786. package/dist/features/builtin-skills/skills/playwright-cli.d.ts +0 -1
  787. package/dist/features/builtin-skills/skills/playwright-mcp-skill.d.ts +0 -1
  788. package/dist/features/builtin-skills/skills/playwright.d.ts +0 -1
  789. package/dist/features/builtin-skills/skills/remove-ai-slops.d.ts +0 -1
  790. package/dist/features/builtin-skills/skills/review-work.d.ts +0 -1
  791. package/dist/features/builtin-skills/skills/security-research.d.ts +0 -1
  792. package/dist/features/builtin-skills/skills/security-review.d.ts +0 -1
  793. package/dist/features/builtin-skills/skills/team-mode.d.ts +0 -1
  794. package/dist/features/builtin-skills/skills/visual-qa.d.ts +0 -1
  795. package/dist/features/builtin-skills/skills.d.ts +0 -1
  796. package/dist/features/builtin-skills/types.d.ts +0 -1
  797. package/dist/features/claude-code-plugin-loader/agent-loader.d.ts +0 -1
  798. package/dist/features/claude-code-plugin-loader/command-loader.d.ts +0 -1
  799. package/dist/features/claude-code-plugin-loader/discovery-core.d.ts +0 -1
  800. package/dist/features/claude-code-plugin-loader/discovery-paths.d.ts +0 -1
  801. package/dist/features/claude-code-plugin-loader/discovery.d.ts +0 -1
  802. package/dist/features/claude-code-plugin-loader/hook-loader.d.ts +0 -1
  803. package/dist/features/claude-code-plugin-loader/index.d.ts +0 -1
  804. package/dist/features/claude-code-plugin-loader/install-path-resolver.d.ts +0 -1
  805. package/dist/features/claude-code-plugin-loader/installed-plugin-database.d.ts +0 -1
  806. package/dist/features/claude-code-plugin-loader/loaded-plugin.d.ts +0 -1
  807. package/dist/features/claude-code-plugin-loader/loader.d.ts +0 -1
  808. package/dist/features/claude-code-plugin-loader/mcp-server-loader.d.ts +0 -1
  809. package/dist/features/claude-code-plugin-loader/plugin-key.d.ts +0 -1
  810. package/dist/features/claude-code-plugin-loader/plugin-manifest.d.ts +0 -1
  811. package/dist/features/claude-code-plugin-loader/plugin-path-resolver.d.ts +0 -1
  812. package/dist/features/claude-code-plugin-loader/plugin-settings.d.ts +0 -1
  813. package/dist/features/claude-code-plugin-loader/scope-filter.d.ts +0 -1
  814. package/dist/features/claude-code-plugin-loader/skill-loader.d.ts +0 -1
  815. package/dist/features/claude-code-plugin-loader/types.d.ts +0 -1
  816. package/dist/hooks/codegraph-bootstrap/command-runner.d.ts +0 -17
  817. package/dist/hooks/codegraph-bootstrap/hook.d.ts +0 -35
  818. package/dist/hooks/codegraph-bootstrap/index.d.ts +0 -1
  819. package/dist/hooks/codegraph-bootstrap/project-root.d.ts +0 -1
  820. package/dist/hooks/codegraph-bootstrap/status.d.ts +0 -11
  821. package/dist/hooks/ralph-loop/completion-promise-detector-test-input.d.ts +0 -11
  822. package/dist/hooks/ralph-loop/loop-session-recovery.d.ts +0 -7
  823. package/dist/hooks/start-work/start-work-hook.d.ts +0 -23
  824. package/dist/mcp/codegraph.d.ts +0 -16
  825. package/dist/plugin/chat-message/start-work-message.d.ts +0 -5
  826. package/dist/shared/prompt-async-gate/message-inspection-error.d.ts +0 -1
  827. package/dist/shared/prompt-async-gate/pending-tool-turn.d.ts +0 -1
  828. package/dist/shared/prompt-async-gate/prompt-message-state.d.ts +0 -1
  829. package/dist/shared/prompt-async-gate/queue.d.ts +0 -1
  830. package/dist/shared/prompt-async-gate/recent-dispatches.d.ts +0 -1
  831. package/dist/shared/prompt-async-gate/reservations.d.ts +0 -1
  832. package/dist/shared/prompt-async-gate/semantic-dedupe.d.ts +0 -1
  833. package/dist/shared/prompt-async-gate/session-idle-dispatch.d.ts +0 -1
  834. package/dist/shared/prompt-async-gate/timing.d.ts +0 -1
  835. package/dist/shared/prompt-async-gate/types.d.ts +0 -1
  836. package/dist/skills/data-scientist/references/common-scenarios.md +0 -176
  837. package/dist/skills/data-scientist/references/execution-templates.md +0 -197
  838. package/dist/skills/data-scientist/references/integration-patterns.md +0 -153
  839. package/dist/skills/data-scientist/references/performance-benchmarks.md +0 -37
  840. package/dist/tools/call-omo-agent/background-agent-executor.d.ts +0 -5
  841. package/dist/tools/call-omo-agent/message-storage-directory.d.ts +0 -1
  842. package/dist/tools/delegate-task/anthropic-categories.d.ts +0 -2
  843. package/dist/tools/delegate-task/model-string-parser.d.ts +0 -1
  844. package/packages/lsp-tools-mcp/dist/lsp/cleanup-errors.d.ts +0 -1
  845. package/packages/lsp-tools-mcp/dist/lsp/constants.d.ts +0 -1
  846. package/packages/lsp-tools-mcp/dist/lsp/language-mappings.d.ts +0 -1
  847. package/packages/lsp-tools-mcp/dist/lsp/process-signal-cleanup.d.ts +0 -1
  848. package/packages/lsp-tools-mcp/dist/missing-dependency-result.d.ts +0 -1
  849. package/packages/omo-codex/plugin/components/codegraph/AGENTS.md +0 -58
  850. package/packages/omo-codex/plugin/components/codegraph/NODE-RUNTIME-LICENSES.md +0 -2951
  851. package/packages/omo-codex/plugin/components/codegraph/NOTICE +0 -16
  852. package/packages/omo-codex/plugin/components/codegraph/dist/cli.js +0 -12136
  853. package/packages/omo-codex/plugin/components/codegraph/dist/serve.js +0 -9734
  854. package/packages/omo-codex/plugin/components/codegraph/package.json +0 -33
  855. package/packages/omo-codex/plugin/components/codegraph/src/cache-gc.ts +0 -29
  856. package/packages/omo-codex/plugin/components/codegraph/src/cli.ts +0 -79
  857. package/packages/omo-codex/plugin/components/codegraph/src/hook-input.ts +0 -33
  858. package/packages/omo-codex/plugin/components/codegraph/src/hook-sweep.ts +0 -25
  859. package/packages/omo-codex/plugin/components/codegraph/src/hook-types.ts +0 -131
  860. package/packages/omo-codex/plugin/components/codegraph/src/hook.ts +0 -258
  861. package/packages/omo-codex/plugin/components/codegraph/src/mcp-bridge.ts +0 -309
  862. package/packages/omo-codex/plugin/components/codegraph/src/mcp-unavailable.ts +0 -80
  863. package/packages/omo-codex/plugin/components/codegraph/src/post-tool-use-hook.ts +0 -34
  864. package/packages/omo-codex/plugin/components/codegraph/src/serve-invocation.ts +0 -29
  865. package/packages/omo-codex/plugin/components/codegraph/src/serve.ts +0 -263
  866. package/packages/omo-codex/plugin/components/codegraph/src/session-start-command.ts +0 -106
  867. package/packages/omo-codex/plugin/components/codegraph/src/session-start-cooldown.ts +0 -145
  868. package/packages/omo-codex/plugin/components/codegraph/src/session-start-hook-runtime.ts +0 -21
  869. package/packages/omo-codex/plugin/components/codegraph/src/session-start-lock.ts +0 -139
  870. package/packages/omo-codex/plugin/components/codegraph/src/session-start-outcome.ts +0 -15
  871. package/packages/omo-codex/plugin/components/codegraph/src/session-start-paths.ts +0 -32
  872. package/packages/omo-codex/plugin/components/codegraph/src/session-start-project.ts +0 -109
  873. package/packages/omo-codex/plugin/components/codegraph/src/session-start-worker-result.ts +0 -148
  874. package/packages/omo-codex/plugin/components/codegraph/src/session-start-worker.ts +0 -175
  875. package/packages/omo-codex/plugin/components/codegraph/src/sweep-cli.ts +0 -81
  876. package/packages/omo-codex/plugin/components/codegraph/test/cache-gc.test.ts +0 -34
  877. package/packages/omo-codex/plugin/components/codegraph/test/hook-exclusion.test.ts +0 -112
  878. package/packages/omo-codex/plugin/components/codegraph/test/hook-registration.test.ts +0 -26
  879. package/packages/omo-codex/plugin/components/codegraph/test/hook-session-start-guard.test.ts +0 -160
  880. package/packages/omo-codex/plugin/components/codegraph/test/hook-store-upgrade.test.ts +0 -50
  881. package/packages/omo-codex/plugin/components/codegraph/test/hook-sweep.test.ts +0 -29
  882. package/packages/omo-codex/plugin/components/codegraph/test/hook.test.ts +0 -320
  883. package/packages/omo-codex/plugin/components/codegraph/test/mcp-bridge-fixtures.ts +0 -172
  884. package/packages/omo-codex/plugin/components/codegraph/test/package-runtime.test.ts +0 -91
  885. package/packages/omo-codex/plugin/components/codegraph/test/provisioned-node-guard.test.ts +0 -100
  886. package/packages/omo-codex/plugin/components/codegraph/test/serve-built-wrapper.test.ts +0 -76
  887. package/packages/omo-codex/plugin/components/codegraph/test/serve-mcp-bridge-lifecycle.test.ts +0 -133
  888. package/packages/omo-codex/plugin/components/codegraph/test/serve-mcp-bridge.test.ts +0 -245
  889. package/packages/omo-codex/plugin/components/codegraph/test/serve-mcp-facade.test.ts +0 -69
  890. package/packages/omo-codex/plugin/components/codegraph/test/serve-node-support.test.ts +0 -43
  891. package/packages/omo-codex/plugin/components/codegraph/test/serve-provision.test.ts +0 -147
  892. package/packages/omo-codex/plugin/components/codegraph/test/serve-unavailable.test.ts +0 -175
  893. package/packages/omo-codex/plugin/components/codegraph/test/serve.test.ts +0 -385
  894. package/packages/omo-codex/plugin/components/codegraph/test/session-start-node-support.test.ts +0 -206
  895. package/packages/omo-codex/plugin/components/codegraph/test/session-start-project.test.ts +0 -58
  896. package/packages/omo-codex/plugin/components/codegraph/test/session-start-state.test.ts +0 -104
  897. package/packages/omo-codex/plugin/components/codegraph/test/session-start-trust-boundary.test.ts +0 -65
  898. package/packages/omo-codex/plugin/components/codegraph/test/session-start-worker-availability.test.ts +0 -106
  899. package/packages/omo-codex/plugin/components/codegraph/test/session-start-worker-cooldown.test.ts +0 -116
  900. package/packages/omo-codex/plugin/components/codegraph/test/session-start-worker-flow.test.ts +0 -258
  901. package/packages/omo-codex/plugin/components/codegraph/test/sweep-cli.test.ts +0 -56
  902. package/packages/omo-codex/plugin/components/codegraph/tsconfig.build.json +0 -13
  903. package/packages/omo-codex/plugin/components/codegraph/tsconfig.json +0 -25
  904. package/packages/omo-codex/plugin/components/start-work-continuation/LICENSE +0 -21
  905. package/packages/omo-codex/plugin/components/start-work-continuation/hooks/hooks.json +0 -28
  906. package/packages/omo-codex/plugin/components/ultrawork/directive.md +0 -471
  907. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-codegraph-init-guidance.json +0 -18
  908. package/packages/omo-codex/plugin/hooks/session-start-checking-codegraph-bootstrap.json +0 -17
  909. package/packages/omo-codex/plugin/hooks/stop-checking-start-work-continuation.json +0 -17
  910. package/packages/omo-codex/plugin/hooks/subagent-stop-checking-start-work-continuation.json +0 -17
  911. package/packages/omo-codex/plugin/scripts/migrate-omo-sot/editor.mjs +0 -125
  912. package/packages/omo-codex/plugin/scripts/migrate-omo-sot/jsonc.mjs +0 -43
  913. package/packages/omo-codex/plugin/scripts/migrate-omo-sot/scaffold.mjs +0 -29
  914. package/packages/omo-codex/plugin/scripts/migrate-omo-sot.mjs +0 -121
  915. package/packages/omo-codex/plugin/skills/data-scientist/references/common-scenarios.md +0 -176
  916. package/packages/omo-codex/plugin/skills/data-scientist/references/execution-templates.md +0 -197
  917. package/packages/omo-codex/plugin/skills/data-scientist/references/integration-patterns.md +0 -153
  918. package/packages/omo-codex/plugin/skills/data-scientist/references/performance-benchmarks.md +0 -37
  919. package/packages/omo-codex/plugin/skills/start-work/agents/openai.yaml +0 -2
  920. package/packages/omo-codex/plugin/test/aggregate-skills.test.mjs +0 -92
  921. package/packages/omo-codex/plugin/test/component-codegraph-mcp-smoke.test.mjs +0 -76
  922. package/packages/omo-codex/plugin/test/migrate-omo-sot.test.mjs +0 -179
  923. package/packages/omo-codex/plugin/test/sync-skills-orchestration.test.mjs +0 -314
  924. package/packages/omo-codex/plugin/test/ulw-plan-scope-contract.test.mjs +0 -24
  925. package/packages/shared-skills/skills/data-scientist/references/common-scenarios.md +0 -176
  926. package/packages/shared-skills/skills/data-scientist/references/execution-templates.md +0 -197
  927. package/packages/shared-skills/skills/data-scientist/references/integration-patterns.md +0 -153
  928. package/packages/shared-skills/skills/data-scientist/references/performance-benchmarks.md +0 -37
  929. /package/dist/hooks/{start-work → ulw-execute}/context-info-formatters.d.ts +0 -0
  930. /package/dist/hooks/{start-work → ulw-execute}/explicit-plan-context.d.ts +0 -0
  931. /package/dist/hooks/{start-work → ulw-execute}/notepad-scaffold.d.ts +0 -0
  932. /package/dist/hooks/{start-work → ulw-execute}/parse-user-request.d.ts +0 -0
  933. /package/dist/hooks/{start-work → ulw-execute}/plan-discovery-context.d.ts +0 -0
  934. /package/dist/hooks/{start-work → ulw-execute}/plan-selection.d.ts +0 -0
  935. /package/dist/hooks/{start-work → ulw-execute}/session-plan-affinity.d.ts +0 -0
  936. /package/dist/hooks/{start-work → ulw-execute}/work-initializer.d.ts +0 -0
  937. /package/dist/hooks/{start-work → ulw-execute}/worktree-block.d.ts +0 -0
  938. /package/dist/hooks/{start-work → ulw-execute}/worktree-detector.d.ts +0 -0
  939. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/.gitattributes +0 -0
  940. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/CHANGELOG.md +0 -0
  941. /package/packages/omo-codex/plugin/components/{codegraph → ulw-execute-continuation}/LICENSE +0 -0
  942. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/plan-checklist.ts +0 -0
  943. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/boulder-completed.json +0 -0
  944. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/boulder-mixed-platforms.json +0 -0
  945. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/boulder-single-codex-work.json +0 -0
  946. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/plan-all-done.md +0 -0
  947. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/plan-scaffold.md +0 -0
  948. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/plan-with-nested-checkboxes.md +0 -0
  949. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/plan-with-unchecked.md +0 -0
  950. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/tsconfig.build.json +0 -0
  951. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/tsconfig.json +0 -0
  952. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/vitest.config.ts +0 -0
@@ -1,18 +1,3 @@
1
- var __defProp = Object.defineProperty;
2
- var __returnValue = (v) => v;
3
- function __exportSetter(name, newValue) {
4
- this[name] = __returnValue.bind(null, newValue);
5
- }
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, {
9
- get: all[name],
10
- enumerable: true,
11
- configurable: true,
12
- set: __exportSetter.bind(all, name)
13
- });
14
- };
15
-
16
1
  // ../../../../telemetry-core/src/activity-state.ts
17
2
  import { existsSync, mkdirSync as mkdirSync2, readFileSync } from "node:fs";
18
3
  import { basename, join } from "node:path";
@@ -23,9 +8,12 @@ import {
23
8
  fsyncSync,
24
9
  openSync,
25
10
  renameSync,
11
+ rmSync,
26
12
  unlinkSync,
27
13
  writeFileSync
28
14
  } from "node:fs";
15
+ import { randomUUID } from "node:crypto";
16
+ import { dirname } from "node:path";
29
17
  var TOLERATED_FSYNC_CODES = new Set([
30
18
  "EPERM",
31
19
  "EACCES",
@@ -47,24 +35,36 @@ function tolerantFsyncSync(fileDescriptor, fsyncImpl) {
47
35
  }
48
36
  }
49
37
  function writeFileAtomically(filePath, content, options = {}) {
50
- const tempPath = `${filePath}.tmp`;
51
- writeFileSync(tempPath, content, "utf-8");
52
- const tempFileDescriptor = openSync(tempPath, "r+");
53
- try {
54
- tolerantFsyncSync(tempFileDescriptor, options.fsyncSync ?? fsyncSync);
55
- } finally {
56
- closeSync(tempFileDescriptor);
57
- }
38
+ const platform = options.platform ?? process.platform;
39
+ const fsyncImpl = options.fsyncSync ?? fsyncSync;
40
+ const tempPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
58
41
  try {
59
- renameSync(tempPath, filePath);
60
- } catch (error) {
61
- const isPermissionError = error instanceof Error && (error.message.includes("EPERM") || error.message.includes("EACCES"));
62
- if ((options.platform ?? process.platform) === "win32" && isPermissionError) {
42
+ writeFileSync(tempPath, content, "utf-8");
43
+ const tempFileDescriptor = openSync(tempPath, "r+");
44
+ try {
45
+ tolerantFsyncSync(tempFileDescriptor, fsyncImpl);
46
+ } finally {
47
+ closeSync(tempFileDescriptor);
48
+ }
49
+ try {
50
+ renameSync(tempPath, filePath);
51
+ } catch (error) {
52
+ const isPermissionError = error instanceof Error && (error.message.includes("EPERM") || error.message.includes("EACCES"));
53
+ if (platform !== "win32" || !isPermissionError)
54
+ throw error;
63
55
  unlinkSync(filePath);
64
56
  renameSync(tempPath, filePath);
57
+ }
58
+ if (platform === "win32")
65
59
  return;
60
+ const directoryFileDescriptor = openSync(dirname(filePath), "r");
61
+ try {
62
+ tolerantFsyncSync(directoryFileDescriptor, fsyncImpl);
63
+ } finally {
64
+ closeSync(directoryFileDescriptor);
66
65
  }
67
- throw error;
66
+ } finally {
67
+ rmSync(tempPath, { force: true });
68
68
  }
69
69
  }
70
70
 
@@ -170,6 +170,7 @@ function writePostHogActivityState(stateDir, nextState, diagnostics) {
170
170
  // ../../../../telemetry-core/src/constants.ts
171
171
  var DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com";
172
172
  var DEFAULT_POSTHOG_API_KEY = "phc_CFJhj5HyvA62QPhvyaUCtaq23aUfznnijg5VaaGkNk74";
173
+ var UNCONFIGURED_POSTHOG_API_KEY = "phc_REPLACE_ME_OMO_NATIVE";
173
174
 
174
175
  // ../../../../telemetry-core/src/diagnostics.ts
175
176
  import { appendFileSync, existsSync as existsSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync2 } from "node:fs";
@@ -306,6 +307,9 @@ function shouldDisableTelemetry(input) {
306
307
  const env = input.env ?? process.env;
307
308
  const globalPrefix = input.globalEnvPrefix ?? "OMO";
308
309
  const prefixes = Array.from(new Set([globalPrefix, input.productEnvPrefix]));
310
+ if (isDisableFlag(env["DO_NOT_TRACK"])) {
311
+ return true;
312
+ }
309
313
  for (const prefix of prefixes) {
310
314
  if (isDisableFlag(env[`${prefix}_DISABLE_POSTHOG`])) {
311
315
  return true;
@@ -319,22 +323,19 @@ function shouldDisableTelemetry(input) {
319
323
  function getTelemetryApiKey(env = process.env, defaultApiKey = DEFAULT_POSTHOG_API_KEY) {
320
324
  return env["POSTHOG_API_KEY"]?.trim() ?? defaultApiKey;
321
325
  }
322
- function getTelemetryHost(env = process.env, defaultHost = DEFAULT_POSTHOG_HOST) {
323
- return env["POSTHOG_HOST"]?.trim() || defaultHost;
326
+ function isConfiguredTelemetryApiKey(apiKey) {
327
+ const normalized = apiKey.trim();
328
+ return normalized.length > 0 && normalized !== UNCONFIGURED_POSTHOG_API_KEY;
324
329
  }
325
-
326
- // ../../../../telemetry-core/src/machine-id.ts
327
- import { createHash } from "node:crypto";
328
- import os2 from "node:os";
329
- function getDefaultTelemetryOsProvider() {
330
- return os2;
330
+ function hasTelemetryApiKey(env, defaultApiKey) {
331
+ return isConfiguredTelemetryApiKey(getTelemetryApiKey(env, defaultApiKey));
331
332
  }
332
- function getTelemetryDistinctId(machineIdPrefix, osProvider = getDefaultTelemetryOsProvider()) {
333
- return createHash("sha256").update(`${machineIdPrefix}${osProvider.hostname()}`).digest("hex");
333
+ function getTelemetryHost(env = process.env, defaultHost = DEFAULT_POSTHOG_HOST) {
334
+ return env["POSTHOG_HOST"]?.trim() || defaultHost;
334
335
  }
335
336
 
336
- // ../../../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs
337
- import { dirname, posix, sep } from "path";
337
+ // ../../../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs
338
+ import { dirname as dirname2, posix, sep } from "path";
338
339
  function createModulerModifier() {
339
340
  const getModuleFromFileName = createGetModuleFromFilename();
340
341
  return async (frames) => {
@@ -343,7 +344,7 @@ function createModulerModifier() {
343
344
  return frames;
344
345
  };
345
346
  }
346
- function createGetModuleFromFilename(basePath = process.argv[1] ? dirname(process.argv[1]) : process.cwd(), isWindows = sep === "\\") {
347
+ function createGetModuleFromFilename(basePath = process.argv[1] ? dirname2(process.argv[1]) : process.cwd(), isWindows = sep === "\\") {
347
348
  const normalizedBase = isWindows ? normalizeWindowsPath(basePath) : basePath;
348
349
  return (filename) => {
349
350
  if (!filename)
@@ -365,11 +366,11 @@ function createGetModuleFromFilename(basePath = process.argv[1] ? dirname(proces
365
366
  return decodedFile;
366
367
  };
367
368
  }
368
- function normalizeWindowsPath(path2) {
369
- return path2.replace(/^[A-Z]:/, "").replace(/\\/g, "/");
369
+ function normalizeWindowsPath(path) {
370
+ return path.replace(/^[A-Z]:/, "").replace(/\\/g, "/");
370
371
  }
371
372
 
372
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/featureFlagUtils.mjs
373
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/featureFlagUtils.mjs
373
374
  var normalizeFlagsResponse = (flagsResponse) => {
374
375
  if ("flags" in flagsResponse) {
375
376
  const featureFlags = getFlagValuesFromFlags(flagsResponse.flags);
@@ -439,8 +440,69 @@ var parsePayload = (response) => {
439
440
  return response;
440
441
  }
441
442
  };
443
+ var MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES = [
444
+ "utm_source",
445
+ "utm_medium",
446
+ "utm_campaign",
447
+ "utm_content",
448
+ "utm_term",
449
+ "gad_source",
450
+ "mc_cid",
451
+ "gclid",
452
+ "gclsrc",
453
+ "dclid",
454
+ "gbraid",
455
+ "wbraid",
456
+ "fbclid",
457
+ "msclkid",
458
+ "twclid",
459
+ "li_fat_id",
460
+ "igshid",
461
+ "ttclid",
462
+ "rdt_cid",
463
+ "epik",
464
+ "qclid",
465
+ "sccid",
466
+ "irclid",
467
+ "_kx"
468
+ ];
469
+ var MINIMAL_FLAG_CALLED_EVENT_PROPERTIES = [
470
+ "$feature_flag",
471
+ "$feature_flag_response",
472
+ "$feature_flag_has_experiment",
473
+ "$feature_flag_id",
474
+ "$feature_flag_version",
475
+ "$feature_flag_reason",
476
+ "$feature_flag_request_id",
477
+ "$feature_flag_evaluated_at",
478
+ "$feature_flag_error",
479
+ "locally_evaluated",
480
+ "$groups",
481
+ "$process_person_profile",
482
+ "$geoip_disable",
483
+ "$current_url",
484
+ "$pathname",
485
+ "$referring_domain",
486
+ ...MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES,
487
+ "$session_id",
488
+ "$window_id",
489
+ "$lib",
490
+ "$lib_version",
491
+ "$device_id",
492
+ "$is_server"
493
+ ];
494
+ var minimizeFlagCalledEventProperties = (properties, transportKeys = []) => {
495
+ const minimal = {};
496
+ const copyKey = (key) => {
497
+ if (properties[key] !== undefined)
498
+ minimal[key] = properties[key];
499
+ };
500
+ MINIMAL_FLAG_CALLED_EVENT_PROPERTIES.forEach(copyKey);
501
+ transportKeys.forEach(copyKey);
502
+ return minimal;
503
+ };
442
504
 
443
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/types.mjs
505
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/types.mjs
444
506
  var types_PostHogPersistedProperty = /* @__PURE__ */ function(PostHogPersistedProperty) {
445
507
  PostHogPersistedProperty["AnonymousId"] = "anonymous_id";
446
508
  PostHogPersistedProperty["DistinctId"] = "distinct_id";
@@ -455,6 +517,8 @@ var types_PostHogPersistedProperty = /* @__PURE__ */ function(PostHogPersistedPr
455
517
  PostHogPersistedProperty["BootstrapFeatureFlagPayloads"] = "bootstrap_feature_flag_payloads";
456
518
  PostHogPersistedProperty["OverrideFeatureFlags"] = "override_feature_flags";
457
519
  PostHogPersistedProperty["Queue"] = "queue";
520
+ PostHogPersistedProperty["AiQueue"] = "ai_queue";
521
+ PostHogPersistedProperty["AiCaptureQueue"] = "ai_capture_queue";
458
522
  PostHogPersistedProperty["LogsQueue"] = "logs_queue";
459
523
  PostHogPersistedProperty["OptedOut"] = "opted_out";
460
524
  PostHogPersistedProperty["SessionId"] = "session_id";
@@ -465,6 +529,8 @@ var types_PostHogPersistedProperty = /* @__PURE__ */ function(PostHogPersistedPr
465
529
  PostHogPersistedProperty["InstalledAppBuild"] = "installed_app_build";
466
530
  PostHogPersistedProperty["InstalledAppVersion"] = "installed_app_version";
467
531
  PostHogPersistedProperty["SessionReplay"] = "session_replay";
532
+ PostHogPersistedProperty["PushRegistered"] = "push_registered";
533
+ PostHogPersistedProperty["SessionReplayEventTriggerActivatedSession"] = "session_replay_event_trigger_activated_session";
468
534
  PostHogPersistedProperty["SurveyLastSeenDate"] = "survey_last_seen_date";
469
535
  PostHogPersistedProperty["SurveysSeen"] = "surveys_seen";
470
536
  PostHogPersistedProperty["Surveys"] = "surveys";
@@ -474,7 +540,7 @@ var types_PostHogPersistedProperty = /* @__PURE__ */ function(PostHogPersistedPr
474
540
  return PostHogPersistedProperty;
475
541
  }({});
476
542
 
477
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/gzip.mjs
543
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/gzip.mjs
478
544
  function isGzipSupported() {
479
545
  return "CompressionStream" in globalThis && "TextEncoder" in globalThis && "Response" in globalThis && typeof Response.prototype.blob == "function";
480
546
  }
@@ -524,7 +590,7 @@ var validateNativeGzip = async (compressed, inputBytes) => {
524
590
  async function gzipCompress(input, isDebug = true, options) {
525
591
  try {
526
592
  const inputBytes = new TextEncoder().encode(input);
527
- const compressedStream = new CompressionStream("gzip");
593
+ const compressedStream = new globalThis.CompressionStream("gzip");
528
594
  const writer = compressedStream.writable.getWriter();
529
595
  const writePromise = writer.write(inputBytes).then(() => writer.close()).catch(async (err) => {
530
596
  try {
@@ -548,7 +614,34 @@ async function gzipCompress(input, isDebug = true, options) {
548
614
  }
549
615
  }
550
616
 
551
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/bot-detection.mjs
617
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/json-utils.mjs
618
+ var MAX_JSON_SAFE_VALUE_DEPTH = 20;
619
+ var MAX_JSON_SAFE_VALUE_ITEMS = 1000;
620
+ var MAX_JSON_SAFE_VALUE_NODES = 1e4;
621
+ var CIRCULAR_VALUE = "[Circular]";
622
+ var TRUNCATED_VALUE = "[Truncated]";
623
+ var UNSERIALIZABLE_VALUE = "[Unserializable]";
624
+ var FUNCTION_VALUE = "[Function]";
625
+ var dateGetTime = Date.prototype.getTime;
626
+ var dateToISOString = Date.prototype.toISOString;
627
+ function sanitizeString(value) {
628
+ let output = "";
629
+ for (let index = 0;index < value.length; index++) {
630
+ const codeUnit = value.charCodeAt(index);
631
+ if (codeUnit >= 55296 && codeUnit <= 56319) {
632
+ const nextCodeUnit = value.charCodeAt(index + 1);
633
+ if (nextCodeUnit >= 56320 && nextCodeUnit <= 57343) {
634
+ output += value[index] + value[index + 1];
635
+ index++;
636
+ } else
637
+ output += "�";
638
+ } else
639
+ output += codeUnit >= 56320 && codeUnit <= 57343 ? "�" : value[index];
640
+ }
641
+ return output;
642
+ }
643
+
644
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/bot-detection.mjs
552
645
  var DEFAULT_BLOCKED_UA_STRS = [
553
646
  "amazonbot",
554
647
  "amazonproductbot",
@@ -637,7 +730,31 @@ var isBlockedUA = function(ua, customBlockedUserAgents = []) {
637
730
  return uaLower.indexOf(blockedUaLower) !== -1;
638
731
  });
639
732
  };
640
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/type-utils.mjs
733
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/string-utils.mjs
734
+ function safeJsonStringify(value) {
735
+ const ancestors = [];
736
+ return JSON.stringify(value, function(_key, replacementValue) {
737
+ if (typeof replacementValue == "bigint")
738
+ return replacementValue.toString();
739
+ if (typeof replacementValue == "function" || typeof replacementValue == "symbol")
740
+ return;
741
+ if (replacementValue instanceof Error)
742
+ return {
743
+ name: replacementValue.name,
744
+ message: replacementValue.message,
745
+ stack: replacementValue.stack
746
+ };
747
+ if (replacementValue && typeof replacementValue == "object") {
748
+ while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this)
749
+ ancestors.pop();
750
+ if (ancestors.includes(replacementValue))
751
+ return "[Circular]";
752
+ ancestors.push(replacementValue);
753
+ }
754
+ return replacementValue;
755
+ }) ?? "null";
756
+ }
757
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/type-utils.mjs
641
758
  var nativeIsArray = Array.isArray;
642
759
  var ObjProto = Object.prototype;
643
760
  var type_utils_hasOwnProperty = ObjProto.hasOwnProperty;
@@ -649,16 +766,27 @@ var isObject = (x) => x === Object(x) && !isArray(x);
649
766
  var isUndefined = (x) => x === undefined;
650
767
  var isString = (x) => type_utils_toString.call(x) == "[object String]";
651
768
  var isEmptyString = (x) => isString(x) && x.trim().length === 0;
769
+ var isNull = (x) => x === null;
770
+ var isNullish = (x) => isUndefined(x) || isNull(x);
652
771
  var isNumber = (x) => type_utils_toString.call(x) == "[object Number]" && x === x;
653
- var isPlainError = (x) => x instanceof Error;
772
+ var isBoolean = (x) => type_utils_toString.call(x) === "[object Boolean]";
654
773
  function isPrimitive(value) {
655
774
  return value === null || typeof value != "object";
656
775
  }
657
776
  function isBuiltin(candidate, className) {
658
777
  return Object.prototype.toString.call(candidate) === `[object ${className}]`;
659
778
  }
660
- function isErrorEvent(event) {
661
- return isBuiltin(event, "ErrorEvent");
779
+ function isError(candidate) {
780
+ switch (Object.prototype.toString.call(candidate)) {
781
+ case "[object Error]":
782
+ case "[object Exception]":
783
+ case "[object DOMException]":
784
+ case "[object DOMError]":
785
+ case "[object WebAssembly.Exception]":
786
+ return true;
787
+ default:
788
+ return isInstanceOf(candidate, Error);
789
+ }
662
790
  }
663
791
  function isEvent(candidate) {
664
792
  return typeof Event != "undefined" && isInstanceOf(candidate, Event);
@@ -674,7 +802,7 @@ function isInstanceOf(candidate, base) {
674
802
  }
675
803
  }
676
804
 
677
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/number-utils.mjs
805
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/number-utils.mjs
678
806
  function clampToRange(value, min, max, logger, fallbackValue) {
679
807
  if (min > max) {
680
808
  logger.warn("min cannot be greater than max.");
@@ -694,8 +822,16 @@ function clampToRange(value, min, max, logger, fallbackValue) {
694
822
  return clampToRange(fallbackValue || max, min, max, logger);
695
823
  }
696
824
 
697
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/bucketed-rate-limiter.mjs
825
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/bucketed-rate-limiter.mjs
698
826
  var ONE_DAY_IN_MS = 86400000;
827
+ var DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE = 1;
828
+ var DEFAULT_EXCEPTION_RATE_LIMITER_BUCKET_SIZE = 10;
829
+ function resolveExceptionRateLimiterConfig(config = {}) {
830
+ return {
831
+ refillRate: config.exceptionRateLimiterRefillRate ?? config.__exceptionRateLimiterRefillRate ?? DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE,
832
+ bucketSize: config.exceptionRateLimiterBucketSize ?? config.__exceptionRateLimiterBucketSize ?? DEFAULT_EXCEPTION_RATE_LIMITER_BUCKET_SIZE
833
+ };
834
+ }
699
835
 
700
836
  class BucketedRateLimiter {
701
837
  constructor(options) {
@@ -738,7 +874,7 @@ class BucketedRateLimiter {
738
874
  this._buckets = {};
739
875
  }
740
876
  }
741
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/vendor/uuidv7.mjs
877
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/vendor/uuidv7.mjs
742
878
  /*! For license information please see uuidv7.mjs.LICENSE.txt */
743
879
  var DIGITS = "0123456789abcdef";
744
880
 
@@ -916,33 +1052,45 @@ var defaultGenerator;
916
1052
  var uuidv7 = () => uuidv7obj().toString();
917
1053
  var uuidv7obj = () => (defaultGenerator || (defaultGenerator = new V7Generator)).generate();
918
1054
 
919
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/promise-queue.mjs
1055
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/promise-queue.mjs
920
1056
  class PromiseQueue {
921
1057
  add(promise) {
922
1058
  const promiseUUID = uuidv7();
923
- this.promiseByIds[promiseUUID] = promise;
1059
+ const id = ++this.nextId;
1060
+ this.promiseByIds[promiseUUID] = {
1061
+ id,
1062
+ promise
1063
+ };
924
1064
  promise.catch(() => {}).finally(() => {
925
1065
  delete this.promiseByIds[promiseUUID];
926
1066
  });
927
1067
  return promise;
928
1068
  }
929
1069
  async join() {
930
- let promises = Object.values(this.promiseByIds);
1070
+ let promises = Object.values(this.promiseByIds).map((item) => item.promise);
931
1071
  let length = promises.length;
932
1072
  while (length > 0) {
933
1073
  await Promise.all(promises);
934
- promises = Object.values(this.promiseByIds);
1074
+ promises = Object.values(this.promiseByIds).map((item) => item.promise);
935
1075
  length = promises.length;
936
1076
  }
937
1077
  }
1078
+ getPromises(ignoredPromises = [], maxId = this.nextId) {
1079
+ const ignoredPromiseSet = new Set(ignoredPromises);
1080
+ return Object.values(this.promiseByIds).filter((item) => item.id <= maxId && !ignoredPromiseSet.has(item.promise)).map((item) => item.promise);
1081
+ }
1082
+ get maxId() {
1083
+ return this.nextId;
1084
+ }
938
1085
  get length() {
939
1086
  return Object.keys(this.promiseByIds).length;
940
1087
  }
941
1088
  constructor() {
942
1089
  this.promiseByIds = {};
1090
+ this.nextId = 0;
943
1091
  }
944
1092
  }
945
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/logger.mjs
1093
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/logger.mjs
946
1094
  function createConsole(consoleLike = console) {
947
1095
  const lockedMethods = {
948
1096
  log: consoleLike.log.bind(consoleLike),
@@ -983,7 +1131,7 @@ var passThrough = (fn) => fn();
983
1131
  function createLogger(prefix, maybeCall = passThrough) {
984
1132
  return _createLogger(prefix, maybeCall, createConsole());
985
1133
  }
986
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/user-agent-utils.mjs
1134
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/user-agent-utils.mjs
987
1135
  var MOBILE = "Mobile";
988
1136
  var IOS = "iOS";
989
1137
  var ANDROID = "Android";
@@ -1026,6 +1174,7 @@ var DUCKDUCKGO = "DuckDuckGo";
1026
1174
  var PALE_MOON = "Pale Moon";
1027
1175
  var WATERFOX = "Waterfox";
1028
1176
  var BRAVE = "Brave";
1177
+ var GOOGLE_SEARCH_APP = "Google Search App";
1029
1178
  var BROWSER_VERSION_REGEX_SUFFIX = "(\\d+(\\.\\d+)?)";
1030
1179
  var DEFAULT_BROWSER_VERSION_REGEX = new RegExp("Version/" + BROWSER_VERSION_REGEX_SUFFIX);
1031
1180
  var XBOX_REGEX = new RegExp(XBOX, "i");
@@ -1113,6 +1262,9 @@ var versionRegexes = {
1113
1262
  [WATERFOX]: [
1114
1263
  new RegExp(WATERFOX + "\\/" + BROWSER_VERSION_REGEX_SUFFIX)
1115
1264
  ],
1265
+ [GOOGLE_SEARCH_APP]: [
1266
+ new RegExp("GSA\\/" + BROWSER_VERSION_REGEX_SUFFIX)
1267
+ ],
1116
1268
  [INTERNET_EXPLORER]: [
1117
1269
  new RegExp("(rv:|MSIE )" + BROWSER_VERSION_REGEX_SUFFIX)
1118
1270
  ],
@@ -1272,8 +1424,15 @@ var osMatchers = [
1272
1424
  ]
1273
1425
  ];
1274
1426
 
1275
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/index.mjs
1427
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/index.mjs
1276
1428
  var STRING_FORMAT = "utf8";
1429
+ var UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1430
+ function isValidUUID(value) {
1431
+ return typeof value == "string" && UUID_REGEX.test(value);
1432
+ }
1433
+ function getEventUuid(uuid, generateUuid) {
1434
+ return isValidUUID(uuid) ? uuid : generateUuid();
1435
+ }
1277
1436
  function removeTrailingSlash(url) {
1278
1437
  return url?.replace(/\/+$/, "");
1279
1438
  }
@@ -1301,7 +1460,26 @@ function safeSetTimeout(fn, timeout) {
1301
1460
  t?.unref && t?.unref();
1302
1461
  return t;
1303
1462
  }
1304
- var isError = (x) => x instanceof Error;
1463
+ async function raceWithTimeout(promise, timeoutMs, onTimeout) {
1464
+ let timeoutHandle;
1465
+ try {
1466
+ return await Promise.race([
1467
+ promise,
1468
+ new Promise((resolve, reject) => {
1469
+ timeoutHandle = safeSetTimeout(() => {
1470
+ try {
1471
+ onTimeout?.();
1472
+ resolve();
1473
+ } catch (error) {
1474
+ reject(error);
1475
+ }
1476
+ }, timeoutMs);
1477
+ })
1478
+ ]);
1479
+ } finally {
1480
+ clearTimeout(timeoutHandle);
1481
+ }
1482
+ }
1305
1483
  function allSettled(promises) {
1306
1484
  return Promise.all(promises.map((p) => (p ?? Promise.resolve()).then((value) => ({
1307
1485
  status: "fulfilled",
@@ -1312,7 +1490,7 @@ function allSettled(promises) {
1312
1490
  }))));
1313
1491
  }
1314
1492
 
1315
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/logs/logs-utils.mjs
1493
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/logs/logs-utils.mjs
1316
1494
  var OTLP_SEVERITY_MAP = {
1317
1495
  trace: {
1318
1496
  text: "TRACE",
@@ -1340,7 +1518,570 @@ var OTLP_SEVERITY_MAP = {
1340
1518
  }
1341
1519
  };
1342
1520
  var DEFAULT_OTLP_SEVERITY = OTLP_SEVERITY_MAP.info;
1343
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/eventemitter.mjs
1521
+ var INT64_RANGE_LIMIT = 9223372036854776000;
1522
+ var propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
1523
+ function newState() {
1524
+ return {
1525
+ ancestors: new WeakSet,
1526
+ remainingNodes: MAX_JSON_SAFE_VALUE_NODES
1527
+ };
1528
+ }
1529
+ function toOtlpKeyValueList(attrs, logger) {
1530
+ try {
1531
+ return encodeKeyValueList(attrs, logger, newState(), 0);
1532
+ } catch {
1533
+ return [];
1534
+ }
1535
+ }
1536
+ function encodeAnyValue(value, logger, state, depth) {
1537
+ if (state.remainingNodes <= 0)
1538
+ return {
1539
+ stringValue: TRUNCATED_VALUE
1540
+ };
1541
+ state.remainingNodes--;
1542
+ if (isBoolean(value))
1543
+ return {
1544
+ boolValue: value
1545
+ };
1546
+ if (typeof value == "number") {
1547
+ if (!Number.isFinite(value))
1548
+ return {
1549
+ stringValue: String(value)
1550
+ };
1551
+ if (Number.isInteger(value)) {
1552
+ if (Number.isSafeInteger(value))
1553
+ return {
1554
+ intValue: String(value)
1555
+ };
1556
+ if (typeof BigInt == "undefined")
1557
+ return {
1558
+ stringValue: String(value)
1559
+ };
1560
+ const decimal = BigInt(value).toString();
1561
+ if (value >= INT64_RANGE_LIMIT || value < -INT64_RANGE_LIMIT) {
1562
+ logger?.debug(`Attribute ${decimal} is outside the int64 range; encoding it as a string`);
1563
+ return {
1564
+ stringValue: decimal
1565
+ };
1566
+ }
1567
+ return {
1568
+ intValue: decimal
1569
+ };
1570
+ }
1571
+ return {
1572
+ doubleValue: value
1573
+ };
1574
+ }
1575
+ if (typeof value == "string")
1576
+ return {
1577
+ stringValue: sanitizeString(value)
1578
+ };
1579
+ if (typeof value == "function")
1580
+ return {
1581
+ stringValue: FUNCTION_VALUE
1582
+ };
1583
+ if (typeof value == "symbol")
1584
+ return {
1585
+ stringValue: String(value)
1586
+ };
1587
+ if (typeof value == "object" && value !== null) {
1588
+ if (state.ancestors.has(value))
1589
+ return {
1590
+ stringValue: CIRCULAR_VALUE
1591
+ };
1592
+ if (depth >= MAX_JSON_SAFE_VALUE_DEPTH)
1593
+ return {
1594
+ stringValue: TRUNCATED_VALUE
1595
+ };
1596
+ if (value instanceof Date) {
1597
+ const time = value.getTime();
1598
+ const iso = Number.isFinite(time) ? value.toISOString() : String(value);
1599
+ return {
1600
+ stringValue: typeof iso == "string" ? sanitizeString(iso) : String(iso)
1601
+ };
1602
+ }
1603
+ state.ancestors.add(value);
1604
+ try {
1605
+ try {
1606
+ const toJSON = value.toJSON;
1607
+ if (typeof toJSON == "function")
1608
+ return encodeAnyValue(toJSON.call(value), logger, state, depth + 1);
1609
+ } catch {}
1610
+ if (isArray(value))
1611
+ return {
1612
+ arrayValue: {
1613
+ values: encodeArrayValues(value, logger, state, depth + 1)
1614
+ }
1615
+ };
1616
+ return {
1617
+ kvlistValue: {
1618
+ values: encodeKeyValueList(value, logger, state, depth + 1)
1619
+ }
1620
+ };
1621
+ } finally {
1622
+ state.ancestors.delete(value);
1623
+ }
1624
+ }
1625
+ return {
1626
+ stringValue: sanitizeString(String(value))
1627
+ };
1628
+ }
1629
+ function encodeArrayValues(values, logger, state, depth) {
1630
+ const result = [];
1631
+ const itemCount = Math.min(values.length, MAX_JSON_SAFE_VALUE_ITEMS);
1632
+ let index = 0;
1633
+ for (;index < itemCount && state.remainingNodes > 0; index++)
1634
+ try {
1635
+ const element = index in values ? values[index] : undefined;
1636
+ if (isNullish(element))
1637
+ continue;
1638
+ result.push(encodeAnyValue(element, logger, state, depth));
1639
+ } catch {
1640
+ result.push({
1641
+ stringValue: UNSERIALIZABLE_VALUE
1642
+ });
1643
+ }
1644
+ if (values.length > index)
1645
+ result.push({
1646
+ stringValue: TRUNCATED_VALUE
1647
+ });
1648
+ return result;
1649
+ }
1650
+ function encodeKeyValueList(attrs, logger, state, depth) {
1651
+ const result = [];
1652
+ for (const key in attrs)
1653
+ if (propertyIsEnumerable.call(attrs, key)) {
1654
+ if (result.length >= MAX_JSON_SAFE_VALUE_ITEMS || state.remainingNodes <= 0) {
1655
+ logger?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");
1656
+ break;
1657
+ }
1658
+ try {
1659
+ const value = attrs[key];
1660
+ if (isNull(value) || isUndefined(value))
1661
+ continue;
1662
+ result.push({
1663
+ key: sanitizeString(key),
1664
+ value: encodeAnyValue(value, logger, state, depth)
1665
+ });
1666
+ } catch {
1667
+ result.push({
1668
+ key: sanitizeString(key),
1669
+ value: {
1670
+ stringValue: UNSERIALIZABLE_VALUE
1671
+ }
1672
+ });
1673
+ }
1674
+ }
1675
+ return result;
1676
+ }
1677
+
1678
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/metrics/metrics-utils.mjs
1679
+ var DEFAULT_HISTOGRAM_BOUNDS = [
1680
+ 0,
1681
+ 5,
1682
+ 10,
1683
+ 25,
1684
+ 50,
1685
+ 75,
1686
+ 100,
1687
+ 250,
1688
+ 500,
1689
+ 750,
1690
+ 1000,
1691
+ 2500,
1692
+ 5000,
1693
+ 7500,
1694
+ 1e4
1695
+ ];
1696
+ function msToUnixNano(ms) {
1697
+ return String(ms) + "000000";
1698
+ }
1699
+ function seriesKey(type, name, unit, attributes) {
1700
+ let attrsKey = "";
1701
+ if (attributes) {
1702
+ const keys = Object.keys(attributes).sort();
1703
+ attrsKey = keys.map((k) => `${JSON.stringify(k)}:${JSON.stringify(attributes[k])}`).join(",");
1704
+ }
1705
+ return `${type}\x00${name}\x00${unit ?? ""}\x00${attrsKey}`;
1706
+ }
1707
+ function bucketIndexFor(value, bounds) {
1708
+ for (let i = 0;i < bounds.length; i++)
1709
+ if (value <= bounds[i])
1710
+ return i;
1711
+ return bounds.length;
1712
+ }
1713
+ function buildMetricsResourceAttributes(config, scopeName, scopeVersion) {
1714
+ return {
1715
+ ...config.resourceAttributes,
1716
+ "service.name": config.serviceName || "unknown_service",
1717
+ ...config.environment && {
1718
+ "deployment.environment": config.environment
1719
+ },
1720
+ ...config.serviceVersion && {
1721
+ "service.version": config.serviceVersion
1722
+ },
1723
+ "telemetry.sdk.name": scopeName,
1724
+ "telemetry.sdk.version": scopeVersion
1725
+ };
1726
+ }
1727
+ function buildOtlpMetricsPayload(metrics, resourceAttributes, scopeName, scopeVersion) {
1728
+ return {
1729
+ resourceMetrics: [
1730
+ {
1731
+ resource: {
1732
+ attributes: toOtlpKeyValueList(resourceAttributes)
1733
+ },
1734
+ scopeMetrics: [
1735
+ {
1736
+ scope: {
1737
+ name: scopeName,
1738
+ version: scopeVersion
1739
+ },
1740
+ metrics
1741
+ }
1742
+ ]
1743
+ }
1744
+ ]
1745
+ };
1746
+ }
1747
+
1748
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/metrics/config.mjs
1749
+ var DEFAULT_FLUSH_INTERVAL_MS = 1e4;
1750
+ var DEFAULT_MAX_SERIES_PER_FLUSH = 1000;
1751
+ function resolveMetricsConfig(config) {
1752
+ const resourceAttributes = config?.resourceAttributes;
1753
+ return {
1754
+ serviceName: resourceAttributes?.["service.name"] ?? config?.serviceName,
1755
+ serviceVersion: resourceAttributes?.["service.version"] ?? config?.serviceVersion,
1756
+ environment: resourceAttributes?.["deployment.environment"] ?? config?.environment,
1757
+ resourceAttributes,
1758
+ beforeSend: config?.beforeSend,
1759
+ flushIntervalMs: config?.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,
1760
+ maxSeriesPerFlush: config?.maxSeriesPerFlush ?? DEFAULT_MAX_SERIES_PER_FLUSH
1761
+ };
1762
+ }
1763
+
1764
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/metrics/index.mjs
1765
+ var OTLP_TEMPORALITY_DELTA = 1;
1766
+
1767
+ class PostHogMetrics {
1768
+ constructor(_instance, _config, _logger) {
1769
+ this._instance = _instance;
1770
+ this._config = _config;
1771
+ this._logger = _logger;
1772
+ this._series = new Map;
1773
+ this._flushPromise = null;
1774
+ this._seriesCapWarned = false;
1775
+ this._typeByName = new Map;
1776
+ this._typeCollisionWarned = new Set;
1777
+ this._generation = 0;
1778
+ }
1779
+ count(name, value = 1, options) {
1780
+ this._capture({
1781
+ name,
1782
+ type: "count",
1783
+ value,
1784
+ unit: options?.unit,
1785
+ attributes: options?.attributes
1786
+ });
1787
+ }
1788
+ gauge(name, value, options) {
1789
+ this._capture({
1790
+ name,
1791
+ type: "gauge",
1792
+ value,
1793
+ unit: options?.unit,
1794
+ attributes: options?.attributes
1795
+ });
1796
+ }
1797
+ histogram(name, value, options) {
1798
+ this._capture({
1799
+ name,
1800
+ type: "histogram",
1801
+ value,
1802
+ unit: options?.unit,
1803
+ attributes: options?.attributes
1804
+ });
1805
+ }
1806
+ flush() {
1807
+ const prev = this._flushPromise;
1808
+ const run = async () => {
1809
+ if (prev)
1810
+ await prev.catch(() => {});
1811
+ await this._doFlush();
1812
+ };
1813
+ const p = run().finally(() => {
1814
+ if (this._flushPromise === p)
1815
+ this._flushPromise = null;
1816
+ });
1817
+ this._flushPromise = p;
1818
+ return p;
1819
+ }
1820
+ drainWindow() {
1821
+ if (this._series.size === 0)
1822
+ return null;
1823
+ const window = this._series;
1824
+ this._series = new Map;
1825
+ this._seriesCapWarned = false;
1826
+ this._typeByName = new Map;
1827
+ this._typeCollisionWarned = new Set;
1828
+ return this._buildPayload(window);
1829
+ }
1830
+ reset() {
1831
+ this._generation++;
1832
+ this._clearFlushTimer();
1833
+ this._series = new Map;
1834
+ this._flushPromise = null;
1835
+ this._seriesCapWarned = false;
1836
+ this._typeByName = new Map;
1837
+ this._typeCollisionWarned = new Set;
1838
+ }
1839
+ _capture(sample) {
1840
+ if (this._instance.isDisabled || this._instance.optedOut)
1841
+ return;
1842
+ const filtered = this._runBeforeSend(sample);
1843
+ if (filtered === null)
1844
+ return;
1845
+ if (!filtered.name || typeof filtered.name != "string")
1846
+ return void this._logger.warn("Dropping metric with empty name");
1847
+ if (typeof filtered.value != "number" || !Number.isFinite(filtered.value))
1848
+ return void this._logger.warn(`Dropping metric '${filtered.name}': value must be a finite number`);
1849
+ if (filtered.type === "count" && filtered.value < 0)
1850
+ return void this._logger.warn(`Dropping count '${filtered.name}': counters are monotonic, value must be >= 0`);
1851
+ let attributes;
1852
+ let key;
1853
+ try {
1854
+ attributes = filtered.attributes ? {
1855
+ ...filtered.attributes
1856
+ } : undefined;
1857
+ key = seriesKey(filtered.type, filtered.name, filtered.unit, attributes);
1858
+ } catch (e) {
1859
+ this._logger.warn(`Dropping metric '${filtered.name}': attributes could not be serialized`, e);
1860
+ return;
1861
+ }
1862
+ let state = this._series.get(key);
1863
+ if (!state) {
1864
+ if (!this._admitNewSeries())
1865
+ return;
1866
+ state = {
1867
+ name: filtered.name,
1868
+ type: filtered.type,
1869
+ unit: filtered.unit,
1870
+ attributes,
1871
+ windowStartMs: Date.now()
1872
+ };
1873
+ this._series.set(key, state);
1874
+ }
1875
+ const seenType = this._typeByName.get(filtered.name);
1876
+ if (seenType === undefined)
1877
+ this._typeByName.set(filtered.name, filtered.type);
1878
+ else if (seenType !== filtered.type && !this._typeCollisionWarned.has(filtered.name)) {
1879
+ this._typeCollisionWarned.add(filtered.name);
1880
+ 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.`);
1881
+ }
1882
+ this._fold(state, filtered.value);
1883
+ this._armFlushTimer();
1884
+ }
1885
+ _admitNewSeries() {
1886
+ if (this._series.size < this._config.maxSeriesPerFlush)
1887
+ return true;
1888
+ if (!this._seriesCapWarned) {
1889
+ this._seriesCapWarned = true;
1890
+ this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`);
1891
+ }
1892
+ return false;
1893
+ }
1894
+ _fold(state, value) {
1895
+ switch (state.type) {
1896
+ case "count":
1897
+ state.total = (state.total ?? 0) + value;
1898
+ break;
1899
+ case "gauge":
1900
+ state.last = value;
1901
+ break;
1902
+ case "histogram": {
1903
+ if (!state.hist)
1904
+ state.hist = {
1905
+ count: 0,
1906
+ sum: 0,
1907
+ min: value,
1908
+ max: value,
1909
+ bucketCounts: new Array(DEFAULT_HISTOGRAM_BOUNDS.length + 1).fill(0)
1910
+ };
1911
+ const hist = state.hist;
1912
+ hist.count += 1;
1913
+ hist.sum += value;
1914
+ hist.min = Math.min(hist.min, value);
1915
+ hist.max = Math.max(hist.max, value);
1916
+ hist.bucketCounts[bucketIndexFor(value, DEFAULT_HISTOGRAM_BOUNDS)] += 1;
1917
+ break;
1918
+ }
1919
+ }
1920
+ }
1921
+ _runBeforeSend(sample) {
1922
+ const beforeSend = this._config.beforeSend;
1923
+ if (!beforeSend)
1924
+ return sample;
1925
+ const fns = isArray(beforeSend) ? beforeSend : [
1926
+ beforeSend
1927
+ ];
1928
+ let result = sample;
1929
+ for (const fn of fns)
1930
+ try {
1931
+ const next = fn(result);
1932
+ if (!next) {
1933
+ this._logger.info("Metric was rejected in beforeSend function");
1934
+ return null;
1935
+ }
1936
+ result = next;
1937
+ } catch (e) {
1938
+ this._logger.error("Error in beforeSend function for metric:", e);
1939
+ return null;
1940
+ }
1941
+ return result;
1942
+ }
1943
+ _armFlushTimer() {
1944
+ if (this._flushTimer)
1945
+ return;
1946
+ this._flushTimer = safeSetTimeout(() => {
1947
+ this._flushTimer = undefined;
1948
+ this.flush().catch((e) => {
1949
+ this._logger.error("Metrics flush failed:", e);
1950
+ });
1951
+ }, this._config.flushIntervalMs);
1952
+ }
1953
+ _clearFlushTimer() {
1954
+ if (this._flushTimer) {
1955
+ clearTimeout(this._flushTimer);
1956
+ this._flushTimer = undefined;
1957
+ }
1958
+ }
1959
+ async _doFlush() {
1960
+ if (this._series.size === 0)
1961
+ return;
1962
+ const window = this._series;
1963
+ this._series = new Map;
1964
+ this._seriesCapWarned = false;
1965
+ this._typeByName = new Map;
1966
+ this._typeCollisionWarned = new Set;
1967
+ const generation = this._generation;
1968
+ const outcome = await this._instance._sendMetricsBatch(this._buildPayload(window));
1969
+ if (generation !== this._generation)
1970
+ return;
1971
+ switch (outcome.kind) {
1972
+ case "ok":
1973
+ return;
1974
+ case "retry-later":
1975
+ this._mergeWindowBack(window);
1976
+ this._armFlushTimer();
1977
+ return;
1978
+ case "too-large":
1979
+ this._logger.warn("Metrics batch exceeded the server size limit and was dropped");
1980
+ return;
1981
+ case "fatal":
1982
+ this._logger.error("Failed to send metrics batch:", outcome.error);
1983
+ return;
1984
+ }
1985
+ }
1986
+ _buildPayload(window) {
1987
+ return buildOtlpMetricsPayload(this._buildMetrics(window), buildMetricsResourceAttributes(this._config, this._instance.getLibraryId(), this._instance.getLibraryVersion()), this._instance.getLibraryId(), this._instance.getLibraryVersion());
1988
+ }
1989
+ _buildMetrics(window) {
1990
+ const nowNano = msToUnixNano(Date.now());
1991
+ const byMetric = new Map;
1992
+ for (const state of window.values()) {
1993
+ const metricKey = seriesKey(state.type, state.name, state.unit, undefined);
1994
+ let metric = byMetric.get(metricKey);
1995
+ if (!metric) {
1996
+ metric = {
1997
+ name: state.name,
1998
+ ...state.unit && {
1999
+ unit: state.unit
2000
+ }
2001
+ };
2002
+ if (state.type === "count")
2003
+ metric.sum = {
2004
+ aggregationTemporality: OTLP_TEMPORALITY_DELTA,
2005
+ isMonotonic: true,
2006
+ dataPoints: []
2007
+ };
2008
+ else if (state.type === "gauge")
2009
+ metric.gauge = {
2010
+ dataPoints: []
2011
+ };
2012
+ else
2013
+ metric.histogram = {
2014
+ aggregationTemporality: OTLP_TEMPORALITY_DELTA,
2015
+ dataPoints: []
2016
+ };
2017
+ byMetric.set(metricKey, metric);
2018
+ }
2019
+ const attributes = toOtlpKeyValueList(state.attributes ?? {}, this._logger);
2020
+ const startNano = msToUnixNano(state.windowStartMs);
2021
+ if (state.type === "count") {
2022
+ const dp = {
2023
+ attributes,
2024
+ startTimeUnixNano: startNano,
2025
+ timeUnixNano: nowNano,
2026
+ asDouble: state.total ?? 0
2027
+ };
2028
+ metric.sum.dataPoints.push(dp);
2029
+ } else if (state.type === "gauge") {
2030
+ const dp = {
2031
+ attributes,
2032
+ timeUnixNano: nowNano,
2033
+ asDouble: state.last ?? 0
2034
+ };
2035
+ metric.gauge.dataPoints.push(dp);
2036
+ } else if (state.hist) {
2037
+ const dp = {
2038
+ attributes,
2039
+ startTimeUnixNano: startNano,
2040
+ timeUnixNano: nowNano,
2041
+ count: state.hist.count,
2042
+ sum: state.hist.sum,
2043
+ min: state.hist.min,
2044
+ max: state.hist.max,
2045
+ bucketCounts: state.hist.bucketCounts,
2046
+ explicitBounds: DEFAULT_HISTOGRAM_BOUNDS
2047
+ };
2048
+ metric.histogram.dataPoints.push(dp);
2049
+ }
2050
+ }
2051
+ return Array.from(byMetric.values());
2052
+ }
2053
+ _mergeWindowBack(window) {
2054
+ for (const [key, old] of window) {
2055
+ const current = this._series.get(key);
2056
+ if (!current) {
2057
+ if (this._admitNewSeries())
2058
+ this._series.set(key, old);
2059
+ continue;
2060
+ }
2061
+ current.windowStartMs = Math.min(current.windowStartMs, old.windowStartMs);
2062
+ switch (current.type) {
2063
+ case "count":
2064
+ current.total = (current.total ?? 0) + (old.total ?? 0);
2065
+ break;
2066
+ case "gauge":
2067
+ break;
2068
+ case "histogram":
2069
+ if (old.hist)
2070
+ if (current.hist) {
2071
+ current.hist.count += old.hist.count;
2072
+ current.hist.sum += old.hist.sum;
2073
+ current.hist.min = Math.min(current.hist.min, old.hist.min);
2074
+ current.hist.max = Math.max(current.hist.max, old.hist.max);
2075
+ for (let i = 0;i < current.hist.bucketCounts.length; i++)
2076
+ current.hist.bucketCounts[i] += old.hist.bucketCounts[i];
2077
+ } else
2078
+ current.hist = old.hist;
2079
+ break;
2080
+ }
2081
+ }
2082
+ }
2083
+ }
2084
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/eventemitter.mjs
1344
2085
  class SimpleEventEmitter {
1345
2086
  constructor() {
1346
2087
  this.events = {};
@@ -1362,37 +2103,7 @@ class SimpleEventEmitter {
1362
2103
  }
1363
2104
  }
1364
2105
 
1365
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/index.mjs
1366
- var exports_error_tracking = {};
1367
- __export(exports_error_tracking, {
1368
- winjsStackLineParser: () => winjsStackLineParser,
1369
- stripReservedExceptionStepFields: () => stripReservedExceptionStepFields,
1370
- reverseAndStripFrames: () => reverseAndStripFrames,
1371
- resolveExceptionStepsConfig: () => resolveExceptionStepsConfig,
1372
- opera11StackLineParser: () => opera11StackLineParser,
1373
- opera10StackLineParser: () => opera10StackLineParser,
1374
- nodeStackLineParser: () => nodeStackLineParser,
1375
- getUtf8ByteLength: () => getUtf8ByteLength,
1376
- geckoStackLineParser: () => geckoStackLineParser,
1377
- createStackParser: () => createStackParser,
1378
- createDefaultStackParser: () => createDefaultStackParser,
1379
- chromeStackLineParser: () => chromeStackLineParser,
1380
- StringCoercer: () => StringCoercer,
1381
- ReduceableCache: () => ReduceableCache,
1382
- PromiseRejectionEventCoercer: () => PromiseRejectionEventCoercer,
1383
- PrimitiveCoercer: () => PrimitiveCoercer,
1384
- ObjectCoercer: () => ObjectCoercer,
1385
- ExceptionStepsBuffer: () => ExceptionStepsBuffer,
1386
- EventCoercer: () => EventCoercer,
1387
- ErrorPropertiesBuilder: () => ErrorPropertiesBuilder,
1388
- ErrorEventCoercer: () => ErrorEventCoercer,
1389
- ErrorCoercer: () => ErrorCoercer,
1390
- EXCEPTION_STEP_INTERNAL_FIELDS: () => EXCEPTION_STEP_INTERNAL_FIELDS,
1391
- DOMExceptionCoercer: () => DOMExceptionCoercer,
1392
- DEFAULT_EXCEPTION_STEPS_CONFIG: () => DEFAULT_EXCEPTION_STEPS_CONFIG
1393
- });
1394
-
1395
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/chunk-ids.mjs
2106
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/chunk-ids.mjs
1396
2107
  var parsedStackResults;
1397
2108
  var lastKeysCount;
1398
2109
  var cachedFilenameChunkIds;
@@ -1431,7 +2142,7 @@ function getFilenameToChunkIdMap(stackParser) {
1431
2142
  return cachedFilenameChunkIds;
1432
2143
  }
1433
2144
 
1434
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/error-properties-builder.mjs
2145
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/error-properties-builder.mjs
1435
2146
  var MAX_CAUSE_RECURSION = 4;
1436
2147
 
1437
2148
  class ErrorPropertiesBuilder {
@@ -1535,11 +2246,11 @@ class ErrorPropertiesBuilder {
1535
2246
  return context;
1536
2247
  }
1537
2248
  buildCoercingContext(mechanism, hint, depth = 0) {
1538
- const coerce = (input, depth2) => {
1539
- if (!(depth2 <= MAX_CAUSE_RECURSION))
2249
+ const coerce = (input, depth) => {
2250
+ if (!(depth <= MAX_CAUSE_RECURSION))
1540
2251
  return;
1541
2252
  {
1542
- const ctx = this.buildCoercingContext(mechanism, hint, depth2);
2253
+ const ctx = this.buildCoercingContext(mechanism, hint, depth);
1543
2254
  return this.applyCoercers(input, ctx);
1544
2255
  }
1545
2256
  };
@@ -1553,14 +2264,16 @@ class ErrorPropertiesBuilder {
1553
2264
  return context;
1554
2265
  }
1555
2266
  }
1556
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/base.mjs
2267
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/base.mjs
1557
2268
  var UNKNOWN_FUNCTION = "?";
2269
+ var MASKED_URL_PREFIX = "webkit-masked-url://";
2270
+ var ANONYMOUS_FILENAME = "<anonymous>";
1558
2271
  function createFrame(platform, filename, func, lineno, colno) {
1559
2272
  const frame = {
1560
2273
  platform,
1561
2274
  filename,
1562
2275
  function: func === "<anonymous>" ? UNKNOWN_FUNCTION : func,
1563
- in_app: true
2276
+ in_app: !filename?.startsWith(MASKED_URL_PREFIX) && filename !== ANONYMOUS_FILENAME
1564
2277
  };
1565
2278
  if (!isUndefined(lineno))
1566
2279
  frame.lineno = lineno;
@@ -1569,7 +2282,7 @@ function createFrame(platform, filename, func, lineno, colno) {
1569
2282
  return frame;
1570
2283
  }
1571
2284
 
1572
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/safari.mjs
2285
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/safari.mjs
1573
2286
  var extractSafariExtensionDetails = (func, filename) => {
1574
2287
  const isSafariExtension = func.indexOf("safari-extension") !== -1;
1575
2288
  const isSafariWebExtension = func.indexOf("safari-web-extension") !== -1;
@@ -1582,15 +2295,15 @@ var extractSafariExtensionDetails = (func, filename) => {
1582
2295
  ];
1583
2296
  };
1584
2297
 
1585
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/chrome.mjs
2298
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/chrome.mjs
1586
2299
  var chromeRegexNoFnName = /^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i;
1587
2300
  var chromeRegex = /^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
1588
2301
  var chromeEvalRegex = /\((\S*)(?::(\d+))(?::(\d+))\)/;
1589
2302
  var chromeStackLineParser = (line, platform) => {
1590
2303
  const noFnParts = chromeRegexNoFnName.exec(line);
1591
2304
  if (noFnParts) {
1592
- const [, filename, line2, col] = noFnParts;
1593
- return createFrame(platform, filename, UNKNOWN_FUNCTION, +line2, +col);
2305
+ const [, filename, line, col] = noFnParts;
2306
+ return createFrame(platform, filename, UNKNOWN_FUNCTION, +line, +col);
1594
2307
  }
1595
2308
  const parts = chromeRegex.exec(line);
1596
2309
  if (parts) {
@@ -1608,7 +2321,7 @@ var chromeStackLineParser = (line, platform) => {
1608
2321
  }
1609
2322
  };
1610
2323
 
1611
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/gecko.mjs
2324
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/gecko.mjs
1612
2325
  var geckoREgex = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i;
1613
2326
  var geckoEvalRegex = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
1614
2327
  var geckoStackLineParser = (line, platform) => {
@@ -1631,28 +2344,12 @@ var geckoStackLineParser = (line, platform) => {
1631
2344
  }
1632
2345
  };
1633
2346
 
1634
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/winjs.mjs
1635
- var winjsRegex = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
1636
- var winjsStackLineParser = (line, platform) => {
1637
- const parts = winjsRegex.exec(line);
1638
- return parts ? createFrame(platform, parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : undefined) : undefined;
1639
- };
1640
-
1641
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/opera.mjs
1642
- var opera10Regex = / line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i;
1643
- var opera10StackLineParser = (line, platform) => {
1644
- const parts = opera10Regex.exec(line);
1645
- return parts ? createFrame(platform, parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : undefined;
1646
- };
1647
- var opera11Regex = / line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i;
1648
- var opera11StackLineParser = (line, platform) => {
1649
- const parts = opera11Regex.exec(line);
1650
- return parts ? createFrame(platform, parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : undefined;
1651
- };
1652
-
1653
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/node.mjs
2347
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/node.mjs
1654
2348
  var FILENAME_MATCH = /^\s*[-]{4,}$/;
1655
2349
  var FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;
2350
+ var PROMISE_COMBINATOR = /^Promise\.(?:all|any)$/;
2351
+ var PROMISE_INDEX = /^index \d+$/;
2352
+ var PROMISE_FRAME_FILENAME = "node:internal/promise";
1656
2353
  var nodeStackLineParser = (line, platform) => {
1657
2354
  const lineMatch = line.match(FULL_MATCH);
1658
2355
  if (lineMatch) {
@@ -1695,6 +2392,8 @@ var nodeStackLineParser = (line, platform) => {
1695
2392
  filename = filename.slice(1);
1696
2393
  if (!filename && lineMatch[5] && !isNative)
1697
2394
  filename = lineMatch[5];
2395
+ if (PROMISE_COMBINATOR.test(functionName) && PROMISE_INDEX.test(filename || ""))
2396
+ filename = PROMISE_FRAME_FILENAME;
1698
2397
  return {
1699
2398
  filename: filename ? decodeURI(filename) : undefined,
1700
2399
  module: undefined,
@@ -1719,7 +2418,7 @@ function _parseIntOrUndefined(input) {
1719
2418
  return parseInt(input || "", 10) || undefined;
1720
2419
  }
1721
2420
 
1722
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/index.mjs
2421
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/index.mjs
1723
2422
  var WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
1724
2423
  var STACKTRACE_FRAME_LIMIT = 50;
1725
2424
  function reverseAndStripFrames(stack) {
@@ -1764,52 +2463,24 @@ function createStackParser(platform, ...parsers) {
1764
2463
  return reverseAndStripFrames(frames);
1765
2464
  };
1766
2465
  }
1767
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/dom-exception-coercer.mjs
1768
- class DOMExceptionCoercer {
2466
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/error-coercer.mjs
2467
+ class ErrorCoercer {
1769
2468
  match(err) {
1770
- return this.isDOMException(err) || this.isDOMError(err);
2469
+ return isError(err);
1771
2470
  }
1772
2471
  coerce(err, ctx) {
1773
- const hasStack = isString(err.stack);
2472
+ const stack = this.getStack(err);
2473
+ const synthetic = stack === undefined;
1774
2474
  return {
1775
2475
  type: this.getType(err),
1776
- value: this.getValue(err),
1777
- stack: hasStack ? err.stack : undefined,
2476
+ value: this.getMessage(err, ctx),
2477
+ stack: stack ?? ctx.syntheticException?.stack,
1778
2478
  cause: err.cause ? ctx.next(err.cause) : undefined,
1779
- synthetic: false
2479
+ synthetic
1780
2480
  };
1781
2481
  }
1782
- getType(candidate) {
1783
- return this.isDOMError(candidate) ? "DOMError" : "DOMException";
1784
- }
1785
- getValue(err) {
1786
- const name = err.name || (this.isDOMError(err) ? "DOMError" : "DOMException");
1787
- const message = err.message ? `${name}: ${err.message}` : name;
1788
- return message;
1789
- }
1790
- isDOMException(err) {
1791
- return isBuiltin(err, "DOMException");
1792
- }
1793
- isDOMError(err) {
1794
- return isBuiltin(err, "DOMError");
1795
- }
1796
- }
1797
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/error-coercer.mjs
1798
- class ErrorCoercer {
1799
- match(err) {
1800
- return isPlainError(err);
1801
- }
1802
- coerce(err, ctx) {
1803
- return {
1804
- type: this.getType(err),
1805
- value: this.getMessage(err, ctx),
1806
- stack: this.getStack(err),
1807
- cause: err.cause ? ctx.next(err.cause) : undefined,
1808
- synthetic: false
1809
- };
1810
- }
1811
- getType(err) {
1812
- return err.name || err.constructor.name;
2482
+ getType(err) {
2483
+ return err.name || err.constructor.name;
1813
2484
  }
1814
2485
  getMessage(err, _ctx) {
1815
2486
  const message = err.message;
@@ -1821,25 +2492,7 @@ class ErrorCoercer {
1821
2492
  return err.stacktrace || err.stack || undefined;
1822
2493
  }
1823
2494
  }
1824
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/error-event-coercer.mjs
1825
- class ErrorEventCoercer {
1826
- constructor() {}
1827
- match(err) {
1828
- return isErrorEvent(err) && err.error != null;
1829
- }
1830
- coerce(err, ctx) {
1831
- const exceptionLike = ctx.apply(err.error);
1832
- if (!exceptionLike)
1833
- return {
1834
- type: "ErrorEvent",
1835
- value: err.message,
1836
- stack: ctx.syntheticException?.stack,
1837
- synthetic: true
1838
- };
1839
- return exceptionLike;
1840
- }
1841
- }
1842
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/string-coercer.mjs
2495
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/string-coercer.mjs
1843
2496
  var ERROR_TYPES_PATTERN = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;
1844
2497
 
1845
2498
  class StringCoercer {
@@ -1869,7 +2522,7 @@ class StringCoercer {
1869
2522
  ];
1870
2523
  }
1871
2524
  }
1872
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/types.mjs
2525
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/types.mjs
1873
2526
  var severityLevels = [
1874
2527
  "fatal",
1875
2528
  "error",
@@ -1879,7 +2532,7 @@ var severityLevels = [
1879
2532
  "debug"
1880
2533
  ];
1881
2534
 
1882
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/utils.mjs
2535
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/utils.mjs
1883
2536
  function extractExceptionKeysForMessage(err, maxLength = 40) {
1884
2537
  const keys = Object.keys(err);
1885
2538
  keys.sort();
@@ -1896,7 +2549,7 @@ function extractExceptionKeysForMessage(err, maxLength = 40) {
1896
2549
  return "";
1897
2550
  }
1898
2551
 
1899
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.mjs
2552
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.mjs
1900
2553
  class ObjectCoercer {
1901
2554
  match(candidate) {
1902
2555
  return typeof candidate == "object" && candidate !== null;
@@ -1908,13 +2561,16 @@ class ObjectCoercer {
1908
2561
  return {
1909
2562
  type: this.getType(candidate),
1910
2563
  value: this.getValue(candidate),
1911
- stack: ctx.syntheticException?.stack,
2564
+ stack: this.getStack(candidate) ?? ctx.syntheticException?.stack,
1912
2565
  level: this.isSeverityLevel(candidate.level) ? candidate.level : "error",
1913
2566
  synthetic: true
1914
2567
  };
1915
2568
  }
1916
2569
  getType(err) {
1917
- return isEvent(err) ? err.constructor.name : "Error";
2570
+ if (isEvent(err))
2571
+ return err.constructor.name;
2572
+ const name = "name" in err ? err.name : undefined;
2573
+ return isString(name) && !isEmptyString(name) ? name : "Error";
1918
2574
  }
1919
2575
  getValue(err) {
1920
2576
  if ("name" in err && typeof err.name == "string") {
@@ -1932,6 +2588,15 @@ class ObjectCoercer {
1932
2588
  isSeverityLevel(x) {
1933
2589
  return isString(x) && !isEmptyString(x) && severityLevels.indexOf(x) >= 0;
1934
2590
  }
2591
+ getStack(candidate) {
2592
+ try {
2593
+ if (isString(candidate.stacktrace) && candidate.stacktrace.length > 0)
2594
+ return candidate.stacktrace;
2595
+ return isString(candidate.stack) && candidate.stack.length > 0 ? candidate.stack : undefined;
2596
+ } catch {
2597
+ return;
2598
+ }
2599
+ }
1935
2600
  getErrorPropertyFromObject(obj) {
1936
2601
  for (const prop in obj)
1937
2602
  if (Object.prototype.hasOwnProperty.call(obj, prop)) {
@@ -1949,7 +2614,7 @@ class ObjectCoercer {
1949
2614
  }
1950
2615
  }
1951
2616
  }
1952
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/event-coercer.mjs
2617
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/event-coercer.mjs
1953
2618
  class EventCoercer {
1954
2619
  match(err) {
1955
2620
  return isEvent(err);
@@ -1964,7 +2629,7 @@ class EventCoercer {
1964
2629
  };
1965
2630
  }
1966
2631
  }
1967
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/primitive-coercer.mjs
2632
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/primitive-coercer.mjs
1968
2633
  class PrimitiveCoercer {
1969
2634
  match(candidate) {
1970
2635
  return isPrimitive(candidate);
@@ -1978,43 +2643,7 @@ class PrimitiveCoercer {
1978
2643
  };
1979
2644
  }
1980
2645
  }
1981
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/promise-rejection-event.mjs
1982
- class PromiseRejectionEventCoercer {
1983
- match(err) {
1984
- return isBuiltin(err, "PromiseRejectionEvent") || this.isCustomEventWrappingRejection(err);
1985
- }
1986
- isCustomEventWrappingRejection(err) {
1987
- if (!isEvent(err))
1988
- return false;
1989
- try {
1990
- const detail = err.detail;
1991
- return detail != null && typeof detail == "object" && "reason" in detail;
1992
- } catch {
1993
- return false;
1994
- }
1995
- }
1996
- coerce(err, ctx) {
1997
- const reason = this.getUnhandledRejectionReason(err);
1998
- if (isPrimitive(reason))
1999
- return {
2000
- type: "UnhandledRejection",
2001
- value: `Non-Error promise rejection captured with value: ${String(reason)}`,
2002
- stack: ctx.syntheticException?.stack,
2003
- synthetic: true
2004
- };
2005
- return ctx.apply(reason);
2006
- }
2007
- getUnhandledRejectionReason(error) {
2008
- try {
2009
- if ("reason" in error)
2010
- return error.reason;
2011
- if ("detail" in error && error.detail != null && typeof error.detail == "object" && "reason" in error.detail)
2012
- return error.detail.reason;
2013
- } catch {}
2014
- return error;
2015
- }
2016
- }
2017
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/utils.mjs
2646
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/utils.mjs
2018
2647
  class ReduceableCache {
2019
2648
  constructor(_maxSize) {
2020
2649
  this._maxSize = _maxSize;
@@ -2039,7 +2668,7 @@ class ReduceableCache {
2039
2668
  }
2040
2669
  }
2041
2670
  }
2042
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/exception-steps.mjs
2671
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/exception-steps.mjs
2043
2672
  var EXCEPTION_STEP_INTERNAL_FIELDS = {
2044
2673
  MESSAGE: "$message",
2045
2674
  TIMESTAMP: "$timestamp"
@@ -2048,167 +2677,65 @@ var RESERVED_EXCEPTION_STEP_KEYS = new Set([
2048
2677
  EXCEPTION_STEP_INTERNAL_FIELDS.MESSAGE,
2049
2678
  EXCEPTION_STEP_INTERNAL_FIELDS.TIMESTAMP
2050
2679
  ]);
2051
- var DEFAULT_EXCEPTION_STEPS_CONFIG = {
2052
- enabled: true,
2053
- max_bytes: 32768
2054
- };
2055
- function resolveExceptionStepsConfig(config) {
2056
- if (!config)
2057
- return {
2058
- ...DEFAULT_EXCEPTION_STEPS_CONFIG
2059
- };
2060
- return {
2061
- enabled: config.enabled ?? DEFAULT_EXCEPTION_STEPS_CONFIG.enabled,
2062
- max_bytes: normalizePositiveInteger(config.max_bytes, DEFAULT_EXCEPTION_STEPS_CONFIG.max_bytes)
2063
- };
2064
- }
2065
- function stripReservedExceptionStepFields(properties) {
2066
- if (!properties)
2067
- return {
2068
- sanitizedProperties: {},
2069
- droppedKeys: []
2070
- };
2071
- const droppedKeys = [];
2072
- const sanitizedProperties = Object.keys(properties).reduce((acc, key) => {
2073
- if (RESERVED_EXCEPTION_STEP_KEYS.has(key)) {
2074
- droppedKeys.push(key);
2075
- return acc;
2076
- }
2077
- acc[key] = properties[key];
2078
- return acc;
2079
- }, {});
2080
- return {
2081
- sanitizedProperties,
2082
- droppedKeys
2083
- };
2084
- }
2085
-
2086
- class ExceptionStepsBuffer {
2087
- constructor(config) {
2088
- this._entries = [];
2089
- this._totalBytes = 0;
2090
- this._config = resolveExceptionStepsConfig(config);
2091
- }
2092
- setConfig(config) {
2093
- this._config = resolveExceptionStepsConfig(config);
2094
- this._trimToMaxBytes();
2095
- }
2096
- add(step) {
2097
- const serialized = normalizeAndSerializeStep(step);
2098
- if (!serialized)
2099
- return;
2100
- const bytes = getUtf8ByteLength(serialized.json);
2101
- if (bytes > this._config.max_bytes)
2102
- return;
2103
- this._entries.push({
2104
- step: serialized.step,
2105
- bytes
2106
- });
2107
- this._totalBytes += bytes;
2108
- this._trimToMaxBytes();
2109
- }
2110
- getAttachable() {
2111
- return this._entries.map((e) => e.step);
2112
- }
2113
- clear() {
2114
- this._entries = [];
2115
- this._totalBytes = 0;
2116
- }
2117
- size() {
2118
- return this._entries.length;
2119
- }
2120
- _trimToMaxBytes() {
2121
- while (this._totalBytes > this._config.max_bytes && this._entries.length > 0) {
2122
- const evicted = this._entries.shift();
2123
- if (evicted)
2124
- this._totalBytes -= evicted.bytes;
2125
- }
2126
- }
2127
- }
2128
- function normalizePositiveInteger(input, fallback) {
2129
- if (!isNumber(input) || input === 1 / 0 || input === -1 / 0)
2130
- return fallback;
2131
- const normalized = Math.floor(input);
2132
- if (normalized < 0)
2133
- return fallback;
2134
- return normalized;
2680
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/release.mjs
2681
+ function getInjectedReleaseId() {
2682
+ const injected = globalThis._posthogReleaseId;
2683
+ return typeof injected == "string" && injected.length > 0 ? injected : undefined;
2135
2684
  }
2136
- function normalizeAndSerializeStep(step) {
2137
- const json = safeStringify(step);
2138
- if (!json)
2139
- return;
2140
- try {
2141
- const parsed = JSON.parse(json);
2142
- if (!isObject(parsed))
2143
- return;
2144
- const parsedStep = parsed;
2145
- const message = parsedStep[EXCEPTION_STEP_INTERNAL_FIELDS.MESSAGE];
2146
- const timestamp = parsedStep[EXCEPTION_STEP_INTERNAL_FIELDS.TIMESTAMP];
2147
- if (!isString(message) || message.trim().length === 0)
2148
- return;
2149
- if (!isString(timestamp) && !isNumber(timestamp))
2150
- return;
2151
- return {
2152
- step: parsedStep,
2153
- json
2154
- };
2155
- } catch {
2156
- return;
2157
- }
2158
- }
2159
- function safeStringify(value) {
2160
- const seen = new WeakSet;
2161
- try {
2162
- return JSON.stringify(value, (_key, replacementValue) => {
2163
- if (typeof replacementValue == "bigint")
2164
- return replacementValue.toString();
2165
- if (typeof replacementValue == "function" || typeof replacementValue == "symbol")
2166
- return;
2167
- if (replacementValue instanceof Date)
2168
- return replacementValue.toISOString();
2169
- if (replacementValue instanceof Error)
2170
- return {
2171
- name: replacementValue.name,
2172
- message: replacementValue.message,
2173
- stack: replacementValue.stack
2174
- };
2175
- if (replacementValue && typeof replacementValue == "object") {
2176
- if (seen.has(replacementValue))
2177
- return "[Circular]";
2178
- seen.add(replacementValue);
2179
- }
2180
- return replacementValue;
2181
- });
2182
- } catch {
2183
- return;
2184
- }
2185
- }
2186
- function getUtf8ByteLength(value) {
2187
- if (typeof TextEncoder != "undefined")
2188
- return new TextEncoder().encode(value).length;
2189
- const encoded = encodeURIComponent(value);
2190
- let byteLength = 0;
2191
- for (let i = 0;i < encoded.length; i++)
2192
- if (encoded[i] === "%") {
2193
- byteLength += 1;
2194
- i += 2;
2195
- } else
2196
- byteLength += 1;
2197
- return byteLength;
2198
- }
2199
- // ../../../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/posthog-core-stateless.mjs
2685
+ // ../../../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/posthog-core-stateless.mjs
2200
2686
  class PostHogFetchHttpError extends Error {
2201
- constructor(response, reqByteLength) {
2202
- super("HTTP error while fetching PostHog: status=" + response.status + ", reqByteLength=" + reqByteLength), this.response = response, this.reqByteLength = reqByteLength, this.name = "PostHogFetchHttpError";
2687
+ constructor(response, reqByteLength, responseBodyDeadline, abortController) {
2688
+ super("HTTP error while fetching PostHog: status=" + response.status + ", reqByteLength=" + reqByteLength), this.response = response, this.reqByteLength = reqByteLength, this.responseBodyDeadline = responseBodyDeadline, this.abortController = abortController, this.name = "PostHogFetchHttpError", this._bodyReadTimedOut = false;
2203
2689
  }
2204
2690
  get status() {
2205
2691
  return this.response.status;
2206
2692
  }
2693
+ get bodyReadTimedOut() {
2694
+ return this._bodyReadTimedOut;
2695
+ }
2207
2696
  get text() {
2208
- return this.response.text();
2697
+ if (!this.responseBodyTextPromise)
2698
+ if (Date.now() >= this.responseBodyDeadline) {
2699
+ this._bodyReadTimedOut = true;
2700
+ const timeoutError = new Error("Response body read timed out");
2701
+ timeoutError.name = "AbortError";
2702
+ this.cancelResponseBody(timeoutError);
2703
+ this.responseBodyTextPromise = Promise.reject(timeoutError);
2704
+ } else {
2705
+ const responseBodyTimeout = new Promise((_resolve, reject) => {
2706
+ this.responseBodyTimer = safeSetTimeout(() => {
2707
+ this._bodyReadTimedOut = true;
2708
+ const timeoutError = new Error("Response body read timed out");
2709
+ timeoutError.name = "AbortError";
2710
+ reject(timeoutError);
2711
+ this.cancelResponseBody(timeoutError);
2712
+ }, this.responseBodyDeadline - Date.now());
2713
+ });
2714
+ let responseBodyText;
2715
+ try {
2716
+ responseBodyText = Promise.resolve(this.response.text());
2717
+ } catch (error) {
2718
+ responseBodyText = Promise.reject(error);
2719
+ }
2720
+ this.responseBodyTextPromise = Promise.race([
2721
+ responseBodyText,
2722
+ responseBodyTimeout
2723
+ ]).finally(() => clearTimeout(this.responseBodyTimer));
2724
+ }
2725
+ return this.responseBodyTextPromise;
2209
2726
  }
2210
2727
  get json() {
2211
- return this.response.json();
2728
+ return this.text.then((text) => JSON.parse(text));
2729
+ }
2730
+ cancelResponseBody(reason) {
2731
+ clearTimeout(this.responseBodyTimer);
2732
+ if (!this.abortController.signal.aborted)
2733
+ this.abortController.abort(reason);
2734
+ (async () => {
2735
+ try {
2736
+ await this.response.body?.cancel();
2737
+ } catch {}
2738
+ })();
2212
2739
  }
2213
2740
  }
2214
2741
 
@@ -2219,12 +2746,20 @@ class PostHogFetchNetworkError extends Error {
2219
2746
  } : {}), this.error = error, this.name = "PostHogFetchNetworkError";
2220
2747
  }
2221
2748
  }
2749
+ var applyCallerFeatureFlagOverrides = (target, callerProperties) => {
2750
+ for (const key of Object.keys(callerProperties))
2751
+ if (key.startsWith("$feature/") || key === "$active_feature_flags")
2752
+ target[key] = callerProperties[key];
2753
+ };
2222
2754
  async function logFlushError(err) {
2223
2755
  if (err instanceof PostHogFetchHttpError) {
2224
2756
  let text = "";
2225
2757
  try {
2226
2758
  text = await err.text;
2227
- } catch {}
2759
+ } catch {
2760
+ if (err.bodyReadTimedOut)
2761
+ text = "<response body read timed out>";
2762
+ }
2228
2763
  console.error(`Error while flushing PostHog: message=${err.message}, response body=${text}`, err);
2229
2764
  } else
2230
2765
  console.error("Error while flushing PostHog", err);
@@ -2236,9 +2771,28 @@ function isPostHogFetchError(err) {
2236
2771
  function isPostHogFetchNetworkError(err) {
2237
2772
  return err instanceof PostHogFetchNetworkError;
2238
2773
  }
2774
+ function isRetryableFlagsFetchError(err) {
2775
+ if (err instanceof PostHogFetchHttpError)
2776
+ return err.status === 502 || err.status === 504;
2777
+ if (!(err instanceof PostHogFetchNetworkError))
2778
+ return false;
2779
+ const cause = err.error;
2780
+ const code = cause?.code ?? cause?.cause?.code;
2781
+ return code !== "ECONNREFUSED";
2782
+ }
2239
2783
  function isPostHogFetchContentTooLargeError(err) {
2240
2784
  return typeof err == "object" && err instanceof PostHogFetchHttpError && err.status === 413;
2241
2785
  }
2786
+ function isPostHogFetchRetryableError(err) {
2787
+ if (err instanceof PostHogFetchHttpError)
2788
+ return err.status === 408 || err.status === 429 || err.status >= 500;
2789
+ return isPostHogFetchNetworkError(err);
2790
+ }
2791
+ function isPostHogEventProperties(value) {
2792
+ return value !== null && typeof value == "object" && !Array.isArray(value);
2793
+ }
2794
+ var DEFAULT_QUEUE_ROUTE = "default";
2795
+
2242
2796
  class PostHogCoreStateless {
2243
2797
  getErrorPropertiesBuilder() {
2244
2798
  if (!this._errorPropertiesBuilder)
@@ -2255,6 +2809,9 @@ class PostHogCoreStateless {
2255
2809
  }
2256
2810
  constructor(apiKey, options = {}) {
2257
2811
  this.flushPromise = null;
2812
+ this.pendingFlushPromise = null;
2813
+ this.flushPromises = new Set;
2814
+ this._dequeuedMessagesCount = 0;
2258
2815
  this.shutdownPromise = null;
2259
2816
  this.promiseQueue = new PromiseQueue;
2260
2817
  this._events = new SimpleEventEmitter;
@@ -2277,10 +2834,11 @@ class PostHogCoreStateless {
2277
2834
  this._retryOptions = {
2278
2835
  retryCount: options.fetchRetryCount ?? 3,
2279
2836
  retryDelay: options.fetchRetryDelay ?? 3000,
2280
- retryCheck: isPostHogFetchError
2837
+ retryCheck: isPostHogFetchRetryableError
2281
2838
  };
2282
2839
  this.requestTimeout = options.requestTimeout ?? 1e4;
2283
2840
  this.featureFlagsRequestTimeoutMs = options.featureFlagsRequestTimeoutMs ?? 3000;
2841
+ this.featureFlagsRequestMaxRetries = options.featureFlagsRequestMaxRetries ?? 1;
2284
2842
  this.remoteConfigRequestTimeoutMs = options.remoteConfigRequestTimeoutMs ?? 3000;
2285
2843
  this.disableGeoip = options.disableGeoip ?? true;
2286
2844
  this.disabled = (options.disabled ?? false) || missingApiKey;
@@ -2342,15 +2900,23 @@ class PostHogCoreStateless {
2342
2900
  return this.disabled;
2343
2901
  }
2344
2902
  buildPayload(payload) {
2903
+ const userProperties = payload.properties || {};
2904
+ let properties = {
2905
+ ...userProperties,
2906
+ ...this.getCommonEventProperties()
2907
+ };
2908
+ applyCallerFeatureFlagOverrides(properties, userProperties);
2909
+ if (payload.event === "$feature_flag_called" && properties.$feature_flag_has_experiment === false && this.isMinimalFlagCalledEventsEnabled())
2910
+ properties = minimizeFlagCalledEventProperties(properties);
2345
2911
  return {
2346
2912
  distinct_id: payload.distinct_id,
2347
2913
  event: payload.event,
2348
- properties: {
2349
- ...payload.properties || {},
2350
- ...this.getCommonEventProperties()
2351
- }
2914
+ properties
2352
2915
  };
2353
2916
  }
2917
+ isMinimalFlagCalledEventsEnabled() {
2918
+ return false;
2919
+ }
2354
2920
  addPendingPromise(promise) {
2355
2921
  return this.promiseQueue.add(promise);
2356
2922
  }
@@ -2435,6 +3001,19 @@ class PostHogCoreStateless {
2435
3001
  this.enqueue("capture", payload, options);
2436
3002
  });
2437
3003
  }
3004
+ async groupIdentifyStatelessImmediate(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
3005
+ const payload = this.buildPayload({
3006
+ distinct_id: distinctId || `$${groupType}_${groupKey}`,
3007
+ event: "$groupidentify",
3008
+ properties: {
3009
+ $group_type: groupType,
3010
+ $group_key: groupKey,
3011
+ $group_set: groupProperties || {},
3012
+ ...eventProperties || {}
3013
+ }
3014
+ });
3015
+ await this.sendImmediate("capture", payload, options);
3016
+ }
2438
3017
  async getRemoteConfig() {
2439
3018
  await this._initPromise;
2440
3019
  let host = this.host;
@@ -2451,8 +3030,11 @@ class PostHogCoreStateless {
2451
3030
  }
2452
3031
  };
2453
3032
  return this.fetchWithRetry(url, fetchOptions, {
3033
+ type: "required",
3034
+ consume: (response) => response.json()
3035
+ }, {
2454
3036
  retryCount: 0
2455
- }, this.remoteConfigRequestTimeoutMs).then((response) => response.json()).catch((error) => {
3037
+ }, this.remoteConfigRequestTimeoutMs).catch((error) => {
2456
3038
  this._logger.error("Remote config could not be loaded", error);
2457
3039
  this._events.emit("error", error);
2458
3040
  });
@@ -2483,8 +3065,12 @@ class PostHogCoreStateless {
2483
3065
  };
2484
3066
  this._logger.info("Flags URL", url);
2485
3067
  return this.fetchWithRetry(url, fetchOptions, {
2486
- retryCount: 0
2487
- }, this.featureFlagsRequestTimeoutMs).then((response) => response.json()).then((response) => ({
3068
+ type: "required",
3069
+ consume: (response) => response.json()
3070
+ }, {
3071
+ retryCount: this.featureFlagsRequestMaxRetries,
3072
+ retryCheck: isRetryableFlagsFetchError
3073
+ }, this.featureFlagsRequestTimeoutMs).then((response) => ({
2488
3074
  success: true,
2489
3075
  response: normalizeFlagsResponse(response)
2490
3076
  })).catch((error) => {
@@ -2584,9 +3170,9 @@ class PostHogCoreStateless {
2584
3170
  }
2585
3171
  async getFeatureFlagDetailsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
2586
3172
  await this._initPromise;
2587
- const extraPayload = {};
2588
- if (disableGeoip ?? this.disableGeoip)
2589
- extraPayload["geoip_disable"] = true;
3173
+ const extraPayload = {
3174
+ geoip_disable: disableGeoip ?? this.disableGeoip
3175
+ };
2590
3176
  if (flagKeysToEvaluate)
2591
3177
  extraPayload["flag_keys_to_evaluate"] = flagKeysToEvaluate;
2592
3178
  const result = await this.getFlags(distinctId, groups, personProperties, groupProperties, extraPayload);
@@ -2623,15 +3209,18 @@ class PostHogCoreStateless {
2623
3209
  "Content-Type": "application/json"
2624
3210
  }
2625
3211
  };
2626
- const response = await this.fetchWithRetry(url, fetchOptions).then((response2) => {
2627
- if (response2.status !== 200 || !response2.json) {
2628
- const msg = `Surveys API could not be loaded: ${response2.status}`;
2629
- const error = new Error(msg);
2630
- this._logger.error(error);
2631
- this._events.emit("error", new Error(msg));
2632
- return;
3212
+ const response = await this.fetchWithRetry(url, fetchOptions, {
3213
+ type: "required",
3214
+ consume: (response) => {
3215
+ if (response.status !== 200 || !response.json) {
3216
+ const msg = `Surveys API could not be loaded: ${response.status}`;
3217
+ const error = new Error(msg);
3218
+ this._logger.error(error);
3219
+ this._events.emit("error", new Error(msg));
3220
+ return Promise.resolve(undefined);
3221
+ }
3222
+ return response.json();
2633
3223
  }
2634
- return response2.json();
2635
3224
  }).catch((error) => {
2636
3225
  this._logger.error("Surveys API could not be loaded", error);
2637
3226
  this._events.emit("error", error);
@@ -2668,23 +3257,39 @@ class PostHogCoreStateless {
2668
3257
  return message;
2669
3258
  }
2670
3259
  async flushStorage() {}
2671
- enqueue(type, _message, options) {
3260
+ getQueueRouteKey(_message) {
3261
+ return DEFAULT_QUEUE_ROUTE;
3262
+ }
3263
+ persistedQueueKeyForRoute(_route) {
3264
+ return types_PostHogPersistedProperty.Queue;
3265
+ }
3266
+ getActiveQueueRoutes() {
3267
+ return [
3268
+ DEFAULT_QUEUE_ROUTE
3269
+ ];
3270
+ }
3271
+ getRouteQueue(route) {
3272
+ return this.getPersistedProperty(this.persistedQueueKeyForRoute(route)) || [];
3273
+ }
3274
+ enqueue(type, _message, options, explicitRoute) {
2672
3275
  this.wrap(() => {
2673
3276
  if (this.optedOut)
2674
3277
  return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
2675
- let message = this.prepareMessage(type, _message, options);
3278
+ let message = this.prepareMessage(_message, options);
2676
3279
  message = this.processBeforeEnqueue(message);
2677
3280
  if (message === null)
2678
3281
  return;
2679
- const queue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
3282
+ message = this.normalizeMessage(message);
3283
+ const queueKey = this.persistedQueueKeyForRoute(explicitRoute ?? this.getQueueRouteKey(message));
3284
+ const queue = this.getPersistedProperty(queueKey) || [];
2680
3285
  if (queue.length >= this.maxQueueSize) {
2681
3286
  queue.shift();
2682
- this._logger.info("Queue is full, the oldest event is dropped.");
3287
+ this._logger.warn("Queue is full, the oldest event is dropped.");
2683
3288
  }
2684
3289
  queue.push({
2685
3290
  message
2686
3291
  });
2687
- this.setPersistedProperty(types_PostHogPersistedProperty.Queue, queue);
3292
+ this.setPersistedProperty(queueKey, queue);
2688
3293
  this._events.emit(type, message);
2689
3294
  if (queue.length >= this.flushAt)
2690
3295
  this.flushBackground();
@@ -2692,61 +3297,63 @@ class PostHogCoreStateless {
2692
3297
  this._flushTimer = safeSetTimeout(() => this.flushBackground(), this.flushInterval);
2693
3298
  });
2694
3299
  }
2695
- async sendImmediate(type, _message, options) {
3300
+ async sendImmediate(type, _message, options, explicitRoute) {
2696
3301
  if (this.disabled)
2697
3302
  return void this._logger.warn("The client is disabled");
2698
3303
  if (!this._isInitialized)
2699
3304
  await this._initPromise;
2700
3305
  if (this.optedOut)
2701
3306
  return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
2702
- let message = this.prepareMessage(type, _message, options);
3307
+ let message = this.prepareMessage(_message, options);
2703
3308
  message = this.processBeforeEnqueue(message);
2704
3309
  if (message === null)
2705
3310
  return;
2706
- const data = {
2707
- api_key: this.apiKey,
2708
- batch: [
2709
- message
2710
- ],
2711
- sent_at: currentISOTime()
2712
- };
2713
- if (this.historicalMigration)
2714
- data.historical_migration = true;
2715
- const payload = JSON.stringify(data);
2716
- const url = `${this.host}/batch/`;
2717
- const gzippedPayload = this.disableCompression ? null : await gzipCompress(payload, this.isDebug);
2718
- const fetchOptions = {
2719
- method: "POST",
2720
- headers: {
2721
- ...this.getCustomHeaders(),
2722
- "Content-Type": "application/json",
2723
- ...gzippedPayload !== null && {
2724
- "Content-Encoding": "gzip"
2725
- }
2726
- },
2727
- body: gzippedPayload || payload
2728
- };
3311
+ message = this.normalizeMessage(message);
2729
3312
  try {
2730
- const response = await this.fetchWithRetry(url, fetchOptions);
2731
- await response.body?.cancel()?.catch(() => {});
3313
+ await this.sendBatch([
3314
+ message
3315
+ ], undefined, explicitRoute ?? this.getQueueRouteKey(message));
2732
3316
  } catch (err) {
2733
3317
  this._events.emit("error", err);
2734
3318
  }
2735
3319
  }
2736
- prepareMessage(type, _message, options) {
3320
+ normalizeMessage(message) {
3321
+ const { type: _type, library, library_version, ...sanitizedMessage } = message;
3322
+ let properties = isPostHogEventProperties(sanitizedMessage.properties) ? sanitizedMessage.properties : undefined;
3323
+ if (library !== undefined && properties?.$lib === undefined)
3324
+ properties = {
3325
+ ...properties || {},
3326
+ $lib: library
3327
+ };
3328
+ if (library_version !== undefined && properties?.$lib_version === undefined)
3329
+ properties = {
3330
+ ...properties || {},
3331
+ $lib_version: library_version
3332
+ };
3333
+ if (properties)
3334
+ sanitizedMessage.properties = properties;
3335
+ sanitizedMessage.uuid = getEventUuid(sanitizedMessage.uuid, uuidv7);
3336
+ return sanitizedMessage;
3337
+ }
3338
+ normalizeTimestampForWire(timestamp) {
3339
+ const parsedTimestamp = timestamp instanceof Date ? timestamp : typeof timestamp == "string" ? new Date(timestamp) : null;
3340
+ if (!parsedTimestamp || Number.isNaN(parsedTimestamp.getTime()))
3341
+ return timestamp;
3342
+ const normalized = parsedTimestamp.toISOString();
3343
+ const fractionalSeconds = typeof timestamp == "string" ? timestamp.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1] : undefined;
3344
+ return fractionalSeconds && fractionalSeconds.length > 3 ? normalized.replace(/\.\d{3}Z$/, `.${fractionalSeconds}Z`) : normalized;
3345
+ }
3346
+ prepareMessage(_message, options) {
2737
3347
  const message = {
2738
3348
  ..._message,
2739
- type,
2740
- library: this.getLibraryId(),
2741
- library_version: this.getLibraryVersion(),
2742
3349
  timestamp: options?.timestamp ? options?.timestamp : currentISOTime(),
2743
- uuid: options?.uuid ? options.uuid : uuidv7()
3350
+ uuid: getEventUuid(options?.uuid, uuidv7)
2744
3351
  };
2745
3352
  const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip;
2746
3353
  if (addGeoipDisableProperty) {
2747
- if (!message.properties)
3354
+ if (!isPostHogEventProperties(message.properties))
2748
3355
  message.properties = {};
2749
- message["properties"]["$geoip_disable"] = true;
3356
+ message.properties["$geoip_disable"] = true;
2750
3357
  }
2751
3358
  if (message.distinctId) {
2752
3359
  message.distinct_id = message.distinctId;
@@ -2761,21 +3368,64 @@ class PostHogCoreStateless {
2761
3368
  }
2762
3369
  }
2763
3370
  flushBackground() {
3371
+ if (this.pendingFlushPromise)
3372
+ return;
2764
3373
  this.flush().catch(async (err) => {
2765
3374
  await logFlushError(err);
2766
3375
  });
2767
3376
  }
2768
- async flush() {
3377
+ async waitForPendingPromises(maxPromiseId, ignoredPromises = []) {
3378
+ const ignoredPendingPromises = ignoredPromises.filter((promise) => !!promise);
3379
+ let iteration = 0;
3380
+ while (true) {
3381
+ const promises = this.promiseQueue.getPromises([
3382
+ ...ignoredPendingPromises,
3383
+ ...this.flushPromises
3384
+ ], maxPromiseId);
3385
+ if (promises.length === 0)
3386
+ return;
3387
+ if (iteration > 0)
3388
+ this._logger.debug(`flush() re-checking ${promises.length} pending promise(s) before flushing`);
3389
+ await Promise.all(promises.map((promise) => promise.catch(() => {})));
3390
+ iteration++;
3391
+ }
3392
+ }
3393
+ flushWithPendingPromises() {
3394
+ return this.flushInternal(true);
3395
+ }
3396
+ flush() {
3397
+ return this.flushInternal(false);
3398
+ }
3399
+ flushInternal(waitForPendingPromises) {
2769
3400
  if (this.disabled)
2770
- return;
2771
- const nextFlushPromise = allSettled([
2772
- this.flushPromise
2773
- ]).then(() => this._flush());
3401
+ return Promise.resolve();
3402
+ if (!waitForPendingPromises && this.pendingFlushPromise)
3403
+ return this.pendingFlushPromise;
3404
+ const previousFlushPromise = this.flushPromise;
3405
+ const maxPromiseId = this.promiseQueue.maxId;
3406
+ const nextFlushPromise = Promise.resolve().then(() => {
3407
+ if (waitForPendingPromises)
3408
+ return this.waitForPendingPromises(maxPromiseId, [
3409
+ previousFlushPromise,
3410
+ nextFlushPromise
3411
+ ]);
3412
+ }).then(() => allSettled([
3413
+ previousFlushPromise
3414
+ ])).then(() => {
3415
+ if (this.pendingFlushPromise === nextFlushPromise)
3416
+ this.pendingFlushPromise = null;
3417
+ return this._flush();
3418
+ });
3419
+ this.pendingFlushPromise = nextFlushPromise;
2774
3420
  this.flushPromise = nextFlushPromise;
3421
+ this.flushPromises.add(nextFlushPromise);
2775
3422
  this.addPendingPromise(nextFlushPromise);
2776
3423
  allSettled([
2777
3424
  nextFlushPromise
2778
3425
  ]).then(() => {
3426
+ this.flushPromises.delete(nextFlushPromise);
3427
+ if (this.pendingFlushPromise === nextFlushPromise)
3428
+ this.pendingFlushPromise = null;
2779
3429
  if (this.flushPromise === nextFlushPromise)
2780
3430
  this.flushPromise = null;
2781
3431
  });
@@ -2788,55 +3438,102 @@ class PostHogCoreStateless {
2788
3438
  headers["User-Agent"] = customUserAgent;
2789
3439
  return headers;
2790
3440
  }
3441
+ compressPayload(payload) {
3442
+ return gzipCompress(payload, this.isDebug);
3443
+ }
3444
+ getBatchEndpointPath(_route) {
3445
+ return "/batch/";
3446
+ }
3447
+ async sendBatch(batchMessages, retryOptions, route = DEFAULT_QUEUE_ROUTE) {
3448
+ const data = {
3449
+ api_key: this.apiKey,
3450
+ batch: batchMessages.map((message) => {
3451
+ if (!message)
3452
+ return message;
3453
+ const timestamp = this.normalizeTimestampForWire(message.timestamp);
3454
+ return timestamp === message.timestamp ? message : {
3455
+ ...message,
3456
+ timestamp
3457
+ };
3458
+ }),
3459
+ sent_at: currentISOTime()
3460
+ };
3461
+ if (this.historicalMigration)
3462
+ data.historical_migration = true;
3463
+ const payload = safeJsonStringify(data);
3464
+ const url = `${this.host}${this.getBatchEndpointPath(route)}`;
3465
+ const gzippedPayload = this.disableCompression ? null : await this.compressPayload(payload);
3466
+ const fetchOptions = {
3467
+ method: "POST",
3468
+ headers: {
3469
+ ...this.getCustomHeaders(),
3470
+ "Content-Type": "application/json",
3471
+ ...gzippedPayload !== null && {
3472
+ "Content-Encoding": "gzip"
3473
+ }
3474
+ },
3475
+ body: gzippedPayload || payload
3476
+ };
3477
+ await this.fetchWithRetry(url, fetchOptions, {
3478
+ type: "successful-write"
3479
+ }, retryOptions);
3480
+ }
2791
3481
  async _flush() {
2792
3482
  this.clearFlushTimer();
2793
3483
  await this._initPromise;
2794
- let queue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
2795
- if (!queue.length)
3484
+ const routes = this.getActiveQueueRoutes();
3485
+ if (!routes.some((route) => this.getRouteQueue(route).length > 0))
2796
3486
  return;
2797
3487
  const sentMessages = [];
3488
+ let firstError;
3489
+ for (const route of routes)
3490
+ try {
3491
+ await this._flushRoute(route, sentMessages);
3492
+ } catch (err) {
3493
+ if (firstError === undefined)
3494
+ firstError = err;
3495
+ }
3496
+ if (firstError !== undefined)
3497
+ throw firstError;
3498
+ this._events.emit("flush", sentMessages);
3499
+ }
3500
+ async _flushRoute(route, sentMessages) {
3501
+ const queueKey = this.persistedQueueKeyForRoute(route);
3502
+ let queue = this.getPersistedProperty(queueKey) || [];
3503
+ if (!queue.length)
3504
+ return;
2798
3505
  const originalQueueLength = queue.length;
2799
- while (queue.length > 0 && sentMessages.length < originalQueueLength) {
3506
+ let sentFromRoute = 0;
3507
+ while (queue.length > 0 && sentFromRoute < originalQueueLength) {
2800
3508
  const batchItems = queue.slice(0, this.maxBatchSize);
2801
- const batchMessages = batchItems.map((item) => item.message);
3509
+ const batchMessages = batchItems.map((item) => item.message === undefined ? item.message : this.normalizeMessage(item.message));
2802
3510
  const persistQueueChange = async () => {
2803
- const refreshedQueue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
2804
- const newQueue = refreshedQueue.slice(batchItems.length);
2805
- this.setPersistedProperty(types_PostHogPersistedProperty.Queue, newQueue);
3511
+ const refreshedQueue = this.getPersistedProperty(queueKey) || [];
3512
+ const remainingBatchItems = [
3513
+ ...batchItems
3514
+ ];
3515
+ const newQueue = refreshedQueue.filter((item) => {
3516
+ const itemUuid = item.message?.uuid;
3517
+ const batchItemIndex = remainingBatchItems.findIndex((batchItem) => batchItem === item || typeof itemUuid == "string" && itemUuid.length > 0 && batchItem.message?.uuid === itemUuid);
3518
+ if (batchItemIndex === -1)
3519
+ return true;
3520
+ remainingBatchItems.splice(batchItemIndex, 1);
3521
+ return false;
3522
+ });
3523
+ this.setPersistedProperty(queueKey, newQueue);
2806
3524
  queue = newQueue;
3525
+ this._dequeuedMessagesCount += batchItems.length;
2807
3526
  await this.flushStorage();
2808
3527
  };
2809
- const data = {
2810
- api_key: this.apiKey,
2811
- batch: batchMessages,
2812
- sent_at: currentISOTime()
2813
- };
2814
- if (this.historicalMigration)
2815
- data.historical_migration = true;
2816
- const payload = JSON.stringify(data);
2817
- const url = `${this.host}/batch/`;
2818
- const gzippedPayload = this.disableCompression ? null : await gzipCompress(payload, this.isDebug);
2819
- const fetchOptions = {
2820
- method: "POST",
2821
- headers: {
2822
- ...this.getCustomHeaders(),
2823
- "Content-Type": "application/json",
2824
- ...gzippedPayload !== null && {
2825
- "Content-Encoding": "gzip"
2826
- }
2827
- },
2828
- body: gzippedPayload || payload
2829
- };
2830
3528
  const retryOptions = {
2831
3529
  retryCheck: (err) => {
2832
3530
  if (isPostHogFetchContentTooLargeError(err))
2833
3531
  return false;
2834
- return isPostHogFetchError(err);
3532
+ return isPostHogFetchRetryableError(err);
2835
3533
  }
2836
3534
  };
2837
3535
  try {
2838
- const response = await this.fetchWithRetry(url, fetchOptions, retryOptions);
2839
- await response.body?.cancel()?.catch(() => {});
3536
+ await this.sendBatch(batchMessages, retryOptions, route);
2840
3537
  } catch (err) {
2841
3538
  if (isPostHogFetchContentTooLargeError(err) && batchMessages.length > 1) {
2842
3539
  this.maxBatchSize = Math.max(1, Math.floor(batchMessages.length / 2));
@@ -2850,8 +3547,8 @@ class PostHogCoreStateless {
2850
3547
  }
2851
3548
  await persistQueueChange();
2852
3549
  sentMessages.push(...batchMessages);
3550
+ sentFromRoute += batchMessages.length;
2853
3551
  }
2854
- this._events.emit("flush", sentMessages);
2855
3552
  }
2856
3553
  async _sendLogsBatch(payload) {
2857
3554
  if (this.disabled)
@@ -2861,7 +3558,7 @@ class PostHogCoreStateless {
2861
3558
  };
2862
3559
  const serialized = JSON.stringify(payload);
2863
3560
  const url = `${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`;
2864
- const gzippedPayload = this.disableCompression ? null : await gzipCompress(serialized, this.isDebug);
3561
+ const gzippedPayload = this.disableCompression ? null : await this.compressPayload(serialized);
2865
3562
  const fetchOptions = {
2866
3563
  method: "POST",
2867
3564
  headers: {
@@ -2875,10 +3572,12 @@ class PostHogCoreStateless {
2875
3572
  };
2876
3573
  try {
2877
3574
  await this.fetchWithRetry(url, fetchOptions, {
3575
+ type: "successful-write"
3576
+ }, {
2878
3577
  retryCheck: (err) => {
2879
3578
  if (isPostHogFetchContentTooLargeError(err))
2880
3579
  return false;
2881
- return isPostHogFetchError(err);
3580
+ return isPostHogFetchRetryableError(err);
2882
3581
  }
2883
3582
  });
2884
3583
  return {
@@ -2900,41 +3599,155 @@ class PostHogCoreStateless {
2900
3599
  };
2901
3600
  }
2902
3601
  }
2903
- async fetchWithRetry(url, options, retryOptions, requestTimeout) {
3602
+ async _sendMetricsBatch(payload) {
3603
+ if (this.disabled)
3604
+ return {
3605
+ kind: "fatal",
3606
+ error: new Error("The client is disabled")
3607
+ };
3608
+ const serialized = JSON.stringify(payload);
3609
+ const url = `${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`;
3610
+ const gzippedPayload = this.disableCompression ? null : await this.compressPayload(serialized);
3611
+ const fetchOptions = {
3612
+ method: "POST",
3613
+ headers: {
3614
+ ...this.getCustomHeaders(),
3615
+ "Content-Type": "application/json",
3616
+ ...gzippedPayload !== null && {
3617
+ "Content-Encoding": "gzip"
3618
+ }
3619
+ },
3620
+ body: gzippedPayload || serialized
3621
+ };
3622
+ try {
3623
+ await this.fetchWithRetry(url, fetchOptions, {
3624
+ type: "successful-write"
3625
+ }, {
3626
+ retryCheck: (err) => {
3627
+ if (isPostHogFetchContentTooLargeError(err))
3628
+ return false;
3629
+ return isPostHogFetchRetryableError(err);
3630
+ }
3631
+ });
3632
+ return {
3633
+ kind: "ok"
3634
+ };
3635
+ } catch (err) {
3636
+ if (isPostHogFetchContentTooLargeError(err))
3637
+ return {
3638
+ kind: "too-large"
3639
+ };
3640
+ if (isPostHogFetchRetryableError(err))
3641
+ return {
3642
+ kind: "retry-later",
3643
+ error: err
3644
+ };
3645
+ return {
3646
+ kind: "fatal",
3647
+ error: err
3648
+ };
3649
+ }
3650
+ }
3651
+ async fetchWithRetry(url, options, responseHandling, retryOptions, requestTimeout) {
2904
3652
  const body = options.body ? options.body : "";
2905
3653
  let reqByteLength = -1;
2906
3654
  try {
2907
- reqByteLength = body instanceof Blob ? body.size : Buffer.byteLength(body, STRING_FORMAT);
3655
+ reqByteLength = body instanceof Blob ? body.size : body instanceof Uint8Array ? body.byteLength : Buffer.byteLength(body, STRING_FORMAT);
2908
3656
  } catch {
2909
3657
  if (body instanceof Blob)
2910
3658
  reqByteLength = body.size;
3659
+ else if (body instanceof Uint8Array)
3660
+ reqByteLength = body.byteLength;
2911
3661
  else {
2912
3662
  const encoded = new TextEncoder().encode(body);
2913
3663
  reqByteLength = encoded.length;
2914
3664
  }
2915
3665
  }
3666
+ const retriableOptions = {
3667
+ ...this._retryOptions,
3668
+ ...retryOptions
3669
+ };
3670
+ let attempt = 0;
2916
3671
  return await retriable(async () => {
3672
+ attempt++;
2917
3673
  const ctrl = new AbortController;
2918
3674
  const timeoutMs = requestTimeout ?? this.requestTimeout;
2919
- const timer = safeSetTimeout(() => ctrl.abort(), timeoutMs);
2920
- let res = null;
3675
+ const requestDeadline = Date.now() + timeoutMs;
3676
+ let timer;
3677
+ const deadline = new Promise((_resolve, reject) => {
3678
+ timer = safeSetTimeout(() => {
3679
+ const timeoutError = new Error(`Request timed out after ${timeoutMs}ms`);
3680
+ timeoutError.name = "AbortError";
3681
+ reject(timeoutError);
3682
+ ctrl.abort(timeoutError);
3683
+ }, timeoutMs);
3684
+ });
3685
+ let res;
3686
+ let responseAccepted = false;
3687
+ let cancellation;
3688
+ const cancelBody = () => cancellation ??= (async () => {
3689
+ try {
3690
+ await res?.body?.cancel();
3691
+ } catch {}
3692
+ })();
2921
3693
  try {
2922
- res = await this.fetch(url, {
2923
- signal: ctrl.signal,
2924
- ...options
2925
- });
2926
- } catch (e) {
2927
- throw new PostHogFetchNetworkError(e);
3694
+ let fetchPromise;
3695
+ try {
3696
+ fetchPromise = this.fetch(url, {
3697
+ signal: ctrl.signal,
3698
+ ...options
3699
+ });
3700
+ } catch (e) {
3701
+ throw new PostHogFetchNetworkError(e);
3702
+ }
3703
+ fetchPromise.then((lateResponse) => {
3704
+ if (ctrl.signal.aborted && !responseAccepted)
3705
+ Promise.resolve(lateResponse.body?.cancel()).catch(() => {});
3706
+ }).catch(() => {});
3707
+ try {
3708
+ res = await Promise.race([
3709
+ fetchPromise,
3710
+ deadline
3711
+ ]);
3712
+ responseAccepted = true;
3713
+ } catch (e) {
3714
+ throw new PostHogFetchNetworkError(e);
3715
+ }
3716
+ const isNoCors = options.mode === "no-cors";
3717
+ if (!isNoCors && (res.status < 200 || res.status >= 400))
3718
+ throw new PostHogFetchHttpError(res, reqByteLength, requestDeadline, ctrl);
3719
+ if (responseHandling.type === "successful-write") {
3720
+ try {
3721
+ await Promise.race([
3722
+ cancelBody(),
3723
+ deadline
3724
+ ]);
3725
+ } catch {}
3726
+ return;
3727
+ }
3728
+ try {
3729
+ return await Promise.race([
3730
+ responseHandling.consume(res),
3731
+ deadline
3732
+ ]);
3733
+ } catch (e) {
3734
+ if (ctrl.signal.aborted)
3735
+ throw new PostHogFetchNetworkError(e);
3736
+ throw e;
3737
+ }
2928
3738
  } finally {
2929
3739
  clearTimeout(timer);
3740
+ if (ctrl.signal.aborted && res)
3741
+ cancelBody();
2930
3742
  }
2931
- const isNoCors = options.mode === "no-cors";
2932
- if (!isNoCors && (res.status < 200 || res.status >= 400))
2933
- throw new PostHogFetchHttpError(res, reqByteLength);
2934
- return res;
2935
3743
  }, {
2936
- ...this._retryOptions,
2937
- ...retryOptions
3744
+ ...retriableOptions,
3745
+ retryCheck: (error) => {
3746
+ const shouldRetry = retriableOptions.retryCheck(error);
3747
+ if (shouldRetry && attempt <= retriableOptions.retryCount && error instanceof PostHogFetchHttpError)
3748
+ error.cancelResponseBody();
3749
+ return shouldRetry;
3750
+ }
2938
3751
  });
2939
3752
  }
2940
3753
  async _shutdown(shutdownTimeoutMs = 30000) {
@@ -2947,12 +3760,17 @@ class PostHogCoreStateless {
2947
3760
  try {
2948
3761
  await this.promiseQueue.join();
2949
3762
  while (true) {
2950
- const queue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
2951
- if (queue.length === 0)
3763
+ const hasQueuedEvents = this.getActiveQueueRoutes().some((route) => this.getRouteQueue(route).length > 0);
3764
+ if (!hasQueuedEvents)
2952
3765
  break;
3766
+ const dequeuedBeforeFlush = this._dequeuedMessagesCount;
2953
3767
  await this.flush();
2954
3768
  if (hasTimedOut)
2955
3769
  break;
3770
+ if (this._dequeuedMessagesCount === dequeuedBeforeFlush) {
3771
+ this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");
3772
+ break;
3773
+ }
2956
3774
  }
2957
3775
  } catch (e) {
2958
3776
  if (!isPostHogFetchError(e))
@@ -2960,21 +3778,12 @@ class PostHogCoreStateless {
2960
3778
  await logFlushError(e);
2961
3779
  }
2962
3780
  };
2963
- let timeoutHandle;
2964
- try {
2965
- return await Promise.race([
2966
- new Promise((_, reject) => {
2967
- timeoutHandle = safeSetTimeout(() => {
2968
- this._logger.error("Timed out while shutting down PostHog");
2969
- hasTimedOut = true;
2970
- reject("Timeout while shutting down PostHog. Some events may not have been sent.");
2971
- }, shutdownTimeoutMs);
2972
- }),
2973
- doShutdown()
2974
- ]);
2975
- } finally {
2976
- clearTimeout(timeoutHandle);
2977
- }
3781
+ return raceWithTimeout(doShutdown(), shutdownTimeoutMs, () => {
3782
+ this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.", {
3783
+ shutdownTimeoutMs
3784
+ });
3785
+ hasTimedOut = true;
3786
+ });
2978
3787
  }
2979
3788
  async shutdown(shutdownTimeoutMs = 30000) {
2980
3789
  if (this.shutdownPromise)
@@ -2986,21 +3795,30 @@ class PostHogCoreStateless {
2986
3795
  return this.shutdownPromise;
2987
3796
  }
2988
3797
  }
2989
- // ../../../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/context-lines.node.mjs
2990
- import { createReadStream } from "node:fs";
3798
+ // ../../../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/context-lines.node.mjs
3799
+ import { constants as constants2 } from "node:fs";
3800
+ import { open as promises_open } from "node:fs/promises";
3801
+ import { isAbsolute } from "node:path";
2991
3802
  import { createInterface } from "node:readline";
2992
- var LRU_FILE_CONTENTS_CACHE = new exports_error_tracking.ReduceableCache(25);
2993
- var LRU_FILE_CONTENTS_FS_READ_FAILED = new exports_error_tracking.ReduceableCache(20);
3803
+ var LRU_FILE_CONTENTS_CACHE = new ReduceableCache(25);
3804
+ var LRU_FILE_CONTENTS_FS_READ_FAILED = new ReduceableCache(20);
2994
3805
  var DEFAULT_LINES_OF_CONTEXT = 7;
2995
3806
  var MAX_CONTEXTLINES_COLNO = 1000;
2996
3807
  var MAX_CONTEXTLINES_LINENO = 1e4;
2997
- async function addSourceContext(frames) {
3808
+ var MAX_CONTEXTLINES_FILE_SIZE = 10485760;
3809
+ async function addSourceContext(frames, openSourceFile = promises_open, logger) {
2998
3810
  const filesToLines = {};
3811
+ let basePath;
3812
+ try {
3813
+ basePath = process.cwd();
3814
+ } catch {}
2999
3815
  for (let i = frames.length - 1;i >= 0; i--) {
3000
3816
  const frame = frames[i];
3001
3817
  const filename = frame?.filename;
3002
3818
  if (!frame || typeof filename != "string" || typeof frame.lineno != "number" || shouldSkipContextLinesForFile(filename) || shouldSkipContextLinesForFrame(frame))
3003
3819
  continue;
3820
+ if (!isAbsolute(filename) && basePath === undefined)
3821
+ continue;
3004
3822
  const filesToLinesOutput = filesToLines[filename];
3005
3823
  if (!filesToLinesOutput)
3006
3824
  filesToLines[filename] = [];
@@ -3011,50 +3829,98 @@ async function addSourceContext(frames) {
3011
3829
  return frames;
3012
3830
  const readlinePromises = [];
3013
3831
  for (const file of files) {
3014
- if (LRU_FILE_CONTENTS_FS_READ_FAILED.get(file))
3832
+ const cacheKey = makeSourceCacheKey(file, basePath);
3833
+ if (cacheKey === undefined)
3834
+ continue;
3835
+ if (LRU_FILE_CONTENTS_FS_READ_FAILED.get(cacheKey))
3015
3836
  continue;
3016
3837
  const filesToLineRanges = filesToLines[file];
3017
3838
  if (!filesToLineRanges)
3018
3839
  continue;
3019
3840
  filesToLineRanges.sort((a, b) => a - b);
3020
3841
  const ranges = makeLineReaderRanges(filesToLineRanges);
3021
- if (ranges.every((r) => rangeExistsInContentCache(file, r)))
3842
+ if (ranges.every((r) => rangeExistsInContentCache(cacheKey, r)))
3022
3843
  continue;
3023
- const cache = emplace(LRU_FILE_CONTENTS_CACHE, file, {});
3024
- readlinePromises.push(getContextLinesFromFile(file, ranges, cache));
3844
+ const cache = emplace(LRU_FILE_CONTENTS_CACHE, cacheKey, {});
3845
+ readlinePromises.push(getContextLinesFromFile(file, ranges, cache, cacheKey, openSourceFile, logger));
3025
3846
  }
3026
3847
  await Promise.all(readlinePromises).catch(() => {});
3027
3848
  if (frames && frames.length > 0)
3028
- addSourceContextToFrames(frames, LRU_FILE_CONTENTS_CACHE);
3849
+ addSourceContextToFrames(frames, LRU_FILE_CONTENTS_CACHE, basePath);
3029
3850
  LRU_FILE_CONTENTS_CACHE.reduce();
3030
3851
  return frames;
3031
3852
  }
3032
- function getContextLinesFromFile(path2, ranges, output) {
3853
+ async function openRegularSourceFile(path, openSourceFile, logger) {
3854
+ let fileHandle;
3855
+ let isValid = false;
3856
+ try {
3857
+ fileHandle = await openSourceFile(path, constants2.O_RDONLY | constants2.O_NONBLOCK);
3858
+ const fileStat = await fileHandle.stat();
3859
+ if (!fileStat.isFile())
3860
+ return;
3861
+ if (fileStat.size > MAX_CONTEXTLINES_FILE_SIZE)
3862
+ return void logger?.debug(`Skipping source context for oversized file ${path}: ${fileStat.size} bytes exceeds ${MAX_CONTEXTLINES_FILE_SIZE}`);
3863
+ isValid = true;
3864
+ return fileHandle;
3865
+ } catch {
3866
+ return;
3867
+ } finally {
3868
+ if (fileHandle && !isValid)
3869
+ await fileHandle.close().catch(() => {});
3870
+ }
3871
+ }
3872
+ async function getContextLinesFromFile(path, ranges, output, cacheKey, openSourceFile, logger) {
3873
+ const fileHandle = await openRegularSourceFile(path, openSourceFile, logger);
3874
+ if (fileHandle === undefined)
3875
+ return void LRU_FILE_CONTENTS_FS_READ_FAILED.set(cacheKey, 1);
3876
+ const openedFileHandle = fileHandle;
3033
3877
  return new Promise((resolve) => {
3034
- const stream = createReadStream(path2);
3035
- const lineReaded = createInterface({
3036
- input: stream
3037
- });
3038
- function destroyStreamAndResolve() {
3039
- stream.destroy();
3040
- resolve();
3878
+ let finished = false;
3879
+ function destroyStreamAndResolve(stream) {
3880
+ if (finished)
3881
+ return;
3882
+ finished = true;
3883
+ stream?.destroy();
3884
+ openedFileHandle.close().then(resolve, resolve);
3885
+ }
3886
+ let stream;
3887
+ try {
3888
+ stream = openedFileHandle.createReadStream({
3889
+ autoClose: false,
3890
+ start: 0,
3891
+ end: MAX_CONTEXTLINES_FILE_SIZE - 1
3892
+ });
3893
+ } catch {
3894
+ LRU_FILE_CONTENTS_FS_READ_FAILED.set(cacheKey, 1);
3895
+ destroyStreamAndResolve();
3896
+ return;
3897
+ }
3898
+ let lineReaded;
3899
+ try {
3900
+ lineReaded = createInterface({
3901
+ input: stream
3902
+ });
3903
+ } catch {
3904
+ LRU_FILE_CONTENTS_FS_READ_FAILED.set(cacheKey, 1);
3905
+ destroyStreamAndResolve(stream);
3906
+ return;
3041
3907
  }
3042
3908
  let lineNumber = 0;
3043
3909
  let currentRangeIndex = 0;
3044
3910
  const range = ranges[currentRangeIndex];
3045
3911
  if (range === undefined)
3046
- return void destroyStreamAndResolve();
3912
+ return void destroyStreamAndResolve(stream);
3047
3913
  let rangeStart = range[0];
3048
3914
  let rangeEnd = range[1];
3049
3915
  function onStreamError() {
3050
- LRU_FILE_CONTENTS_FS_READ_FAILED.set(path2, 1);
3916
+ LRU_FILE_CONTENTS_FS_READ_FAILED.set(cacheKey, 1);
3051
3917
  lineReaded.close();
3052
3918
  lineReaded.removeAllListeners();
3053
- destroyStreamAndResolve();
3919
+ destroyStreamAndResolve(stream);
3054
3920
  }
3055
3921
  stream.on("error", onStreamError);
3056
3922
  lineReaded.on("error", onStreamError);
3057
- lineReaded.on("close", destroyStreamAndResolve);
3923
+ lineReaded.on("close", () => destroyStreamAndResolve(stream));
3058
3924
  lineReaded.on("line", (line) => {
3059
3925
  lineNumber++;
3060
3926
  if (lineNumber < rangeStart)
@@ -3067,22 +3933,23 @@ function getContextLinesFromFile(path2, ranges, output) {
3067
3933
  return;
3068
3934
  }
3069
3935
  currentRangeIndex++;
3070
- const range2 = ranges[currentRangeIndex];
3071
- if (range2 === undefined) {
3936
+ const range = ranges[currentRangeIndex];
3937
+ if (range === undefined) {
3072
3938
  lineReaded.close();
3073
3939
  lineReaded.removeAllListeners();
3074
3940
  return;
3075
3941
  }
3076
- rangeStart = range2[0];
3077
- rangeEnd = range2[1];
3942
+ rangeStart = range[0];
3943
+ rangeEnd = range[1];
3078
3944
  }
3079
3945
  });
3080
3946
  });
3081
3947
  }
3082
- function addSourceContextToFrames(frames, cache) {
3948
+ function addSourceContextToFrames(frames, cache, basePath) {
3083
3949
  for (const frame of frames)
3084
3950
  if (frame.filename && frame.context_line === undefined && typeof frame.lineno == "number") {
3085
- const contents = cache.get(frame.filename);
3951
+ const cacheKey = makeSourceCacheKey(frame.filename, basePath);
3952
+ const contents = cacheKey === undefined ? undefined : cache.get(cacheKey);
3086
3953
  if (contents === undefined)
3087
3954
  continue;
3088
3955
  addContextToFrame(frame.lineno, frame, contents);
@@ -3115,8 +3982,8 @@ function clearLineContext(frame) {
3115
3982
  delete frame.context_line;
3116
3983
  delete frame.post_context;
3117
3984
  }
3118
- function shouldSkipContextLinesForFile(path2) {
3119
- return path2.startsWith("node:") || path2.endsWith(".min.js") || path2.endsWith(".min.cjs") || path2.endsWith(".min.mjs") || path2.startsWith("data:");
3985
+ function shouldSkipContextLinesForFile(path) {
3986
+ return path.startsWith("node:") || path.endsWith(".min.js") || path.endsWith(".min.cjs") || path.endsWith(".min.mjs") || path.startsWith("data:");
3120
3987
  }
3121
3988
  function shouldSkipContextLinesForFrame(frame) {
3122
3989
  if (frame.lineno !== undefined && frame.lineno > MAX_CONTEXTLINES_LINENO)
@@ -3125,8 +3992,19 @@ function shouldSkipContextLinesForFrame(frame) {
3125
3992
  return true;
3126
3993
  return false;
3127
3994
  }
3128
- function rangeExistsInContentCache(file, range) {
3129
- const contents = LRU_FILE_CONTENTS_CACHE.get(file);
3995
+ function makeSourceCacheKey(path, basePath) {
3996
+ if (isAbsolute(path))
3997
+ return JSON.stringify([
3998
+ null,
3999
+ path
4000
+ ]);
4001
+ return basePath === undefined ? undefined : JSON.stringify([
4002
+ basePath,
4003
+ path
4004
+ ]);
4005
+ }
4006
+ function rangeExistsInContentCache(cacheKey, range) {
4007
+ const contents = LRU_FILE_CONTENTS_CACHE.get(cacheKey);
3130
4008
  if (contents === undefined)
3131
4009
  return false;
3132
4010
  for (let i = range[0];i <= range[1]; i++)
@@ -3204,8 +4082,8 @@ function snipLine(line, colno) {
3204
4082
  return newLine;
3205
4083
  }
3206
4084
 
3207
- // ../../../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/relative-path.node.mjs
3208
- import { isAbsolute, relative, sep as sep2 } from "path";
4085
+ // ../../../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/relative-path.node.mjs
4086
+ import { isAbsolute as isAbsolute2, relative, sep as sep2 } from "path";
3209
4087
  function createRelativePathModifier(basePath = process.cwd()) {
3210
4088
  const isWindows = sep2 === "\\";
3211
4089
  const toUnix = (p) => isWindows ? p.replace(/\\/g, "/") : p;
@@ -3213,17 +4091,17 @@ function createRelativePathModifier(basePath = process.cwd()) {
3213
4091
  return async (frames) => {
3214
4092
  for (const frame of frames)
3215
4093
  if (!(!frame.filename || frame.filename.startsWith("node:") || frame.filename.startsWith("data:"))) {
3216
- if (isAbsolute(frame.filename))
4094
+ if (isAbsolute2(frame.filename))
3217
4095
  frame.filename = toUnix(relative(normalizedBase, toUnix(frame.filename)));
3218
4096
  }
3219
4097
  return frames;
3220
4098
  };
3221
4099
  }
3222
4100
 
3223
- // ../../../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/version.mjs
3224
- var version = "5.35.12";
4101
+ // ../../../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/version.mjs
4102
+ var version = "5.51.1";
3225
4103
 
3226
- // ../../../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/types.mjs
4104
+ // ../../../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/types.mjs
3227
4105
  var FeatureFlagError2 = {
3228
4106
  ERRORS_WHILE_COMPUTING: "errors_while_computing_flags",
3229
4107
  FLAG_MISSING: "flag_missing",
@@ -3231,7 +4109,7 @@ var FeatureFlagError2 = {
3231
4109
  UNKNOWN_ERROR: "unknown_error"
3232
4110
  };
3233
4111
 
3234
- // ../../../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/feature-flag-evaluations.mjs
4112
+ // ../../../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/feature-flag-evaluations.mjs
3235
4113
  class FeatureFlagEvaluations {
3236
4114
  constructor(init) {
3237
4115
  this._host = init.host;
@@ -3247,10 +4125,10 @@ class FeatureFlagEvaluations {
3247
4125
  this._accessed = init.accessed ?? new Set;
3248
4126
  this._isSlice = init.isSlice ?? false;
3249
4127
  }
3250
- isEnabled(key) {
4128
+ isEnabled(key, options = {}) {
3251
4129
  const flag = this._flags[key];
3252
4130
  this._recordAccess(key);
3253
- return flag?.enabled ?? false;
4131
+ return flag?.enabled ?? options.defaultValue ?? false;
3254
4132
  }
3255
4133
  getFlag(key) {
3256
4134
  const flag = this._flags[key];
@@ -3340,6 +4218,8 @@ class FeatureFlagEvaluations {
3340
4218
  $feature_flag_request_id: this._requestId,
3341
4219
  $feature_flag_evaluated_at: flag?.locallyEvaluated ? Date.now() : this._evaluatedAt
3342
4220
  };
4221
+ if (flag?.hasExperiment !== undefined)
4222
+ properties.$feature_flag_has_experiment = flag.hasExperiment;
3343
4223
  if (flag?.locallyEvaluated && this._flagDefinitionsLoadedAt !== undefined)
3344
4224
  properties.$feature_flag_definitions_loaded_at = this._flagDefinitionsLoadedAt;
3345
4225
  const errors = [];
@@ -3362,7 +4242,7 @@ class FeatureFlagEvaluations {
3362
4242
  }
3363
4243
  }
3364
4244
 
3365
- // ../../../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/feature-flags/crypto.mjs
4245
+ // ../../../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/feature-flags/crypto.mjs
3366
4246
  async function hashSHA1(text) {
3367
4247
  const subtle = globalThis.crypto?.subtle;
3368
4248
  if (!subtle)
@@ -3372,7 +4252,7 @@ async function hashSHA1(text) {
3372
4252
  return hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
3373
4253
  }
3374
4254
 
3375
- // ../../../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/feature-flags/feature-flags.mjs
4255
+ // ../../../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/feature-flags/feature-flags.mjs
3376
4256
  var SIXTY_SECONDS = 60000;
3377
4257
  var LONG_SCALE = 1152921504606847000;
3378
4258
  var NULL_VALUES_ALLOWED_OPERATORS = [
@@ -3389,22 +4269,23 @@ class ClientError extends Error {
3389
4269
  Object.setPrototypeOf(this, ClientError.prototype);
3390
4270
  }
3391
4271
  }
4272
+ function setCustomErrorPrototype(error, constructor) {
4273
+ error.name = constructor.name;
4274
+ Error.captureStackTrace(error, constructor);
4275
+ Object.setPrototypeOf(error, constructor.prototype);
4276
+ }
3392
4277
 
3393
4278
  class InconclusiveMatchError extends Error {
3394
4279
  constructor(message) {
3395
4280
  super(message);
3396
- this.name = this.constructor.name;
3397
- Error.captureStackTrace(this, this.constructor);
3398
- Object.setPrototypeOf(this, InconclusiveMatchError.prototype);
4281
+ setCustomErrorPrototype(this, InconclusiveMatchError);
3399
4282
  }
3400
4283
  }
3401
4284
 
3402
4285
  class RequiresServerEvaluation extends Error {
3403
4286
  constructor(message) {
3404
4287
  super(message);
3405
- this.name = this.constructor.name;
3406
- Error.captureStackTrace(this, this.constructor);
3407
- Object.setPrototypeOf(this, RequiresServerEvaluation.prototype);
4288
+ setCustomErrorPrototype(this, RequiresServerEvaluation);
3408
4289
  }
3409
4290
  }
3410
4291
 
@@ -3413,6 +4294,7 @@ class FeatureFlagsPoller {
3413
4294
  this.debugMode = false;
3414
4295
  this.shouldBeginExponentialBackoff = false;
3415
4296
  this.backOffCount = 0;
4297
+ this.pollerStopped = false;
3416
4298
  this.pollingInterval = pollingInterval;
3417
4299
  this.personalApiKey = personalApiKey;
3418
4300
  this.featureFlags = [];
@@ -3428,6 +4310,7 @@ class FeatureFlagsPoller {
3428
4310
  this.onError = options.onError;
3429
4311
  this.customHeaders = customHeaders;
3430
4312
  this.onLoad = options.onLoad;
4313
+ this.onMinimalFlagCalledEvents = options.onMinimalFlagCalledEvents;
3431
4314
  this.cacheProvider = options.cacheProvider;
3432
4315
  this.strictLocalEvaluation = options.strictLocalEvaluation ?? false;
3433
4316
  this.loadFeatureFlags();
@@ -3625,6 +4508,7 @@ class FeatureFlagsPoller {
3625
4508
  const flagFilters = flag.filters || {};
3626
4509
  const flagConditions = flagFilters.groups || [];
3627
4510
  const flagAggregation = flagFilters.aggregation_group_type_index;
4511
+ const earlyExitEnabled = flagFilters.early_exit ?? false;
3628
4512
  const { groups, groupProperties } = evaluationContext;
3629
4513
  let isInconclusive = false;
3630
4514
  let result;
@@ -3648,12 +4532,15 @@ class FeatureFlagsPoller {
3648
4532
  effectiveBucketingValue = groups[groupName];
3649
4533
  }
3650
4534
  }
3651
- if (await this.isConditionMatch(flag, effectiveBucketingValue, condition, effectiveProperties, evaluationContext)) {
4535
+ const matchResult = await this.isConditionMatch(flag, effectiveBucketingValue, condition, effectiveProperties, evaluationContext);
4536
+ if (matchResult === "match") {
3652
4537
  const variantOverride = condition.variant;
3653
4538
  const flagVariants = flagFilters.multivariate?.variants || [];
3654
4539
  result = variantOverride && flagVariants.some((variant) => variant.key === variantOverride) ? variantOverride : await this.getMatchingVariant(flag, effectiveBucketingValue) || true;
3655
4540
  break;
3656
4541
  }
4542
+ if (earlyExitEnabled && matchResult === "out_of_rollout_bound")
4543
+ return false;
3657
4544
  } catch (e) {
3658
4545
  if (e instanceof RequiresServerEvaluation)
3659
4546
  throw e;
@@ -3677,16 +4564,20 @@ class FeatureFlagsPoller {
3677
4564
  for (const prop of condition.properties) {
3678
4565
  const propertyType = prop.type;
3679
4566
  let matches = false;
3680
- matches = propertyType === "cohort" ? await matchCohort(prop, properties, this.cohorts, this.debugMode, (depProp) => this.evaluateFlagDependency(depProp, properties, evaluationContext)) : propertyType === "flag" ? await this.evaluateFlagDependency(prop, properties, evaluationContext) : matchProperty(prop, properties, warnFunction);
4567
+ if (propertyType === "cohort") {
4568
+ const inCohort = await matchCohort(prop, properties, this.cohorts, this.debugMode, (depProp) => this.evaluateFlagDependency(depProp, properties, evaluationContext));
4569
+ matches = prop.operator === "not_in" ? !inCohort : inCohort;
4570
+ } else
4571
+ matches = propertyType === "flag" ? await this.evaluateFlagDependency(prop, properties, evaluationContext) : matchProperty(prop, properties, warnFunction);
3681
4572
  if (!matches)
3682
- return false;
4573
+ return "no_match";
3683
4574
  }
3684
4575
  if (rolloutPercentage == undefined)
3685
- return true;
4576
+ return "match";
3686
4577
  }
3687
4578
  if (rolloutPercentage != null && await _hash(flag.key, bucketingValue) > rolloutPercentage / 100)
3688
- return false;
3689
- return true;
4579
+ return "out_of_rollout_bound";
4580
+ return "match";
3690
4581
  }
3691
4582
  async getMatchingVariant(flag, bucketingValue) {
3692
4583
  const hashValue = await _hash(flag.key, bucketingValue, "variant");
@@ -3717,6 +4608,7 @@ class FeatureFlagsPoller {
3717
4608
  this.groupTypeMapping = flagData.groupTypeMapping;
3718
4609
  this.cohorts = flagData.cohorts;
3719
4610
  this.loadedSuccessfullyOnce = true;
4611
+ this.onMinimalFlagCalledEvents?.(flagData.minimalFlagCalledEvents === true);
3720
4612
  }
3721
4613
  warnAboutExperienceContinuityFlags(flags) {
3722
4614
  if (this.strictLocalEvaluation)
@@ -3780,7 +4672,6 @@ class FeatureFlagsPoller {
3780
4672
  clearTimeout(this.poller);
3781
4673
  this.poller = undefined;
3782
4674
  }
3783
- this.poller = setTimeout(() => this.loadFeatureFlags(true), this.getPollingInterval());
3784
4675
  try {
3785
4676
  let shouldFetch = true;
3786
4677
  if (this.cacheProvider)
@@ -3808,17 +4699,18 @@ class FeatureFlagsPoller {
3808
4699
  return;
3809
4700
  case 401:
3810
4701
  this.beginBackoff();
3811
- throw new ClientError(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);
4702
+ 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`);
3812
4703
  case 402:
3813
4704
  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");
3814
4705
  this.featureFlags = [];
3815
4706
  this.featureFlagsByKey = {};
3816
4707
  this.groupTypeMapping = {};
3817
4708
  this.cohorts = {};
4709
+ this.onMinimalFlagCalledEvents?.(false);
3818
4710
  return;
3819
4711
  case 403:
3820
4712
  this.beginBackoff();
3821
- throw new ClientError(`Your personal API 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 personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);
4713
+ 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`);
3822
4714
  case 429:
3823
4715
  this.beginBackoff();
3824
4716
  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`);
@@ -3830,7 +4722,8 @@ class FeatureFlagsPoller {
3830
4722
  const flagData = {
3831
4723
  flags: responseJson.flags ?? [],
3832
4724
  groupTypeMapping: responseJson.group_type_mapping || {},
3833
- cohorts: responseJson.cohorts || {}
4725
+ cohorts: responseJson.cohorts || {},
4726
+ minimalFlagCalledEvents: responseJson.minimal_flag_called_events === true
3834
4727
  };
3835
4728
  this.updateFlagState(flagData);
3836
4729
  this.flagDefinitionsLoadedAt = Date.now();
@@ -3851,6 +4744,9 @@ class FeatureFlagsPoller {
3851
4744
  } catch (err) {
3852
4745
  if (err instanceof ClientError)
3853
4746
  this.onError?.(err);
4747
+ } finally {
4748
+ if (!this.pollerStopped)
4749
+ this.poller = setTimeout(() => this.loadFeatureFlags(true), this.getPollingInterval());
3854
4750
  }
3855
4751
  }
3856
4752
  getPersonalApiKeyRequestOptions(method = "GET", etag) {
@@ -3866,7 +4762,7 @@ class FeatureFlagsPoller {
3866
4762
  headers
3867
4763
  };
3868
4764
  }
3869
- _requestFeatureFlagDefinitions() {
4765
+ async _requestFeatureFlagDefinitions() {
3870
4766
  const url = `${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`;
3871
4767
  const options = this.getPersonalApiKeyRequestOptions("GET", this.flagsEtag);
3872
4768
  let abortTimeout = null;
@@ -3877,23 +4773,49 @@ class FeatureFlagsPoller {
3877
4773
  }, this.timeout);
3878
4774
  options.signal = controller.signal;
3879
4775
  }
4776
+ const clearAbortTimeout = () => clearTimeout(abortTimeout);
3880
4777
  try {
3881
4778
  const fetch1 = this.fetch;
3882
- return fetch1(url, options);
3883
- } finally {
3884
- clearTimeout(abortTimeout);
4779
+ const res = await fetch1(url, options);
4780
+ if (res.status !== 200) {
4781
+ clearAbortTimeout();
4782
+ return res;
4783
+ }
4784
+ return {
4785
+ status: res.status,
4786
+ headers: res.headers,
4787
+ body: res.body,
4788
+ text: async () => {
4789
+ try {
4790
+ return await res.text();
4791
+ } finally {
4792
+ clearAbortTimeout();
4793
+ }
4794
+ },
4795
+ json: async () => {
4796
+ try {
4797
+ return await res.json();
4798
+ } finally {
4799
+ clearAbortTimeout();
4800
+ }
4801
+ }
4802
+ };
4803
+ } catch (err) {
4804
+ clearAbortTimeout();
4805
+ throw err;
3885
4806
  }
3886
4807
  }
3887
4808
  async stopPoller(timeoutMs = 30000) {
4809
+ this.pollerStopped = true;
3888
4810
  clearTimeout(this.poller);
4811
+ this.poller = undefined;
3889
4812
  if (this.cacheProvider)
3890
4813
  try {
3891
4814
  const shutdownResult = this.cacheProvider.shutdown();
3892
4815
  if (shutdownResult instanceof Promise)
3893
- await Promise.race([
3894
- shutdownResult,
3895
- new Promise((_, reject) => setTimeout(() => reject(new Error(`Cache shutdown timeout after ${timeoutMs}ms`)), timeoutMs))
3896
- ]);
4816
+ await raceWithTimeout(shutdownResult, timeoutMs, () => {
4817
+ throw new Error(`Cache shutdown timeout after ${timeoutMs}ms`);
4818
+ });
3897
4819
  } catch (err) {
3898
4820
  this.onError?.(new Error(`Error during cache shutdown: ${err}`));
3899
4821
  }
@@ -3921,21 +4843,21 @@ function matchProperty(property, propertyValues, warnFunction) {
3921
4843
  warnFunction(`Property ${key} cannot have a value of null/undefined with the ${operator} operator`);
3922
4844
  return false;
3923
4845
  }
3924
- function computeExactMatch(value2, overrideValue2) {
3925
- if (Array.isArray(value2))
3926
- return value2.map((val) => String(val).toLowerCase()).includes(String(overrideValue2).toLowerCase());
3927
- return String(value2).toLowerCase() === String(overrideValue2).toLowerCase();
4846
+ function computeExactMatch(value, overrideValue) {
4847
+ if (Array.isArray(value))
4848
+ return value.map((val) => String(val).toLowerCase()).includes(String(overrideValue).toLowerCase());
4849
+ return String(value).toLowerCase() === String(overrideValue).toLowerCase();
3928
4850
  }
3929
- function compare(lhs, rhs, operator2) {
3930
- if (operator2 === "gt")
4851
+ function compare(lhs, rhs, operator) {
4852
+ if (operator === "gt")
3931
4853
  return lhs > rhs;
3932
- if (operator2 === "gte")
4854
+ if (operator === "gte")
3933
4855
  return lhs >= rhs;
3934
- if (operator2 === "lt")
4856
+ if (operator === "lt")
3935
4857
  return lhs < rhs;
3936
- if (operator2 === "lte")
4858
+ if (operator === "lte")
3937
4859
  return lhs <= rhs;
3938
- throw new Error(`Invalid operator: ${operator2}`);
4860
+ throw new Error(`Invalid operator: ${operator}`);
3939
4861
  }
3940
4862
  switch (operator) {
3941
4863
  case "exact":
@@ -3948,6 +4870,14 @@ function matchProperty(property, propertyValues, warnFunction) {
3948
4870
  return String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
3949
4871
  case "not_icontains":
3950
4872
  return !String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
4873
+ case "starts_with":
4874
+ return String(overrideValue).toLowerCase().startsWith(String(value).toLowerCase());
4875
+ case "not_starts_with":
4876
+ return !String(overrideValue).toLowerCase().startsWith(String(value).toLowerCase());
4877
+ case "ends_with":
4878
+ return String(overrideValue).toLowerCase().endsWith(String(value).toLowerCase());
4879
+ case "not_ends_with":
4880
+ return !String(overrideValue).toLowerCase().endsWith(String(value).toLowerCase());
3951
4881
  case "regex":
3952
4882
  return isValidRegex(String(value)) && String(overrideValue).match(String(value)) !== null;
3953
4883
  case "not_regex":
@@ -4274,19 +5204,75 @@ function relativeDateParseForFeatureFlagMatching(value) {
4274
5204
  }
4275
5205
  }
4276
5206
 
4277
- // ../../../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/error-tracking/autocapture.mjs
5207
+ // ../../../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/error-tracking/autocapture.mjs
5208
+ var UNHANDLED_REJECTION_OPTION_NAMES = [
5209
+ "--unhandled-rejections",
5210
+ "--unhandled_rejections"
5211
+ ];
5212
+ var UNHANDLED_REJECTION_MODES = new Set([
5213
+ "throw",
5214
+ "strict",
5215
+ "warn",
5216
+ "warn-with-error-code",
5217
+ "none"
5218
+ ]);
5219
+ var STARTUP_EXEC_ARGV = [
5220
+ ...globalThis.process?.execArgv ?? []
5221
+ ];
5222
+ var STARTUP_NODE_OPTIONS = globalThis.process?.env?.NODE_OPTIONS;
5223
+ function splitNodeOptions(nodeOptions) {
5224
+ const args = [];
5225
+ let current = "";
5226
+ let isInString = false;
5227
+ for (let index = 0;index < nodeOptions.length; index++) {
5228
+ const character = nodeOptions[index];
5229
+ if (character === "\\" && isInString && index + 1 < nodeOptions.length)
5230
+ current += nodeOptions[++index];
5231
+ else if (character !== " " || isInString)
5232
+ if (character === '"')
5233
+ isInString = !isInString;
5234
+ else
5235
+ current += character;
5236
+ else if (current) {
5237
+ args.push(current);
5238
+ current = "";
5239
+ }
5240
+ }
5241
+ if (current)
5242
+ args.push(current);
5243
+ return args;
5244
+ }
5245
+ function findUnhandledRejectionMode(args) {
5246
+ let mode;
5247
+ for (let index = 0;index < args.length; index++) {
5248
+ const argument = args[index];
5249
+ const optionName = UNHANDLED_REJECTION_OPTION_NAMES.find((name) => argument === name || argument.startsWith(`${name}=`));
5250
+ if (!optionName)
5251
+ continue;
5252
+ const value = argument === optionName ? args[++index] : argument.slice(optionName.length + 1);
5253
+ if (UNHANDLED_REJECTION_MODES.has(value))
5254
+ mode = value;
5255
+ }
5256
+ return mode;
5257
+ }
5258
+ function getUnhandledRejectionMode(execArgv = STARTUP_EXEC_ARGV, nodeOptions = STARTUP_NODE_OPTIONS) {
5259
+ return findUnhandledRejectionMode(execArgv) ?? findUnhandledRejectionMode(splitNodeOptions(nodeOptions ?? "")) ?? "throw";
5260
+ }
5261
+ var STARTUP_UNHANDLED_REJECTION_MODE = getUnhandledRejectionMode();
5262
+ function captureUncaughtException(captureFn, error, origin) {
5263
+ captureFn(error, {
5264
+ mechanism: {
5265
+ type: origin === "unhandledRejection" ? "onunhandledrejection" : "onuncaughtexception",
5266
+ handled: false
5267
+ }
5268
+ });
5269
+ }
4278
5270
  function makeUncaughtExceptionHandler(captureFn, onFatalFn) {
4279
5271
  let calledFatalError = false;
4280
- return Object.assign((error) => {
5272
+ return Object.assign((error, origin) => {
4281
5273
  const userProvidedListenersCount = global.process.listeners("uncaughtException").filter((listener) => listener.name !== "domainUncaughtExceptionClear" && listener._posthogErrorHandler !== true).length;
4282
- const processWouldExit = userProvidedListenersCount === 0;
4283
- captureFn(error, {
4284
- mechanism: {
4285
- type: "onuncaughtexception",
4286
- handled: false
4287
- }
4288
- });
4289
- if (!calledFatalError && processWouldExit) {
5274
+ captureUncaughtException(captureFn, error, origin);
5275
+ if (!calledFatalError && userProvidedListenersCount === 0) {
4290
5276
  calledFatalError = true;
4291
5277
  onFatalFn(error);
4292
5278
  }
@@ -4294,29 +5280,38 @@ function makeUncaughtExceptionHandler(captureFn, onFatalFn) {
4294
5280
  _posthogErrorHandler: true
4295
5281
  });
4296
5282
  }
4297
- function addUncaughtExceptionListener(captureFn, onFatalFn) {
4298
- globalThis.process?.on("uncaughtException", makeUncaughtExceptionHandler(captureFn, onFatalFn));
5283
+ function addUncaughtExceptionListener(captureFn, onFatalFn, mode = STARTUP_UNHANDLED_REJECTION_MODE) {
5284
+ const process2 = globalThis.process;
5285
+ if (!process2)
5286
+ return;
5287
+ if (mode === "strict")
5288
+ return void process2.on("uncaughtExceptionMonitor", (error, origin) => captureUncaughtException(captureFn, error, origin));
5289
+ process2.on("uncaughtException", makeUncaughtExceptionHandler(captureFn, onFatalFn));
4299
5290
  }
4300
- function addUnhandledRejectionListener(captureFn) {
4301
- globalThis.process?.on("unhandledRejection", (reason) => captureFn(reason, {
4302
- mechanism: {
4303
- type: "onunhandledrejection",
4304
- handled: false
4305
- }
4306
- }));
5291
+ function addUnhandledRejectionListener(captureFn, mode = STARTUP_UNHANDLED_REJECTION_MODE) {
5292
+ const process2 = globalThis.process;
5293
+ if (!process2 || mode === "throw" || mode === "strict" || mode === "warn-with-error-code")
5294
+ return;
5295
+ process2.on("unhandledRejection", (reason) => {
5296
+ captureFn(reason, {
5297
+ mechanism: {
5298
+ type: "onunhandledrejection",
5299
+ handled: false
5300
+ }
5301
+ });
5302
+ });
4307
5303
  }
4308
5304
 
4309
- // ../../../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/error-tracking/index.mjs
5305
+ // ../../../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/error-tracking/index.mjs
4310
5306
  var SHUTDOWN_TIMEOUT = 2000;
4311
5307
 
4312
- class ErrorTracking {
5308
+ class error_tracking_ErrorTracking {
4313
5309
  constructor(client, options, _logger) {
4314
5310
  this.client = client;
4315
5311
  this._exceptionAutocaptureEnabled = options.enableExceptionAutocapture || false;
4316
5312
  this._logger = _logger;
4317
5313
  this._rateLimiter = new BucketedRateLimiter({
4318
- refillRate: 1,
4319
- bucketSize: 10,
5314
+ ...resolveExceptionRateLimiterConfig(options),
4320
5315
  refillInterval: 1e4,
4321
5316
  _logger: this._logger
4322
5317
  });
@@ -4331,6 +5326,9 @@ class ErrorTracking {
4331
5326
  };
4332
5327
  const exceptionProperties = builder.buildFromUnknown(error, hint);
4333
5328
  exceptionProperties.$exception_list = await builder.modifyFrames(exceptionProperties.$exception_list);
5329
+ const injectedReleaseId = getInjectedReleaseId();
5330
+ if (injectedReleaseId)
5331
+ properties.$release_id = injectedReleaseId;
4334
5332
  return {
4335
5333
  event: "$exception",
4336
5334
  distinctId,
@@ -4349,8 +5347,8 @@ class ErrorTracking {
4349
5347
  }
4350
5348
  onException(exception, hint) {
4351
5349
  this.client.addPendingPromise((async () => {
4352
- if (!ErrorTracking.isPreviouslyCapturedError(exception)) {
4353
- const eventMessage = await ErrorTracking.buildEventMessage(this.client.getErrorPropertiesBuilder(), exception, hint);
5350
+ if (!error_tracking_ErrorTracking.isPreviouslyCapturedError(exception)) {
5351
+ const eventMessage = await error_tracking_ErrorTracking.buildEventMessage(this.client.getErrorPropertiesBuilder(), exception, hint);
4354
5352
  const exceptionProperties = eventMessage.properties;
4355
5353
  const exceptionType = exceptionProperties?.$exception_list[0]?.type ?? "Exception";
4356
5354
  const isRateLimited = this._rateLimiter.consumeRateLimit(exceptionType);
@@ -4358,14 +5356,14 @@ class ErrorTracking {
4358
5356
  return void this._logger.info("Skipping exception capture because of client rate limiting.", {
4359
5357
  exception: exceptionType
4360
5358
  });
4361
- return this.client.capture(eventMessage);
5359
+ return this.client._capturePreparedEvent(eventMessage, false);
4362
5360
  }
4363
5361
  })());
4364
5362
  }
4365
5363
  async onFatalError(exception) {
4366
5364
  console.error(exception);
4367
5365
  await this.client.shutdown(SHUTDOWN_TIMEOUT);
4368
- process.exit(1);
5366
+ globalThis.process.exit(1);
4369
5367
  }
4370
5368
  isEnabled() {
4371
5369
  return !this.client.isDisabled && this._exceptionAutocaptureEnabled;
@@ -4375,7 +5373,7 @@ class ErrorTracking {
4375
5373
  }
4376
5374
  }
4377
5375
 
4378
- // ../../../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/storage-memory.mjs
5376
+ // ../../../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/storage-memory.mjs
4379
5377
  class PostHogMemoryStorage {
4380
5378
  getProperty(key) {
4381
5379
  return this._memoryStorage[key];
@@ -4388,7 +5386,452 @@ class PostHogMemoryStorage {
4388
5386
  }
4389
5387
  }
4390
5388
 
4391
- // ../../../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/client.mjs
5389
+ // ../../../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/capture-v1/config.mjs
5390
+ function isCaptureMode(value) {
5391
+ return value === "v0" || value === "v1";
5392
+ }
5393
+ function resolveCaptureMode() {
5394
+ const envMode = typeof process != "undefined" ? process.env?.POSTHOG_CAPTURE_MODE : undefined;
5395
+ return isCaptureMode(envMode) ? envMode : "v0";
5396
+ }
5397
+
5398
+ // ../../../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/capture-v1/routing.mjs
5399
+ var AI_EVENT_PREFIX = "$ai_";
5400
+ var ANALYTICS_ROUTE = "analytics";
5401
+ var AI_ROUTE = "ai";
5402
+ function isLegacyOnlyEvent(message) {
5403
+ return typeof message.event == "string" && message.event.startsWith(AI_EVENT_PREFIX);
5404
+ }
5405
+
5406
+ // ../../../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/capture-v1/errors.mjs
5407
+ class CaptureV1Error extends Error {
5408
+ constructor({ requestId, drops, retryExhausted, cause }) {
5409
+ super(CaptureV1Error.buildMessage(requestId, drops, retryExhausted, cause)), this.name = "CaptureV1Error";
5410
+ this.requestId = requestId;
5411
+ this.drops = drops;
5412
+ this.retryExhausted = retryExhausted;
5413
+ this.cause = cause;
5414
+ }
5415
+ static buildMessage(requestId, drops, retryExhausted, cause) {
5416
+ let message = `Capture V1 batch ${requestId} did not fully deliver: ${drops.length} dropped, ${retryExhausted.length} undelivered`;
5417
+ if (cause instanceof Error)
5418
+ message += ` (${cause.message})`;
5419
+ return message;
5420
+ }
5421
+ }
5422
+
5423
+ // ../../../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/capture-v1/transform.mjs
5424
+ function coerceBool(value) {
5425
+ if (typeof value == "boolean")
5426
+ return value;
5427
+ if (typeof value == "number")
5428
+ return value !== 0;
5429
+ if (typeof value == "string") {
5430
+ const normalized = value.trim().toLowerCase();
5431
+ if (normalized === "true" || normalized === "1")
5432
+ return true;
5433
+ if (normalized === "false" || normalized === "0")
5434
+ return false;
5435
+ }
5436
+ }
5437
+ function coerceString(value) {
5438
+ return typeof value == "string" ? value : undefined;
5439
+ }
5440
+ var OPTION_SENTINELS = [
5441
+ {
5442
+ property: "$cookieless_mode",
5443
+ optionKey: "cookieless_mode",
5444
+ coerce: coerceBool
5445
+ },
5446
+ {
5447
+ property: "$ignore_sent_at",
5448
+ optionKey: "disable_skew_correction",
5449
+ coerce: coerceBool
5450
+ },
5451
+ {
5452
+ property: "$process_person_profile",
5453
+ optionKey: "process_person_profile",
5454
+ coerce: coerceBool
5455
+ },
5456
+ {
5457
+ property: "$product_tour_id",
5458
+ optionKey: "product_tour_id",
5459
+ coerce: coerceString
5460
+ }
5461
+ ];
5462
+ var TOPLEVEL_SENTINELS = [
5463
+ {
5464
+ property: "$session_id",
5465
+ field: "session_id"
5466
+ },
5467
+ {
5468
+ property: "$window_id",
5469
+ field: "window_id"
5470
+ }
5471
+ ];
5472
+ function isRecord2(value) {
5473
+ return typeof value == "object" && value !== null && !Array.isArray(value);
5474
+ }
5475
+ function toRfc3339(timestamp) {
5476
+ if (typeof timestamp == "string") {
5477
+ const asDate = new Date(timestamp);
5478
+ if (Number.isNaN(asDate.getTime()))
5479
+ return new Date().toISOString();
5480
+ const normalized = asDate.toISOString();
5481
+ const fractionalSeconds = timestamp.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];
5482
+ return fractionalSeconds && fractionalSeconds.length > 3 ? normalized.replace(/\.\d{3}Z$/, `.${fractionalSeconds}Z`) : normalized;
5483
+ }
5484
+ if (timestamp instanceof Date)
5485
+ return Number.isNaN(timestamp.getTime()) ? new Date().toISOString() : timestamp.toISOString();
5486
+ const asDate = timestamp == null ? new Date : new Date(timestamp);
5487
+ return Number.isNaN(asDate.getTime()) ? new Date().toISOString() : asDate.toISOString();
5488
+ }
5489
+ function relocateInto(properties, key, value) {
5490
+ if (value !== undefined && !(key in properties))
5491
+ properties[key] = value;
5492
+ }
5493
+ function buildV1Event(message) {
5494
+ const sourceProperties = isRecord2(message.properties) ? message.properties : {};
5495
+ const properties = {
5496
+ ...sourceProperties
5497
+ };
5498
+ const options = {};
5499
+ for (const { property, optionKey, coerce } of OPTION_SENTINELS)
5500
+ if (property in properties) {
5501
+ const coerced = coerce(properties[property]);
5502
+ if (coerced !== undefined)
5503
+ options[optionKey] = coerced;
5504
+ delete properties[property];
5505
+ }
5506
+ const topLevel = {};
5507
+ for (const { property, field } of TOPLEVEL_SENTINELS)
5508
+ if (property in properties) {
5509
+ const value = properties[property];
5510
+ if (typeof value == "string")
5511
+ topLevel[field] = value;
5512
+ delete properties[property];
5513
+ }
5514
+ delete properties.$lib;
5515
+ delete properties.$lib_version;
5516
+ relocateInto(properties, "$set", message.$set);
5517
+ relocateInto(properties, "$set_once", message.$set_once);
5518
+ return {
5519
+ event: String(message.event ?? ""),
5520
+ uuid: String(message.uuid ?? ""),
5521
+ distinct_id: String(message.distinct_id ?? ""),
5522
+ timestamp: toRfc3339(message.timestamp),
5523
+ ...topLevel,
5524
+ options,
5525
+ properties
5526
+ };
5527
+ }
5528
+ function buildV1Batch(messages, { createdAt, historicalMigration }) {
5529
+ const batch = {
5530
+ created_at: createdAt,
5531
+ batch: messages.map(buildV1Event)
5532
+ };
5533
+ if (historicalMigration)
5534
+ batch.historical_migration = true;
5535
+ return batch;
5536
+ }
5537
+
5538
+ // ../../../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/capture-v1/sender.mjs
5539
+ var V1_ANALYTICS_PATH = "/i/v1/analytics/events";
5540
+ var DEFAULT_MAX_BACKOFF_MS = 30000;
5541
+ var RETRYABLE_STATUSES = new Set([
5542
+ 408,
5543
+ 500,
5544
+ 502,
5545
+ 503,
5546
+ 504
5547
+ ]);
5548
+
5549
+ class V1CaptureSender {
5550
+ constructor(config, hooks) {
5551
+ this.config = config;
5552
+ this.maxBackoffMs = config.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS;
5553
+ this.fetchFn = hooks.fetch;
5554
+ this.onError = hooks.onError;
5555
+ this.now = hooks.now ?? Date.now;
5556
+ this.sleep = hooks.sleep ?? ((ms) => new Promise((resolve) => safeSetTimeout(resolve, ms)));
5557
+ this.generateRequestId = hooks.generateRequestId ?? uuidv7;
5558
+ this.compress = hooks.compress ?? gzipCompress;
5559
+ }
5560
+ async sendV1Batch(messages) {
5561
+ if (messages.length === 0)
5562
+ return;
5563
+ const requestId = this.generateRequestId();
5564
+ const createdAt = new Date(this.now()).toISOString();
5565
+ const { batch } = buildV1Batch(messages, {
5566
+ createdAt,
5567
+ historicalMigration: this.config.historicalMigration
5568
+ });
5569
+ const url = `${this.config.host}${V1_ANALYTICS_PATH}`;
5570
+ const drops = [];
5571
+ let pending = batch;
5572
+ const maxAttempts = Math.max(1, this.config.maxAttempts);
5573
+ for (let attempt = 1;attempt <= maxAttempts; attempt++) {
5574
+ const isLastAttempt = attempt === maxAttempts;
5575
+ const payload = safeJsonStringify({
5576
+ created_at: createdAt,
5577
+ ...this.config.historicalMigration ? {
5578
+ historical_migration: true
5579
+ } : {},
5580
+ batch: pending
5581
+ });
5582
+ let captureAttempt;
5583
+ let retryDelayMs;
5584
+ try {
5585
+ captureAttempt = await this.sendOnce(url, payload, attempt, requestId);
5586
+ const { response, signal } = captureAttempt;
5587
+ const { status } = response;
5588
+ if (status < 200 || status >= 300)
5589
+ if (!isLastAttempt && RETRYABLE_STATUSES.has(status)) {
5590
+ const retryAfterMs = this.parseRetryAfter(response);
5591
+ await captureAttempt.waitFor(captureAttempt.cancelBody()).catch(() => {});
5592
+ retryDelayMs = this.backoffDelay(attempt, retryAfterMs);
5593
+ } else {
5594
+ const httpError = await this.buildHttpError(response, status, captureAttempt.waitFor);
5595
+ return this.surfaceBatchFailure(requestId, drops, pending, httpError);
5596
+ }
5597
+ else {
5598
+ let parsed;
5599
+ try {
5600
+ parsed = await captureAttempt.waitFor(this.parseResponse(response));
5601
+ } catch (error) {
5602
+ if (signal.aborted)
5603
+ throw error;
5604
+ return this.surfaceBatchFailure(requestId, drops, pending, new Error(`Capture V1 returned an unparseable ${status} response body`));
5605
+ }
5606
+ const retryable = this.classify(pending, parsed, drops);
5607
+ if (retryable.length === 0)
5608
+ return this.surfacePartialDrops(requestId, drops);
5609
+ if (isLastAttempt)
5610
+ return void this.onError(new CaptureV1Error({
5611
+ requestId,
5612
+ drops,
5613
+ retryExhausted: retryable.map((event) => event.uuid)
5614
+ }));
5615
+ pending = retryable;
5616
+ const retryAfterMs = this.parseRetryAfter(response);
5617
+ retryDelayMs = this.backoffDelay(attempt, retryAfterMs);
5618
+ }
5619
+ } catch (transportError) {
5620
+ if (captureAttempt && !captureAttempt.signal.aborted)
5621
+ throw transportError;
5622
+ if (isLastAttempt)
5623
+ return this.surfaceBatchFailure(requestId, drops, pending, transportError);
5624
+ retryDelayMs = this.backoffDelay(attempt);
5625
+ } finally {
5626
+ captureAttempt?.cleanup();
5627
+ }
5628
+ if (retryDelayMs !== undefined)
5629
+ await this.sleep(retryDelayMs);
5630
+ }
5631
+ }
5632
+ async sendOnce(url, payload, attempt, requestId) {
5633
+ const headers = this.buildHeaders(attempt, requestId);
5634
+ let body = payload;
5635
+ if (this.config.compressionEnabled) {
5636
+ const compressed = await this.compress(payload, this.config.isDebug);
5637
+ if (compressed !== null) {
5638
+ body = compressed;
5639
+ headers["Content-Encoding"] = "gzip";
5640
+ }
5641
+ }
5642
+ const controller = new AbortController;
5643
+ let timeoutPhase = "waiting for response headers";
5644
+ let timer;
5645
+ const deadline = new Promise((_resolve, reject) => {
5646
+ timer = safeSetTimeout(() => {
5647
+ const timeoutError = new Error(`Capture V1 request timed out ${timeoutPhase} after ${this.config.requestTimeoutMs}ms`);
5648
+ timeoutError.name = "AbortError";
5649
+ reject(timeoutError);
5650
+ controller.abort(timeoutError);
5651
+ }, this.config.requestTimeoutMs);
5652
+ });
5653
+ try {
5654
+ const fetchPromise = this.fetchFn(url, {
5655
+ method: "POST",
5656
+ headers,
5657
+ body,
5658
+ signal: controller.signal
5659
+ });
5660
+ let responseAccepted = false;
5661
+ fetchPromise.then((lateResponse) => {
5662
+ if (controller.signal.aborted && !responseAccepted)
5663
+ this.cancelBody(lateResponse);
5664
+ }).catch(() => {});
5665
+ const response = await Promise.race([
5666
+ fetchPromise,
5667
+ deadline
5668
+ ]);
5669
+ responseAccepted = true;
5670
+ timeoutPhase = "while reading the response body";
5671
+ let cleanedUp = false;
5672
+ let cancellation;
5673
+ const cancelBody = () => cancellation ??= this.cancelBody(response);
5674
+ return {
5675
+ response,
5676
+ signal: controller.signal,
5677
+ waitFor: (operation) => Promise.race([
5678
+ operation,
5679
+ deadline
5680
+ ]),
5681
+ cancelBody,
5682
+ cleanup: () => {
5683
+ if (cleanedUp)
5684
+ return;
5685
+ cleanedUp = true;
5686
+ clearTimeout(timer);
5687
+ if (controller.signal.aborted)
5688
+ cancelBody();
5689
+ }
5690
+ };
5691
+ } catch (error) {
5692
+ clearTimeout(timer);
5693
+ throw error;
5694
+ }
5695
+ }
5696
+ buildHeaders(attempt, requestId) {
5697
+ const sdkInfo = `${this.config.libraryId}/${this.config.libraryVersion}`;
5698
+ const headers = {
5699
+ "Content-Type": "application/json",
5700
+ Authorization: `Bearer ${this.config.apiKey}`,
5701
+ "PostHog-Sdk-Info": sdkInfo,
5702
+ "PostHog-Attempt": String(attempt),
5703
+ "PostHog-Request-Id": requestId,
5704
+ "PostHog-Request-Timestamp": new Date(this.now()).toISOString()
5705
+ };
5706
+ if (this.config.userAgent)
5707
+ headers["User-Agent"] = this.config.userAgent;
5708
+ return headers;
5709
+ }
5710
+ classify(pending, parsed, drops) {
5711
+ const results = parsed.results ?? {};
5712
+ const retryable = [];
5713
+ for (const event of pending) {
5714
+ const result = results[event.uuid];
5715
+ if (result) {
5716
+ if (result.result === "drop")
5717
+ drops.push({
5718
+ uuid: event.uuid,
5719
+ details: result.details ?? undefined
5720
+ });
5721
+ else if (result.result === "retry")
5722
+ retryable.push(event);
5723
+ }
5724
+ }
5725
+ return retryable;
5726
+ }
5727
+ backoffDelay(attempt, retryAfterMs) {
5728
+ const exponential = Math.min(this.config.initialRetryDelayMs * 2 ** (attempt - 1), this.maxBackoffMs);
5729
+ if (retryAfterMs === undefined)
5730
+ return exponential;
5731
+ return Math.max(exponential, Math.min(retryAfterMs, this.maxBackoffMs));
5732
+ }
5733
+ parseRetryAfter(response) {
5734
+ const raw = response.headers?.get("Retry-After");
5735
+ if (!raw)
5736
+ return;
5737
+ const trimmed = raw.trim();
5738
+ if (/^\d+$/.test(trimmed)) {
5739
+ const seconds = parseInt(trimmed, 10);
5740
+ return Number.isFinite(seconds) && seconds > 0 ? 1000 * seconds : undefined;
5741
+ }
5742
+ const dateMs = Date.parse(trimmed);
5743
+ if (Number.isNaN(dateMs))
5744
+ return;
5745
+ const delta = dateMs - this.now();
5746
+ return delta > 0 ? delta : undefined;
5747
+ }
5748
+ async parseResponse(response) {
5749
+ const text = await response.text();
5750
+ const parsed = JSON.parse(text);
5751
+ if (typeof parsed != "object" || parsed === null || Array.isArray(parsed))
5752
+ throw new Error("unexpected response shape");
5753
+ const results = parsed.results;
5754
+ if (results !== undefined && (typeof results != "object" || results === null || Array.isArray(results)))
5755
+ throw new Error("unexpected results shape");
5756
+ return {
5757
+ results: results ?? {}
5758
+ };
5759
+ }
5760
+ async buildHttpError(response, status, waitFor) {
5761
+ let bodyText = "";
5762
+ try {
5763
+ bodyText = (await waitFor(response.text())).slice(0, 512);
5764
+ } catch {}
5765
+ const suffix = bodyText ? `: ${bodyText}` : "";
5766
+ return new Error(`Capture V1 request failed with HTTP ${status}${suffix}`);
5767
+ }
5768
+ surfaceBatchFailure(requestId, drops, pending, cause) {
5769
+ this.onError(new CaptureV1Error({
5770
+ requestId,
5771
+ drops,
5772
+ retryExhausted: pending.map((event) => event.uuid),
5773
+ cause
5774
+ }));
5775
+ }
5776
+ surfacePartialDrops(requestId, drops) {
5777
+ if (drops.length > 0)
5778
+ this.onError(new CaptureV1Error({
5779
+ requestId,
5780
+ drops,
5781
+ retryExhausted: []
5782
+ }));
5783
+ }
5784
+ async cancelBody(response) {
5785
+ try {
5786
+ await response.body?.cancel();
5787
+ } catch {}
5788
+ }
5789
+ }
5790
+
5791
+ // ../../../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/ai-capture/routing.mjs
5792
+ var AI_CAPTURE_ROUTE = "ai-capture";
5793
+ var AI_CAPTURE_ENDPOINT_PATH = "/i/v0/ai/batch/";
5794
+ var AI_MAX_EVENT_BYTES = 8388608;
5795
+ var AI_BATCH_TARGET_BYTES = 5242880;
5796
+
5797
+ // ../../../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/ai-capture/batching.mjs
5798
+ var encoder = new TextEncoder;
5799
+ function eventByteSize(message) {
5800
+ return encoder.encode(safeJsonStringify(message)).length;
5801
+ }
5802
+ function partitionAiBatch(messages, maxEventBytes = AI_MAX_EVENT_BYTES, targetBatchBytes = AI_BATCH_TARGET_BYTES) {
5803
+ const batches = [];
5804
+ const dropped = [];
5805
+ let current = [];
5806
+ let currentBytes = 0;
5807
+ for (const message of messages) {
5808
+ if (message === undefined)
5809
+ continue;
5810
+ const bytes = eventByteSize(message);
5811
+ if (bytes > maxEventBytes) {
5812
+ dropped.push({
5813
+ event: typeof message.event == "string" ? message.event : "unknown",
5814
+ bytes
5815
+ });
5816
+ continue;
5817
+ }
5818
+ if (current.length > 0 && currentBytes + bytes > targetBatchBytes) {
5819
+ batches.push(current);
5820
+ current = [];
5821
+ currentBytes = 0;
5822
+ }
5823
+ current.push(message);
5824
+ currentBytes += bytes;
5825
+ }
5826
+ if (current.length > 0)
5827
+ batches.push(current);
5828
+ return {
5829
+ batches,
5830
+ dropped
5831
+ };
5832
+ }
5833
+
5834
+ // ../../../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/client.mjs
4392
5835
  var MINIMUM_POLLING_INTERVAL = 100;
4393
5836
  var THIRTY_SECONDS = 30000;
4394
5837
  var MAX_CACHE_SIZE = 50000;
@@ -4413,6 +5856,12 @@ function normalizeHost(value) {
4413
5856
  const normalizedValue = typeof value == "string" ? value.trim() : "";
4414
5857
  return normalizedValue || DEFAULT_NODE_HOST;
4415
5858
  }
5859
+ function normalizeUnsetPersonProperties(value) {
5860
+ const propertyNames = Array.isArray(value) ? value : [
5861
+ value
5862
+ ];
5863
+ return propertyNames.filter((propertyName) => typeof propertyName == "string" && propertyName.trim().length > 0);
5864
+ }
4416
5865
  function buildFlagEventProperties(flagValues) {
4417
5866
  if (!flagValues)
4418
5867
  return {};
@@ -4430,11 +5879,15 @@ class PostHogBackendClient extends PostHogCoreStateless {
4430
5879
  const normalizedApiKey = normalizeApiKey(apiKey);
4431
5880
  const normalizedOptions = {
4432
5881
  ...options,
5882
+ maxQueueSize: options.maxQueueSize ?? 1e4,
5883
+ flushInterval: options.flushInterval ?? 5000,
4433
5884
  host: normalizeHost(options.host),
4434
- personalApiKey: normalizePersonalApiKey(options.personalApiKey)
5885
+ personalApiKey: normalizePersonalApiKey(options.secretKey ?? options.personalApiKey)
4435
5886
  };
4436
- super(normalizedApiKey, normalizedOptions), this._memoryStorage = new PostHogMemoryStorage;
5887
+ super(normalizedApiKey, normalizedOptions), this._memoryStorage = new PostHogMemoryStorage, this._aiCaptureRouteActive = false, this._minimalFlagCalledEvents = false;
4437
5888
  this.options = normalizedOptions;
5889
+ this.captureMode = resolveCaptureMode();
5890
+ this.enableFullAiCapture = normalizedOptions.enableFullAiCapture === true;
4438
5891
  this.context = this.initializeContext();
4439
5892
  this.options.featureFlagsPollingInterval = typeof normalizedOptions.featureFlagsPollingInterval == "number" ? Math.max(normalizedOptions.featureFlagsPollingInterval, MINIMUM_POLLING_INTERVAL) : THIRTY_SECONDS;
4440
5893
  if (typeof normalizedOptions.waitUntilDebounceMs == "number")
@@ -4459,21 +5912,24 @@ class PostHogBackendClient extends PostHogCoreStateless {
4459
5912
  onLoad: (count) => {
4460
5913
  this._events.emit("localEvaluationFlagsLoaded", count);
4461
5914
  },
5915
+ onMinimalFlagCalledEvents: (enabled) => {
5916
+ this._minimalFlagCalledEvents = enabled;
5917
+ },
4462
5918
  customHeaders: this.getCustomHeaders(),
4463
5919
  cacheProvider: normalizedOptions.flagDefinitionCacheProvider,
4464
5920
  strictLocalEvaluation: normalizedOptions.strictLocalEvaluation
4465
5921
  });
4466
5922
  }
4467
- this.errorTracking = new ErrorTracking(this, normalizedOptions, this._logger);
5923
+ this.errorTracking = new error_tracking_ErrorTracking(this, normalizedOptions, this._logger);
4468
5924
  this.distinctIdHasSentFlagCalls = {};
4469
5925
  this.maxCacheSize = normalizedOptions.maxCacheSize || MAX_CACHE_SIZE;
4470
5926
  }
4471
- enqueue(type, message, options) {
4472
- super.enqueue(type, message, options);
5927
+ enqueue(type, message, options, explicitRoute) {
5928
+ super.enqueue(type, message, options, explicitRoute);
4473
5929
  this.scheduleDebouncedFlush();
4474
5930
  }
4475
5931
  async flush() {
4476
- const flushPromise = super.flush();
5932
+ const flushPromise = this.flushWithPendingPromises();
4477
5933
  const waitUntil = this.options.waitUntil;
4478
5934
  if (waitUntil && !this._waitUntilCycle)
4479
5935
  try {
@@ -4526,7 +5982,7 @@ class PostHogBackendClient extends PostHogCoreStateless {
4526
5982
  async resolveWaitUntilFlush() {
4527
5983
  const resolve = this._consumeWaitUntilCycle();
4528
5984
  try {
4529
- await super.flush();
5985
+ await this.flushWithPendingPromises();
4530
5986
  } catch {} finally {
4531
5987
  resolve?.();
4532
5988
  }
@@ -4540,12 +5996,103 @@ class PostHogBackendClient extends PostHogCoreStateless {
4540
5996
  fetch(url, options) {
4541
5997
  return this.options.fetch ? this.options.fetch(url, options) : fetch(url, options);
4542
5998
  }
5999
+ getQueueRouteKey(message) {
6000
+ return this.captureMode === "v1" && isLegacyOnlyEvent(message) ? AI_ROUTE : ANALYTICS_ROUTE;
6001
+ }
6002
+ persistedQueueKeyForRoute(route) {
6003
+ if (route === AI_CAPTURE_ROUTE)
6004
+ return types_PostHogPersistedProperty.AiCaptureQueue;
6005
+ return route === AI_ROUTE ? types_PostHogPersistedProperty.AiQueue : types_PostHogPersistedProperty.Queue;
6006
+ }
6007
+ getActiveQueueRoutes() {
6008
+ const routes = this.captureMode === "v1" ? [
6009
+ ANALYTICS_ROUTE,
6010
+ AI_ROUTE
6011
+ ] : [
6012
+ ANALYTICS_ROUTE
6013
+ ];
6014
+ if (this._aiCaptureRouteActive)
6015
+ routes.push(AI_CAPTURE_ROUTE);
6016
+ return routes;
6017
+ }
6018
+ getBatchEndpointPath(route) {
6019
+ return route === AI_CAPTURE_ROUTE ? AI_CAPTURE_ENDPOINT_PATH : super.getBatchEndpointPath(route);
6020
+ }
6021
+ async sendBatch(batchMessages, retryOptions, route = ANALYTICS_ROUTE) {
6022
+ if (route === AI_CAPTURE_ROUTE)
6023
+ return this.sendAiCaptureBatch(batchMessages, retryOptions);
6024
+ if (this.captureMode !== "v1" || route === AI_ROUTE)
6025
+ return super.sendBatch(batchMessages, retryOptions, route);
6026
+ const v1Events = batchMessages.filter((message) => message !== undefined);
6027
+ await this.getV1Sender().sendV1Batch(v1Events);
6028
+ }
6029
+ async sendAiCaptureBatch(batchMessages, retryOptions) {
6030
+ const { batches, dropped } = partitionAiBatch(batchMessages);
6031
+ for (const { event, bytes } of dropped) {
6032
+ const message = `Event ${event} (${bytes} bytes) exceeds the ${AI_MAX_EVENT_BYTES / 1048576}MiB limit for ${AI_CAPTURE_ENDPOINT_PATH}, dropping.`;
6033
+ this._logger.error(message);
6034
+ this._events.emit("error", new Error(message));
6035
+ }
6036
+ for (const batch of batches)
6037
+ await this.sendAiSubBatch(batch, retryOptions);
6038
+ }
6039
+ async sendAiSubBatch(batch, retryOptions) {
6040
+ try {
6041
+ await super.sendBatch(batch, retryOptions, AI_CAPTURE_ROUTE);
6042
+ } catch (err) {
6043
+ if (!isPostHogFetchContentTooLargeError(err))
6044
+ throw err;
6045
+ if (batch.length === 1) {
6046
+ const [event] = batch;
6047
+ const eventName = typeof event.event == "string" ? event.event : "unknown";
6048
+ const message = `Event ${eventName} (${eventByteSize(event)} bytes) was rejected with 413 by ${AI_CAPTURE_ENDPOINT_PATH} on its own, dropping.`;
6049
+ this._logger.error(message);
6050
+ this._events.emit("error", new Error(message));
6051
+ return;
6052
+ }
6053
+ const mid = Math.ceil(batch.length / 2);
6054
+ await this.sendAiSubBatch(batch.slice(0, mid), retryOptions);
6055
+ await this.sendAiSubBatch(batch.slice(mid), retryOptions);
6056
+ }
6057
+ }
6058
+ getV1Sender() {
6059
+ if (!this._v1Sender)
6060
+ this._v1Sender = new V1CaptureSender({
6061
+ host: this.host,
6062
+ apiKey: this.apiKey,
6063
+ libraryId: this.getLibraryId(),
6064
+ libraryVersion: this.getLibraryVersion(),
6065
+ userAgent: this.getCustomUserAgent() || undefined,
6066
+ historicalMigration: this.historicalMigration,
6067
+ compressionEnabled: !this.disableCompression,
6068
+ requestTimeoutMs: this.requestTimeout,
6069
+ maxAttempts: (this.options.fetchRetryCount ?? 3) + 1,
6070
+ initialRetryDelayMs: this.options.fetchRetryDelay ?? 3000,
6071
+ isDebug: this.isDebug
6072
+ }, {
6073
+ fetch: (url, fetchOptions) => this.fetch(url, fetchOptions),
6074
+ onError: (error) => this._events.emit("error", error),
6075
+ compress: (payload) => this.compressPayload(payload)
6076
+ });
6077
+ return this._v1Sender;
6078
+ }
4543
6079
  getLibraryVersion() {
4544
6080
  return version;
4545
6081
  }
6082
+ get metrics() {
6083
+ if (!this._metrics)
6084
+ this._metrics = new PostHogMetrics(this, resolveMetricsConfig(this.options.metrics), this._logger);
6085
+ return this._metrics;
6086
+ }
4546
6087
  getCustomUserAgent() {
4547
6088
  return `${this.getLibraryId()}/${this.getLibraryVersion()}`;
4548
6089
  }
6090
+ getCommonEventProperties() {
6091
+ const commonProperties = super.getCommonEventProperties();
6092
+ if (this.options.isServer ?? true)
6093
+ commonProperties.$is_server = true;
6094
+ return commonProperties;
6095
+ }
4549
6096
  enable() {
4550
6097
  return super.optIn();
4551
6098
  }
@@ -4556,33 +6103,69 @@ class PostHogBackendClient extends PostHogCoreStateless {
4556
6103
  super.debug(enabled);
4557
6104
  this.featureFlagsPoller?.debug(enabled);
4558
6105
  }
4559
- capture(props) {
6106
+ _warnIfInvalidCapture(props, stringArgumentWarning, exceptionCaptureWarning) {
4560
6107
  if (typeof props == "string")
4561
- this._logger.warn("Called capture() with a string as the first argument when an object was expected.");
6108
+ this._logger.warn(stringArgumentWarning);
4562
6109
  if (props.event === "$exception" && !props._originatedFromCaptureException)
4563
- 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.");
4564
- this.addPendingPromise(this.prepareEventMessage(props).then(({ distinctId, event, properties, options }) => super.captureStateless(distinctId, event, properties, {
4565
- timestamp: options.timestamp,
4566
- disableGeoip: options.disableGeoip,
4567
- uuid: options.uuid
4568
- })).catch((err) => {
6110
+ this._logger.warn(exceptionCaptureWarning);
6111
+ }
6112
+ _sendPreparedEvent(type, props, immediate, prepareOptions, explicitRoute) {
6113
+ return this.addPendingPromise(this._prepareEventMessage(props, prepareOptions).then(({ distinctId, event, properties, options }) => {
6114
+ const captureOptions = {
6115
+ timestamp: options.timestamp,
6116
+ disableGeoip: options.disableGeoip,
6117
+ uuid: options.uuid
6118
+ };
6119
+ const message = {
6120
+ distinctId,
6121
+ event,
6122
+ properties: {
6123
+ ...properties,
6124
+ ...this.getCommonEventProperties()
6125
+ }
6126
+ };
6127
+ return immediate ? this.sendImmediate(type, message, captureOptions, explicitRoute) : this.enqueue(type, message, captureOptions, explicitRoute);
6128
+ }).catch((err) => {
4569
6129
  if (err)
4570
6130
  console.error(err);
4571
6131
  }));
4572
6132
  }
6133
+ _capturePreparedEvent(props, immediate) {
6134
+ return this._sendPreparedEvent("capture", props, immediate);
6135
+ }
6136
+ capture(props) {
6137
+ 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.");
6138
+ this._capturePreparedEvent(props, false);
6139
+ }
4573
6140
  async captureImmediate(props) {
4574
- if (typeof props == "string")
4575
- this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected.");
4576
- if (props.event === "$exception" && !props._originatedFromCaptureException)
4577
- this._logger.warn("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.");
4578
- return this.addPendingPromise(this.prepareEventMessage(props).then(({ distinctId, event, properties, options }) => super.captureStatelessImmediate(distinctId, event, properties, {
4579
- timestamp: options.timestamp,
4580
- disableGeoip: options.disableGeoip,
4581
- uuid: options.uuid
4582
- })).catch((err) => {
4583
- if (err)
4584
- console.error(err);
4585
- }));
6141
+ 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.");
6142
+ return this._capturePreparedEvent(props, true);
6143
+ }
6144
+ captureAi(props) {
6145
+ if (this.disabled)
6146
+ return;
6147
+ const uuid = getEventUuid(props.uuid, uuidv7);
6148
+ this._sendPreparedAiEvent({
6149
+ ...props,
6150
+ uuid
6151
+ }, false);
6152
+ return uuid;
6153
+ }
6154
+ async captureAiImmediate(props) {
6155
+ if (this.disabled)
6156
+ return;
6157
+ const uuid = getEventUuid(props.uuid, uuidv7);
6158
+ await this._sendPreparedAiEvent({
6159
+ ...props,
6160
+ uuid
6161
+ }, true);
6162
+ return uuid;
6163
+ }
6164
+ _sendPreparedAiEvent(props, immediate) {
6165
+ if (typeof props?.event == "string" && !props.event.startsWith("$ai_"))
6166
+ this._logger.debug(`captureAi called with non-AI event ${props.event}; routing it to the AI endpoint anyway.`);
6167
+ this._aiCaptureRouteActive = true;
6168
+ return this._sendPreparedEvent("capture", props, immediate, undefined, AI_CAPTURE_ROUTE);
4586
6169
  }
4587
6170
  identify({ distinctId, properties = {}, disableGeoip }) {
4588
6171
  const { $set, $set_once, $anon_distinct_id, ...rest } = properties;
@@ -4593,8 +6176,13 @@ class PostHogBackendClient extends PostHogCoreStateless {
4593
6176
  $set_once: setOnceProps,
4594
6177
  $anon_distinct_id: $anon_distinct_id ?? undefined
4595
6178
  };
4596
- super.identifyStateless(distinctId, eventProperties, {
6179
+ this._sendPreparedEvent("identify", {
6180
+ distinctId,
6181
+ event: "$identify",
6182
+ properties: eventProperties,
4597
6183
  disableGeoip
6184
+ }, false, {
6185
+ includeContextProperties: false
4598
6186
  });
4599
6187
  }
4600
6188
  async identifyImmediate({ distinctId, properties = {}, disableGeoip }) {
@@ -4606,18 +6194,65 @@ class PostHogBackendClient extends PostHogCoreStateless {
4606
6194
  $set_once: setOnceProps,
4607
6195
  $anon_distinct_id: $anon_distinct_id ?? undefined
4608
6196
  };
4609
- await super.identifyStatelessImmediate(distinctId, eventProperties, {
6197
+ await this._sendPreparedEvent("identify", {
6198
+ distinctId,
6199
+ event: "$identify",
6200
+ properties: eventProperties,
4610
6201
  disableGeoip
6202
+ }, true, {
6203
+ includeContextProperties: false
6204
+ });
6205
+ }
6206
+ setPersonProperties({ distinctId, properties = {}, propertiesOnce = {} }) {
6207
+ if (Object.keys(properties).length === 0 && Object.keys(propertiesOnce).length === 0)
6208
+ return;
6209
+ const eventProperties = {};
6210
+ if (Object.keys(properties).length > 0)
6211
+ eventProperties.$set = properties;
6212
+ if (Object.keys(propertiesOnce).length > 0)
6213
+ eventProperties.$set_once = propertiesOnce;
6214
+ this.capture({
6215
+ distinctId,
6216
+ event: "$set",
6217
+ properties: eventProperties
6218
+ });
6219
+ }
6220
+ unsetPersonProperties({ distinctId, properties }) {
6221
+ const propertyNames = normalizeUnsetPersonProperties(properties);
6222
+ if (propertyNames.length === 0)
6223
+ return;
6224
+ this.capture({
6225
+ distinctId,
6226
+ event: "$set",
6227
+ properties: {
6228
+ $unset: propertyNames
6229
+ }
4611
6230
  });
4612
6231
  }
4613
6232
  alias(data) {
4614
- super.aliasStateless(data.alias, data.distinctId, undefined, {
6233
+ this._sendPreparedEvent("alias", {
6234
+ distinctId: data.distinctId,
6235
+ event: "$create_alias",
6236
+ properties: {
6237
+ distinct_id: data.distinctId,
6238
+ alias: data.alias
6239
+ },
4615
6240
  disableGeoip: data.disableGeoip
6241
+ }, false, {
6242
+ includeContextProperties: false
4616
6243
  });
4617
6244
  }
4618
6245
  async aliasImmediate(data) {
4619
- await super.aliasStatelessImmediate(data.alias, data.distinctId, undefined, {
6246
+ await this._sendPreparedEvent("alias", {
6247
+ distinctId: data.distinctId,
6248
+ event: "$create_alias",
6249
+ properties: {
6250
+ distinct_id: data.distinctId,
6251
+ alias: data.alias
6252
+ },
4620
6253
  disableGeoip: data.disableGeoip
6254
+ }, true, {
6255
+ includeContextProperties: false
4621
6256
  });
4622
6257
  }
4623
6258
  isLocalEvaluationReady() {
@@ -4672,7 +6307,7 @@ class PostHogBackendClient extends PostHogCoreStateless {
4672
6307
  const adjustedProperties = this.addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties);
4673
6308
  personProperties = adjustedProperties.allPersonProperties;
4674
6309
  groupProperties = adjustedProperties.allGroupProperties;
4675
- const evaluationContext = this.createFeatureFlagEvaluationContext(distinctId, groups, personProperties, groupProperties);
6310
+ const evaluationContext = this.createFeatureFlagEvaluationContext(distinctId, groups, this.personPropertiesForLocalEvaluation(distinctId, personProperties), groupProperties);
4676
6311
  if (onlyEvaluateLocally == undefined)
4677
6312
  onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;
4678
6313
  let result;
@@ -4683,6 +6318,7 @@ class PostHogBackendClient extends PostHogCoreStateless {
4683
6318
  let flagId;
4684
6319
  let flagVersion;
4685
6320
  let flagReason;
6321
+ let flagHasExperiment;
4686
6322
  const localEvaluationEnabled = this.featureFlagsPoller !== undefined;
4687
6323
  if (localEvaluationEnabled) {
4688
6324
  await this.featureFlagsPoller?.loadFeatureFlags();
@@ -4697,6 +6333,7 @@ class PostHogBackendClient extends PostHogCoreStateless {
4697
6333
  const value = localResult.value;
4698
6334
  flagId = flag.id;
4699
6335
  flagReason = "Evaluated locally";
6336
+ flagHasExperiment = flag.has_experiment;
4700
6337
  result = {
4701
6338
  key,
4702
6339
  enabled: value !== false,
@@ -4712,12 +6349,13 @@ class PostHogBackendClient extends PostHogCoreStateless {
4712
6349
  }
4713
6350
  }
4714
6351
  if (!flagWasLocallyEvaluated && !onlyEvaluateLocally) {
4715
- const flagsResponse = await super.getFeatureFlagDetailsStateless(evaluationContext.distinctId, evaluationContext.groups, evaluationContext.personProperties, evaluationContext.groupProperties, disableGeoip, [
6352
+ const flagsResponse = await super.getFeatureFlagDetailsStateless(evaluationContext.distinctId, evaluationContext.groups, personProperties, groupProperties, disableGeoip, [
4716
6353
  key
4717
6354
  ]);
4718
6355
  if (flagsResponse === undefined)
4719
6356
  featureFlagError = FeatureFlagError2.UNKNOWN_ERROR;
4720
6357
  else {
6358
+ this._minimalFlagCalledEvents = flagsResponse.minimalFlagCalledEvents === true;
4721
6359
  requestId = flagsResponse.requestId;
4722
6360
  evaluatedAt = flagsResponse.evaluatedAt;
4723
6361
  const errors = [];
@@ -4732,6 +6370,7 @@ class PostHogBackendClient extends PostHogCoreStateless {
4732
6370
  flagId = flagDetail.metadata?.id;
4733
6371
  flagVersion = flagDetail.metadata?.version;
4734
6372
  flagReason = flagDetail.reason?.description ?? flagDetail.reason?.code;
6373
+ flagHasExperiment = flagDetail.metadata?.has_experiment;
4735
6374
  let parsedPayload;
4736
6375
  if (flagDetail.metadata?.payload !== undefined)
4737
6376
  try {
@@ -4742,7 +6381,7 @@ class PostHogBackendClient extends PostHogCoreStateless {
4742
6381
  result = {
4743
6382
  key,
4744
6383
  enabled: flagDetail.enabled,
4745
- variant: flagDetail.variant,
6384
+ variant: flagDetail.variant ?? undefined,
4746
6385
  payload: parsedPayload
4747
6386
  };
4748
6387
  }
@@ -4763,6 +6402,8 @@ class PostHogBackendClient extends PostHogCoreStateless {
4763
6402
  $feature_flag_request_id: requestId,
4764
6403
  $feature_flag_evaluated_at: flagWasLocallyEvaluated ? Date.now() : evaluatedAt
4765
6404
  };
6405
+ if (flagHasExperiment !== undefined)
6406
+ properties.$feature_flag_has_experiment = flagHasExperiment;
4766
6407
  if (flagWasLocallyEvaluated && this.featureFlagsPoller) {
4767
6408
  const flagDefinitionsLoadedAt = this.featureFlagsPoller.getFlagDefinitionsLoadedAt();
4768
6409
  if (flagDefinitionsLoadedAt !== undefined)
@@ -4877,7 +6518,7 @@ class PostHogBackendClient extends PostHogCoreStateless {
4877
6518
  const adjustedProperties = this.addLocalPersonAndGroupProperties(resolvedDistinctId, groups, personProperties, groupProperties);
4878
6519
  personProperties = adjustedProperties.allPersonProperties;
4879
6520
  groupProperties = adjustedProperties.allGroupProperties;
4880
- const evaluationContext = this.createFeatureFlagEvaluationContext(resolvedDistinctId, groups, personProperties, groupProperties);
6521
+ const evaluationContext = this.createFeatureFlagEvaluationContext(resolvedDistinctId, groups, this.personPropertiesForLocalEvaluation(resolvedDistinctId, personProperties), groupProperties);
4881
6522
  if (onlyEvaluateLocally == undefined)
4882
6523
  onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;
4883
6524
  const localEvaluationResult = await this.featureFlagsPoller?.getAllFlagsAndPayloads(evaluationContext, flagKeys);
@@ -4890,7 +6531,7 @@ class PostHogBackendClient extends PostHogCoreStateless {
4890
6531
  fallbackToFlags = localEvaluationResult.fallbackToFlags;
4891
6532
  }
4892
6533
  if (fallbackToFlags && !onlyEvaluateLocally) {
4893
- const remoteEvaluationResult = await super.getFeatureFlagsAndPayloadsStateless(evaluationContext.distinctId, evaluationContext.groups, evaluationContext.personProperties, evaluationContext.groupProperties, disableGeoip, flagKeys);
6534
+ const remoteEvaluationResult = await super.getFeatureFlagsAndPayloadsStateless(evaluationContext.distinctId, evaluationContext.groups, personProperties, groupProperties, disableGeoip, flagKeys);
4894
6535
  featureFlags = {
4895
6536
  ...featureFlags,
4896
6537
  ...remoteEvaluationResult.flags || {}
@@ -4938,9 +6579,10 @@ class PostHogBackendClient extends PostHogCoreStateless {
4938
6579
  const adjustedProperties = this.addLocalPersonAndGroupProperties(resolvedDistinctId, groups, personProperties, groupProperties);
4939
6580
  personProperties = adjustedProperties.allPersonProperties;
4940
6581
  groupProperties = adjustedProperties.allGroupProperties;
4941
- const evaluationContext = this.createFeatureFlagEvaluationContext(resolvedDistinctId, groups, personProperties, groupProperties);
6582
+ const evaluationContext = this.createFeatureFlagEvaluationContext(resolvedDistinctId, groups, this.personPropertiesForLocalEvaluation(resolvedDistinctId, personProperties), groupProperties);
4942
6583
  if (onlyEvaluateLocally == undefined)
4943
6584
  onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;
6585
+ const requestedFlagKeys = flagKeys ? new Set(flagKeys) : undefined;
4944
6586
  const records = {};
4945
6587
  let requestId;
4946
6588
  let evaluatedAt;
@@ -4959,14 +6601,17 @@ class PostHogBackendClient extends PostHogCoreStateless {
4959
6601
  id: flagDef?.id,
4960
6602
  version: undefined,
4961
6603
  reason: "Evaluated locally",
4962
- locallyEvaluated: true
6604
+ locallyEvaluated: true,
6605
+ hasExperiment: flagDef?.has_experiment
4963
6606
  };
4964
6607
  locallyEvaluatedKeys.add(key);
4965
6608
  }
4966
- const fallbackToFlags = localResult ? localResult.fallbackToFlags : true;
6609
+ const requestedFlagMissingLocally = requestedFlagKeys !== undefined && Array.from(requestedFlagKeys).some((key) => this.featureFlagsPoller?.featureFlagsByKey[key] === undefined);
6610
+ const fallbackToFlags = localResult ? localResult.fallbackToFlags || requestedFlagMissingLocally : true;
4967
6611
  if (fallbackToFlags && !onlyEvaluateLocally) {
4968
- const details = await super.getFeatureFlagDetailsStateless(evaluationContext.distinctId, evaluationContext.groups, evaluationContext.personProperties, evaluationContext.groupProperties, disableGeoip, flagKeys);
6612
+ const details = await super.getFeatureFlagDetailsStateless(evaluationContext.distinctId, evaluationContext.groups, personProperties, groupProperties, disableGeoip, flagKeys);
4969
6613
  if (details) {
6614
+ this._minimalFlagCalledEvents = details.minimalFlagCalledEvents === true;
4970
6615
  requestId = details.requestId;
4971
6616
  evaluatedAt = details.evaluatedAt;
4972
6617
  errorsWhileComputing = Boolean(details.errorsWhileComputingFlags);
@@ -4989,7 +6634,8 @@ class PostHogBackendClient extends PostHogCoreStateless {
4989
6634
  id: detail.metadata?.id,
4990
6635
  version: detail.metadata?.version,
4991
6636
  reason: detail.reason?.description ?? detail.reason?.code,
4992
- locallyEvaluated: false
6637
+ locallyEvaluated: false,
6638
+ hasExperiment: detail.metadata?.has_experiment
4993
6639
  };
4994
6640
  }
4995
6641
  }
@@ -5009,7 +6655,8 @@ class PostHogBackendClient extends PostHogCoreStateless {
5009
6655
  id: existing?.id,
5010
6656
  version: existing?.version,
5011
6657
  reason: existing?.reason,
5012
- locallyEvaluated: existing?.locallyEvaluated ?? false
6658
+ locallyEvaluated: existing?.locallyEvaluated ?? false,
6659
+ hasExperiment: existing?.hasExperiment
5013
6660
  };
5014
6661
  }
5015
6662
  if (this._payloadOverrides !== undefined)
@@ -5021,6 +6668,11 @@ class PostHogBackendClient extends PostHogCoreStateless {
5021
6668
  payload
5022
6669
  };
5023
6670
  }
6671
+ if (requestedFlagKeys !== undefined) {
6672
+ for (const key of Object.keys(records))
6673
+ if (!requestedFlagKeys.has(key))
6674
+ delete records[key];
6675
+ }
5024
6676
  return new FeatureFlagEvaluations({
5025
6677
  host: this._getFeatureFlagEvaluationsHost(),
5026
6678
  distinctId: resolvedDistinctId,
@@ -5034,6 +6686,9 @@ class PostHogBackendClient extends PostHogCoreStateless {
5034
6686
  quotaLimited
5035
6687
  });
5036
6688
  }
6689
+ _shouldSendMinimalFlagCalledEvent(event, properties) {
6690
+ return event === "$feature_flag_called" && this._minimalFlagCalledEvents && properties.$feature_flag_has_experiment === false;
6691
+ }
5037
6692
  _captureFlagCalledEventIfNeeded(params) {
5038
6693
  const { distinctId, key, response, groups, disableGeoip, properties } = params;
5039
6694
  const groupSuffix = groups && Object.keys(groups).length > 0 ? `_${JSON.stringify(Object.entries(groups).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0))}` : "";
@@ -5068,9 +6723,32 @@ class PostHogBackendClient extends PostHogCoreStateless {
5068
6723
  return this._featureFlagEvaluationsHost;
5069
6724
  }
5070
6725
  groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip }) {
5071
- super.groupIdentifyStateless(groupType, groupKey, properties, {
6726
+ this._sendPreparedEvent("capture", {
6727
+ distinctId: distinctId || `$${groupType}_${groupKey}`,
6728
+ event: "$groupidentify",
6729
+ properties: {
6730
+ $group_type: groupType,
6731
+ $group_key: groupKey,
6732
+ $group_set: properties || {}
6733
+ },
5072
6734
  disableGeoip
5073
- }, distinctId);
6735
+ }, false, {
6736
+ includeContextProperties: false
6737
+ });
6738
+ }
6739
+ async groupIdentifyImmediate({ groupType, groupKey, properties, distinctId, disableGeoip }) {
6740
+ await this._sendPreparedEvent("capture", {
6741
+ distinctId: distinctId || `$${groupType}_${groupKey}`,
6742
+ event: "$groupidentify",
6743
+ properties: {
6744
+ $group_type: groupType,
6745
+ $group_key: groupKey,
6746
+ $group_set: properties || {}
6747
+ },
6748
+ disableGeoip
6749
+ }, true, {
6750
+ includeContextProperties: false
6751
+ });
5074
6752
  }
5075
6753
  async reloadFeatureFlags() {
5076
6754
  await this.featureFlagsPoller?.loadFeatureFlags(true);
@@ -5142,12 +6820,18 @@ class PostHogBackendClient extends PostHogCoreStateless {
5142
6820
  this.context?.enter(data, options);
5143
6821
  }
5144
6822
  async _shutdown(shutdownTimeoutMs) {
6823
+ const shutdownDeadlineMs = Date.now() + (shutdownTimeoutMs ?? 30000);
5145
6824
  const resolve = this._consumeWaitUntilCycle();
5146
6825
  await this.featureFlagsPoller?.stopPoller(shutdownTimeoutMs);
5147
6826
  this.errorTracking.shutdown();
6827
+ if (this._metrics) {
6828
+ await raceWithTimeout(this._metrics.flush().catch(() => {}), Math.max(0, shutdownDeadlineMs - Date.now()));
6829
+ this._metrics.reset();
6830
+ }
5148
6831
  try {
5149
- return await super._shutdown(shutdownTimeoutMs);
6832
+ return await super._shutdown(Math.max(0, shutdownDeadlineMs - Date.now()));
5150
6833
  } finally {
6834
+ this.distinctIdHasSentFlagCalls = {};
5151
6835
  resolve?.();
5152
6836
  }
5153
6837
  }
@@ -5242,7 +6926,6 @@ class PostHogBackendClient extends PostHogCoreStateless {
5242
6926
  }
5243
6927
  addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties) {
5244
6928
  const allPersonProperties = {
5245
- distinct_id: distinctId,
5246
6929
  ...personProperties || {}
5247
6930
  };
5248
6931
  const allGroupProperties = {};
@@ -5257,6 +6940,12 @@ class PostHogBackendClient extends PostHogCoreStateless {
5257
6940
  allGroupProperties
5258
6941
  };
5259
6942
  }
6943
+ personPropertiesForLocalEvaluation(distinctId, personProperties) {
6944
+ return {
6945
+ distinct_id: distinctId,
6946
+ ...personProperties || {}
6947
+ };
6948
+ }
5260
6949
  createFeatureFlagEvaluationContext(distinctId, groups, personProperties, groupProperties) {
5261
6950
  return {
5262
6951
  distinctId,
@@ -5267,21 +6956,21 @@ class PostHogBackendClient extends PostHogCoreStateless {
5267
6956
  };
5268
6957
  }
5269
6958
  captureException(error, distinctId, additionalProperties, uuid, flags) {
5270
- if (!ErrorTracking.isPreviouslyCapturedError(error)) {
6959
+ if (!error_tracking_ErrorTracking.isPreviouslyCapturedError(error)) {
5271
6960
  const syntheticException = new Error("PostHog syntheticException");
5272
- this.addPendingPromise(ErrorTracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
6961
+ this.addPendingPromise(error_tracking_ErrorTracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
5273
6962
  syntheticException
5274
- }, distinctId, additionalProperties).then((msg) => this.capture({
6963
+ }, distinctId, additionalProperties).then((msg) => this._capturePreparedEvent({
5275
6964
  ...msg,
5276
6965
  uuid,
5277
6966
  flags
5278
- })));
6967
+ }, false)));
5279
6968
  }
5280
6969
  }
5281
6970
  async captureExceptionImmediate(error, distinctId, additionalProperties, flags) {
5282
- if (!ErrorTracking.isPreviouslyCapturedError(error)) {
6971
+ if (!error_tracking_ErrorTracking.isPreviouslyCapturedError(error)) {
5283
6972
  const syntheticException = new Error("PostHog syntheticException");
5284
- return this.addPendingPromise(ErrorTracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
6973
+ return this.addPendingPromise(error_tracking_ErrorTracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
5285
6974
  syntheticException
5286
6975
  }, distinctId, additionalProperties).then((msg) => this.captureImmediate({
5287
6976
  ...msg,
@@ -5290,24 +6979,31 @@ class PostHogBackendClient extends PostHogCoreStateless {
5290
6979
  }
5291
6980
  }
5292
6981
  async prepareEventMessage(props) {
6982
+ return this._prepareEventMessage(props);
6983
+ }
6984
+ async _prepareEventMessage(props, options = {}) {
5293
6985
  const { distinctId, event, properties, groups, flags, sendFeatureFlags, timestamp, disableGeoip, uuid } = props;
5294
6986
  const contextData = this.context?.get();
6987
+ const includeContextProperties = options.includeContextProperties ?? true;
5295
6988
  let mergedDistinctId = distinctId || contextData?.distinctId;
5296
- const mergedProperties = {
6989
+ const mergedProperties = includeContextProperties ? {
5297
6990
  ...this.props,
5298
6991
  ...contextData?.properties || {},
5299
6992
  ...properties || {}
6993
+ } : {
6994
+ ...properties || {}
5300
6995
  };
5301
6996
  if (!mergedDistinctId) {
5302
6997
  mergedDistinctId = uuidv7();
5303
6998
  mergedProperties.$process_person_profile = false;
5304
6999
  }
5305
- if (contextData?.sessionId && !mergedProperties.$session_id)
7000
+ if (includeContextProperties && contextData?.sessionId && !mergedProperties.$session_id)
5306
7001
  mergedProperties.$session_id = contextData.sessionId;
7002
+ const finalProperties = this._shouldSendMinimalFlagCalledEvent(event, mergedProperties) ? minimizeFlagCalledEventProperties(mergedProperties) : mergedProperties;
5307
7003
  const eventMessage = this._runBeforeSend({
5308
7004
  distinctId: mergedDistinctId,
5309
7005
  event,
5310
- properties: mergedProperties,
7006
+ properties: finalProperties,
5311
7007
  groups,
5312
7008
  flags,
5313
7009
  sendFeatureFlags,
@@ -5331,12 +7027,14 @@ class PostHogBackendClient extends PostHogCoreStateless {
5331
7027
  }
5332
7028
  return {};
5333
7029
  }).catch(() => ({})).then((additionalProperties) => {
5334
- const props2 = {
7030
+ const resolvedGroups = eventMessage.groups || groups;
7031
+ return {
5335
7032
  ...additionalProperties,
5336
7033
  ...eventMessage.properties || {},
5337
- $groups: eventMessage.groups || groups
7034
+ ...resolvedGroups !== undefined && Object.keys(resolvedGroups).length > 0 ? {
7035
+ $groups: resolvedGroups
7036
+ } : {}
5338
7037
  };
5339
- return props2;
5340
7038
  });
5341
7039
  if (eventMessage.event === "$pageview" && this.options.__preview_capture_bot_pageviews && typeof eventProperties.$raw_user_agent == "string") {
5342
7040
  if (isBlockedUA(eventProperties.$raw_user_agent, this.options.custom_blocked_useragents || [])) {
@@ -5363,22 +7061,26 @@ class PostHogBackendClient extends PostHogCoreStateless {
5363
7061
  beforeSend
5364
7062
  ];
5365
7063
  let result = eventMessage;
5366
- for (const fn of fns) {
5367
- result = fn(result);
5368
- if (!result) {
5369
- this._logger.info(`Event '${eventMessage.event}' was rejected in beforeSend function`);
7064
+ for (const fn of fns)
7065
+ try {
7066
+ result = fn(result);
7067
+ if (!result) {
7068
+ this._logger.info(`Event '${eventMessage.event}' was rejected in beforeSend function`);
7069
+ return null;
7070
+ }
7071
+ if (!result.properties || Object.keys(result.properties).length === 0) {
7072
+ const message = `Event '${result.event}' has no properties after beforeSend function, this is likely an error.`;
7073
+ this._logger.warn(message);
7074
+ }
7075
+ } catch (error) {
7076
+ this._logger.error(`Error in before_send function for event '${eventMessage.event}':`, error);
5370
7077
  return null;
5371
7078
  }
5372
- if (!result.properties || Object.keys(result.properties).length === 0) {
5373
- const message = `Event '${result.event}' has no properties after beforeSend function, this is likely an error.`;
5374
- this._logger.warn(message);
5375
- }
5376
- }
5377
7079
  return result;
5378
7080
  }
5379
7081
  }
5380
7082
 
5381
- // ../../../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/context/context.mjs
7083
+ // ../../../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/context/context.mjs
5382
7084
  import { AsyncLocalStorage } from "node:async_hooks";
5383
7085
 
5384
7086
  class PostHogContext {
@@ -5409,7 +7111,22 @@ class PostHogContext {
5409
7111
  }
5410
7112
  }
5411
7113
 
5412
- // ../../../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/sentry-integration.mjs
7114
+ // ../../../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/gzip.node.mjs
7115
+ import { gzip } from "node:zlib";
7116
+ import { promisify } from "node:util";
7117
+ var gzipAsync = promisify(gzip);
7118
+ async function gzipCompress2(input, isDebug = true) {
7119
+ try {
7120
+ const compressed = await gzipAsync(input);
7121
+ return new Uint8Array(compressed);
7122
+ } catch (error) {
7123
+ if (isDebug)
7124
+ console.error("Failed to gzip compress data", error);
7125
+ return null;
7126
+ }
7127
+ }
7128
+
7129
+ // ../../../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/sentry-integration.mjs
5413
7130
  var NAME = "posthog-node";
5414
7131
  function createEventProcessor(_posthog, { organization, projectId, prefix, severityAllowList = [
5415
7132
  "error"
@@ -5449,6 +7166,9 @@ function createEventProcessor(_posthog, { organization, projectId, prefix, sever
5449
7166
  $sentry_exception_type: exceptions[0]?.type,
5450
7167
  $sentry_tags: event.tags
5451
7168
  };
7169
+ const injectedReleaseId = getInjectedReleaseId();
7170
+ if (injectedReleaseId)
7171
+ properties.$release_id = injectedReleaseId;
5452
7172
  if (organization && projectId)
5453
7173
  properties["$sentry_url"] = (prefix || "https://sentry.io/organizations/") + organization + "/issues/?project=" + projectId + "&query=" + event.event_id;
5454
7174
  if (sendExceptionsToPostHog)
@@ -5477,29 +7197,42 @@ class PostHogSentryIntegration {
5477
7197
  };
5478
7198
  }
5479
7199
  }
5480
- // ../../../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/entrypoints/index.node.mjs
7200
+ // ../../../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/entrypoints/index.node.mjs
5481
7201
  class PostHog extends PostHogBackendClient {
5482
7202
  getLibraryId() {
5483
7203
  return "posthog-node";
5484
7204
  }
7205
+ compressPayload(payload) {
7206
+ return gzipCompress2(payload, this.isDebug);
7207
+ }
5485
7208
  initializeContext() {
5486
7209
  return new PostHogContext;
5487
7210
  }
5488
7211
  createErrorPropertiesBuilder() {
5489
- return new exports_error_tracking.ErrorPropertiesBuilder([
5490
- new exports_error_tracking.EventCoercer,
5491
- new exports_error_tracking.ErrorCoercer,
5492
- new exports_error_tracking.ObjectCoercer,
5493
- new exports_error_tracking.StringCoercer,
5494
- new exports_error_tracking.PrimitiveCoercer
5495
- ], exports_error_tracking.createStackParser("node:javascript", exports_error_tracking.nodeStackLineParser), [
7212
+ return new ErrorPropertiesBuilder([
7213
+ new EventCoercer,
7214
+ new ErrorCoercer,
7215
+ new ObjectCoercer,
7216
+ new StringCoercer,
7217
+ new PrimitiveCoercer
7218
+ ], createStackParser("node:javascript", nodeStackLineParser), [
5496
7219
  createModulerModifier(),
5497
- addSourceContext,
7220
+ (frames) => addSourceContext(frames, undefined, this._logger),
5498
7221
  createRelativePathModifier()
5499
7222
  ]);
5500
7223
  }
5501
7224
  }
5502
7225
 
7226
+ // ../../../../telemetry-core/src/machine-id.ts
7227
+ import { createHash } from "node:crypto";
7228
+ import os2 from "node:os";
7229
+ function getDefaultTelemetryOsProvider() {
7230
+ return os2;
7231
+ }
7232
+ function getTelemetryDistinctId(machineIdPrefix, osProvider = getDefaultTelemetryOsProvider()) {
7233
+ return createHash("sha256").update(`${machineIdPrefix}${osProvider.hostname()}`).digest("hex");
7234
+ }
7235
+
5503
7236
  // ../../../../telemetry-core/src/posthog-client.ts
5504
7237
  var NO_OP_CLIENT = {
5505
7238
  enabled: false,
@@ -5534,7 +7267,7 @@ function createDefaultPostHogTransport(apiKey, options) {
5534
7267
  }
5535
7268
  function isTelemetryClientEnabled(input) {
5536
7269
  const env = input.env ?? process.env;
5537
- return !shouldDisableTelemetry({ env, productEnvPrefix: input.product.productEnvPrefix }) && getTelemetryApiKey(env, input.product.defaultApiKey).length > 0;
7270
+ return !shouldDisableTelemetry({ env, productEnvPrefix: input.product.productEnvPrefix }) && hasTelemetryApiKey(env, input.product.defaultApiKey);
5538
7271
  }
5539
7272
  function createTelemetryClient(input) {
5540
7273
  if (!isTelemetryClientEnabled(input)) {
@@ -5600,7 +7333,8 @@ function createTransport(input) {
5600
7333
  flushAt: 1,
5601
7334
  flushInterval: 0,
5602
7335
  host: getTelemetryHost(env, input.product.defaultHost),
5603
- disableGeoip: false
7336
+ disableGeoip: input.product.disableGeoip ?? false,
7337
+ ...input.product.transportOptions
5604
7338
  });
5605
7339
  } catch (error) {
5606
7340
  input.diagnostics?.({
@@ -5804,11 +7538,11 @@ function getPostHogDistinctIdForTesting(osProvider) {
5804
7538
  return getTelemetryDistinctId(MACHINE_ID_PREFIX, osProvider);
5805
7539
  }
5806
7540
  export {
5807
- getPostHogDistinctIdForTesting,
5808
- getPostHogDistinctId,
5809
- getComponentVersion,
5810
- createPluginPostHog,
5811
- __createPluginPostHogForTesting,
7541
+ DEFAULT_POSTHOG_API_KEY,
5812
7542
  DEFAULT_POSTHOG_HOST,
5813
- DEFAULT_POSTHOG_API_KEY
7543
+ __createPluginPostHogForTesting,
7544
+ createPluginPostHog,
7545
+ getComponentVersion,
7546
+ getPostHogDistinctId,
7547
+ getPostHogDistinctIdForTesting
5814
7548
  };