oh-my-opencode 5.0.0-beta.3 → 5.0.0-beta.30

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 (583) hide show
  1. package/.agents/command/publish.md +44 -16
  2. package/.agents/skills/publish/SKILL.md +44 -16
  3. package/.agents/skills/senpi-qa/SKILL.md +80 -0
  4. package/.agents/skills/senpi-qa/scripts/resolve-evidence-dir.mjs +65 -0
  5. package/.agents/skills/senpi-qa/scripts/resolve-evidence-dir.test.mjs +171 -0
  6. package/.agents/skills/work-with-pr/SKILL.md +37 -23
  7. package/.opencode/command/publish.md +44 -16
  8. package/.opencode/skills/work-with-pr/SKILL.md +37 -23
  9. package/README.ja.md +25 -21
  10. package/README.ko.md +25 -21
  11. package/README.md +38 -23
  12. package/README.ru.md +24 -20
  13. package/README.zh-cn.md +25 -21
  14. package/dist/agents/atlas/agent.d.ts +0 -1
  15. package/dist/agents/sisyphus/grok-4.d.ts +20 -0
  16. package/dist/agents/sisyphus/index.d.ts +2 -0
  17. package/dist/agents/sisyphus-agent-config.d.ts +6 -0
  18. package/dist/agents/sisyphus-agent-factory.d.ts +1 -1
  19. package/dist/agents/sisyphus-runtime-prompt-reconciler.d.ts +15 -4
  20. package/dist/agents/types.d.ts +2 -2
  21. package/dist/cli/config-manager/parse-opencode-config-file.d.ts +2 -1
  22. package/dist/cli/doctor/checks/system-plugin.d.ts +4 -3
  23. package/dist/cli/fallback-lane-policy.d.ts +1 -0
  24. package/dist/cli/index.js +22572 -20322
  25. package/dist/cli/install-codex/install-codex-test-fixtures.d.ts +1 -1
  26. package/dist/cli/run/on-complete-hook.d.ts +2 -0
  27. package/dist/cli/runtime-commands.d.ts +1 -1
  28. package/dist/cli/worktree-sweep/classify.d.ts +16 -0
  29. package/dist/cli/worktree-sweep/format.d.ts +8 -0
  30. package/dist/cli/worktree-sweep/git.d.ts +19 -0
  31. package/dist/cli/worktree-sweep/index.d.ts +7 -0
  32. package/dist/cli/worktree-sweep/options.d.ts +2 -0
  33. package/dist/cli/worktree-sweep/parse-worktree-list.d.ts +8 -0
  34. package/dist/cli/worktree-sweep/sweep.d.ts +2 -0
  35. package/dist/cli/worktree-sweep/types.d.ts +65 -0
  36. package/dist/cli/worktree-sweep/worktree-sweep.d.ts +2 -0
  37. package/dist/cli-node/index.js +22190 -19917
  38. package/dist/config/schema/commands.d.ts +1 -1
  39. package/dist/config/schema/hooks.d.ts +1 -1
  40. package/dist/config/schema/oh-my-opencode-config.d.ts +4 -1
  41. package/dist/config/schema/ulw-execute.d.ts +5 -0
  42. package/dist/config/validate.d.ts +2 -0
  43. package/dist/create-hooks.d.ts +3 -1
  44. package/dist/features/btw-side/btw-command-draft.d.ts +7 -0
  45. package/dist/features/btw-side/context-injector.d.ts +15 -0
  46. package/dist/features/btw-side/index.d.ts +8 -0
  47. package/dist/features/btw-side/metadata.d.ts +15 -0
  48. package/dist/features/btw-side/parent-context-budget.d.ts +9 -0
  49. package/dist/features/btw-side/server-session-registry.d.ts +8 -0
  50. package/dist/features/btw-side/tui-adoption-cache.d.ts +13 -0
  51. package/dist/features/btw-side/tui-adoption-guard.d.ts +5 -0
  52. package/dist/features/btw-side/tui-controller-types.d.ts +68 -0
  53. package/dist/features/btw-side/tui-controller.d.ts +19 -0
  54. package/dist/features/btw-side/tui-escape-return.d.ts +12 -0
  55. package/dist/features/btw-side/tui-keymap.d.ts +17 -0
  56. package/dist/features/btw-side/tui-parent-validator.d.ts +6 -0
  57. package/dist/features/btw-side/tui-picker-options.d.ts +20 -0
  58. package/dist/features/btw-side/tui-picker.d.ts +9 -0
  59. package/dist/features/btw-side/tui-prompt-queue.d.ts +8 -0
  60. package/dist/features/btw-side/tui-session-bridge.d.ts +11 -0
  61. package/dist/features/btw-side/tui-session-catalog.d.ts +35 -0
  62. package/dist/features/btw-side/tui-side-removal.d.ts +11 -0
  63. package/dist/features/btw-side/tui-side-start.d.ts +9 -0
  64. package/dist/features/btw-side/tui-wiring.d.ts +8 -0
  65. package/dist/features/builtin-commands/templates/ulw-execute.d.ts +1 -0
  66. package/dist/features/builtin-commands/types.d.ts +1 -1
  67. package/dist/features/opengateway-provider/index.d.ts +13 -0
  68. package/dist/features/team-mode/tools/messaging-fallback-wake.d.ts +15 -0
  69. package/dist/hooks/atlas/atlas-hook.d.ts +1 -0
  70. package/dist/hooks/atlas/atlas-lifecycle-store.d.ts +50 -0
  71. package/dist/hooks/atlas/event-handler.d.ts +1 -0
  72. package/dist/hooks/atlas/final-wave-approval-gate.test-support.d.ts +50 -0
  73. package/dist/hooks/atlas/system-reminder-templates.d.ts +0 -1
  74. package/dist/hooks/atlas/tool-execute-before.d.ts +3 -0
  75. package/dist/hooks/atlas/types.d.ts +1 -0
  76. package/dist/hooks/index.d.ts +1 -1
  77. package/dist/hooks/prometheus-md-only/agent-resolution.d.ts +2 -2
  78. package/dist/hooks/runtime-fallback/chat-message-handler.d.ts +2 -0
  79. package/dist/hooks/runtime-fallback/retry-model-payload.d.ts +1 -0
  80. package/dist/hooks/runtime-fallback/runtime-model-settings.d.ts +6 -0
  81. package/dist/hooks/runtime-fallback/session-status-handler.d.ts +1 -1
  82. package/dist/hooks/runtime-fallback/types.d.ts +3 -1
  83. package/dist/hooks/sisyphus-junior-notepad/constants.d.ts +1 -1
  84. package/dist/hooks/todo-continuation-enforcer/types.d.ts +1 -0
  85. package/dist/hooks/{start-work → ulw-execute}/context-info-builder.d.ts +1 -1
  86. package/dist/hooks/{start-work → ulw-execute}/index.d.ts +1 -1
  87. package/dist/hooks/ulw-execute/ulw-execute-hook.d.ts +23 -0
  88. package/dist/index.js +12573 -6957
  89. package/dist/oh-my-opencode.schema.json +15 -2
  90. package/dist/plugin/chat-message/types.d.ts +3 -3
  91. package/dist/plugin/chat-message/ulw-execute-message.d.ts +5 -0
  92. package/dist/plugin/event-session-lifecycle.d.ts +1 -0
  93. package/dist/plugin/hooks/create-core-hooks.d.ts +2 -1
  94. package/dist/plugin/hooks/create-session-hooks.d.ts +2 -2
  95. package/dist/plugin/hooks/create-transform-hooks.d.ts +2 -0
  96. package/dist/plugin/messages-transform.d.ts +1 -0
  97. package/dist/shared/index.d.ts +2 -0
  98. package/dist/shared/legacy-plugin-warning.d.ts +2 -1
  99. package/dist/shared/normalize-sdk-response.d.ts +1 -0
  100. package/dist/shared/plugin-entry-migrator.d.ts +4 -3
  101. package/dist/shared/plugin-entry-shape.d.ts +6 -0
  102. package/dist/shared/runtime-fallback-retry-marker.d.ts +16 -0
  103. package/dist/shared/shell-env.d.ts +1 -1
  104. package/dist/skills/ast-grep/AGENTS.md +51 -0
  105. package/dist/skills/coding-agent-sessions/AGENTS.md +62 -0
  106. package/dist/skills/coding-agent-sessions/SKILL.md +3 -2
  107. package/dist/skills/coding-agent-sessions/references/all-platforms.md +1 -1
  108. package/dist/skills/coding-agent-sessions/references/senpi.md +4 -4
  109. package/dist/skills/coding-agent-sessions/scripts/agent_sessions/pi_family.py +1 -1
  110. package/dist/skills/data-scientist/SKILL.md +99 -239
  111. package/dist/skills/data-scientist/references/execution-surfaces.md +91 -0
  112. package/dist/skills/data-scientist/references/placement.md +74 -0
  113. package/dist/skills/data-scientist/references/polars-lane.md +95 -0
  114. package/dist/skills/data-scientist/references/uv-setup.md +1 -1
  115. package/dist/skills/data-scientist/references/visualization.md +64 -0
  116. package/dist/skills/data-scientist/scripts/ensure-js-deps.sh +28 -0
  117. package/dist/skills/data-scientist/scripts/ensure-py-deps.sh +37 -0
  118. package/dist/skills/debugging/SKILL.md +2 -0
  119. package/dist/skills/debugging/references/methodology/00-setup.md +12 -0
  120. package/dist/skills/debugging/references/methodology/02-investigate.md +21 -0
  121. package/dist/skills/debugging/references/runtimes/go.md +15 -1
  122. package/dist/skills/debugging/references/runtimes/native-binary.md +38 -0
  123. package/dist/skills/debugging/references/runtimes/node.md +25 -0
  124. package/dist/skills/debugging/references/runtimes/python.md +13 -0
  125. package/dist/skills/debugging/references/runtimes/rust.md +41 -0
  126. package/dist/skills/debugging/references/scripts/dap.mjs +267 -0
  127. package/dist/skills/debugging/references/scripts/dap.test.ts +86 -0
  128. package/dist/skills/debugging/references/scripts/fixture-adapter.mjs +59 -0
  129. package/dist/skills/debugging/references/tools/dap.md +103 -0
  130. package/dist/skills/debugging/references/tools/frida.md +193 -0
  131. package/dist/skills/frontend/SKILL.md +11 -7
  132. package/dist/skills/frontend/references/design/_INDEX.md +1 -0
  133. package/dist/skills/frontend/references/design/print-paged-media.md +76 -0
  134. package/dist/skills/frontend/references/design/stylegallery.md +80 -0
  135. package/dist/skills/frontend/references/designpowers/README.md +1 -1
  136. package/dist/skills/frontend/references/designpowers/lane-a-direction.md +1 -1
  137. package/dist/skills/frontend/references/designpowers/lane-b-execution.md +11 -11
  138. package/dist/skills/frontend/references/designpowers/lane-d-memory.md +3 -3
  139. package/dist/skills/frontend/references/designpowers/orchestration.md +1 -1
  140. package/dist/skills/frontend/references/designpowers/routing.md +5 -5
  141. package/dist/skills/review-work/SKILL.md +3 -3
  142. package/dist/skills/ultimate-browsing/ATTRIBUTION.md +37 -10
  143. package/dist/skills/ultimate-browsing/SKILL.md +2 -0
  144. package/dist/skills/ultimate-browsing/engine/AGENTS.md +179 -0
  145. package/dist/skills/ultimate-browsing/engine/templates/package.json +1 -1
  146. package/dist/skills/ultimate-browsing/references/chrome-stealth.md +13 -11
  147. package/dist/skills/{start-work → ulw-execute}/SKILL.md +9 -8
  148. package/dist/skills/ulw-plan/SKILL.md +6 -6
  149. package/dist/skills/ulw-plan/references/full-workflow.md +31 -7
  150. package/dist/skills/ulw-plan/references/intent-clear.md +2 -1
  151. package/dist/skills/ulw-plan/references/intent-unclear.md +5 -5
  152. package/dist/skills/ulw-research/SKILL.md +4 -2
  153. package/dist/skills/visual-qa/AGENTS.md +58 -0
  154. package/dist/skills/visual-qa/SKILL.md +3 -2
  155. package/dist/tools/delegate-task/builtin-categories.d.ts +1 -0
  156. package/dist/tools/delegate-task/builtin-category-definition.d.ts +1 -0
  157. package/dist/tools/delegate-task/tool-description.d.ts +3 -1
  158. package/dist/tools/delegate-task/types.d.ts +3 -0
  159. package/dist/tui.d.ts +12 -0
  160. package/dist/tui.js +11480 -11512
  161. package/package.json +42 -36
  162. package/packages/git-bash-mcp/dist/cli.js +5 -1
  163. package/packages/git-bash-mcp/package.json +1 -1
  164. package/packages/lsp-core/src/index.ts +1 -0
  165. package/packages/lsp-core/src/lsp/client-diagnostics-concurrency.integration.test.ts +44 -0
  166. package/packages/lsp-core/src/lsp/client-diagnostics-freshness.integration.test.ts +0 -28
  167. package/packages/lsp-core/src/lsp/client-wrapper-outside-cwd.test.ts +78 -0
  168. package/packages/lsp-core/src/lsp/client-wrapper.test.ts +66 -13
  169. package/packages/lsp-core/src/lsp/client-wrapper.ts +95 -23
  170. package/packages/lsp-core/src/lsp/client.ts +26 -0
  171. package/packages/lsp-core/src/lsp/connection.ts +16 -0
  172. package/packages/lsp-core/src/lsp/constants.ts +1 -0
  173. package/packages/lsp-core/src/lsp/format-document.test.ts +143 -0
  174. package/packages/lsp-core/src/lsp/format-document.ts +90 -0
  175. package/packages/lsp-core/src/lsp/manager-max-clients.test.ts +151 -0
  176. package/packages/lsp-core/src/lsp/manager.ts +34 -1
  177. package/packages/lsp-core/src/lsp/outside-context-workspace.ts +33 -0
  178. package/packages/lsp-core/src/lsp/server-definitions.ts +29 -0
  179. package/packages/lsp-core/src/lsp/server-installation.test.ts +376 -0
  180. package/packages/lsp-core/src/lsp/server-installation.ts +200 -27
  181. package/packages/lsp-core/src/lsp/server-resolution-local-binary.test.ts +170 -0
  182. package/packages/lsp-core/src/lsp/server-resolution.ts +18 -5
  183. package/packages/lsp-core/src/lsp/transport.ts +9 -0
  184. package/packages/lsp-core/src/lsp/types.ts +8 -0
  185. package/packages/lsp-core/src/lsp/workspace-edit-adversarial.test.ts +20 -1
  186. package/packages/lsp-core/src/lsp/workspace-markers.ts +1 -0
  187. package/packages/lsp-core/src/request-context.test.ts +29 -0
  188. package/packages/lsp-core/src/request-context.ts +1 -1
  189. package/packages/lsp-core/src/tool-surface.test.ts +13 -1
  190. package/packages/lsp-core/src/tools/definitions.ts +14 -0
  191. package/packages/lsp-core/src/tools/diagnostics.ts +3 -3
  192. package/packages/lsp-core/src/tools/format.test.ts +56 -0
  193. package/packages/lsp-core/src/tools/format.ts +56 -0
  194. package/packages/lsp-core/src/tools/index.ts +1 -0
  195. package/packages/lsp-core/src/tools/navigation.ts +4 -2
  196. package/packages/lsp-core/src/tools/rename.ts +4 -2
  197. package/packages/lsp-core/src/tools/symbols.ts +1 -1
  198. package/packages/lsp-core/src/tools/types.ts +10 -0
  199. package/packages/lsp-daemon/dist/cli.js +645 -296
  200. package/packages/lsp-daemon/dist/client.d.ts +10 -0
  201. package/packages/lsp-daemon/dist/client.js +605 -253
  202. package/packages/lsp-daemon/dist/daemon-client.d.ts +1 -0
  203. package/packages/lsp-daemon/dist/daemon-client.js +3 -0
  204. package/packages/lsp-daemon/dist/ensure-daemon.js +1 -0
  205. package/packages/lsp-daemon/dist/index.js +609 -262
  206. package/packages/lsp-daemon/dist/version-reap.js +1 -1
  207. package/packages/lsp-daemon/package.json +1 -1
  208. package/packages/lsp-tools-mcp/dist/cli.js +564 -217
  209. package/packages/lsp-tools-mcp/dist/lsp/manager.js +115 -92
  210. package/packages/lsp-tools-mcp/dist/mcp.js +566 -219
  211. package/packages/lsp-tools-mcp/dist/request-context.js +12 -13
  212. package/packages/lsp-tools-mcp/dist/tools.js +571 -227
  213. package/packages/omo-codex/THIRD-PARTY-NOTICES.md +4 -4
  214. package/packages/omo-codex/plugin/.codex-plugin/plugin.json +4 -4
  215. package/packages/omo-codex/plugin/AGENTS.md +47 -0
  216. package/packages/omo-codex/plugin/README.md +1 -1
  217. package/packages/omo-codex/plugin/components/bootstrap/dist/cli.js +34 -33
  218. package/packages/omo-codex/plugin/components/bootstrap/hooks/hooks.json +1 -1
  219. package/packages/omo-codex/plugin/components/bootstrap/package.json +1 -1
  220. package/packages/omo-codex/plugin/components/bootstrap/src/hook.ts +1 -0
  221. package/packages/omo-codex/plugin/components/codegraph/dist/cli.js +293 -116
  222. package/packages/omo-codex/plugin/components/codegraph/dist/serve.js +245 -84
  223. package/packages/omo-codex/plugin/components/codegraph/package.json +4 -4
  224. package/packages/omo-codex/plugin/components/codegraph/src/mcp-bridge.ts +1 -0
  225. package/packages/omo-codex/plugin/components/codegraph/src/session-start-hook-runtime.ts +1 -0
  226. package/packages/omo-codex/plugin/components/comment-checker/AGENTS.md +9 -0
  227. package/packages/omo-codex/plugin/components/comment-checker/biome.json +2 -2
  228. package/packages/omo-codex/plugin/components/comment-checker/dist/cli.js +2 -1
  229. package/packages/omo-codex/plugin/components/comment-checker/hooks/hooks.json +1 -1
  230. package/packages/omo-codex/plugin/components/comment-checker/package.json +5 -5
  231. package/packages/omo-codex/plugin/components/comment-checker/src/apply-patch.ts +2 -8
  232. package/packages/omo-codex/plugin/components/comment-checker/src/core.ts +1 -2
  233. package/packages/omo-codex/plugin/components/comment-checker/src/request-extractor.ts +1 -1
  234. package/packages/omo-codex/plugin/components/comment-checker/src/runner.ts +1 -0
  235. package/packages/omo-codex/plugin/components/git-bash/AGENTS.md +1 -1
  236. package/packages/omo-codex/plugin/components/git-bash/hooks/hooks.json +2 -2
  237. package/packages/omo-codex/plugin/components/git-bash/package.json +3 -4
  238. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/biome.json +2 -2
  239. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/dist/cli.js +1 -5
  240. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/dist/codex-hook.js +1 -5
  241. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/hooks/hooks.json +1 -1
  242. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/package.json +5 -5
  243. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/src/codex-hook.ts +1 -5
  244. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/test/codex-hook.test.ts +4 -21
  245. package/packages/omo-codex/plugin/components/lsp/AGENTS.md +30 -15
  246. package/packages/omo-codex/plugin/components/lsp/biome.json +2 -2
  247. package/packages/omo-codex/plugin/components/lsp/dist/.omo-runtime-manifest.json +4 -4
  248. package/packages/omo-codex/plugin/components/lsp/dist/cli.js +596 -267
  249. package/packages/omo-codex/plugin/components/lsp/dist/daemon-cli-path.js +1 -1
  250. package/packages/omo-codex/plugin/components/lsp/hooks/hooks.json +2 -2
  251. package/packages/omo-codex/plugin/components/lsp/package.json +5 -5
  252. package/packages/omo-codex/plugin/components/lsp/src/cli.ts +1 -1
  253. package/packages/omo-codex/plugin/components/lsp/src/codex-hook.ts +1 -1
  254. package/packages/omo-codex/plugin/components/lsp/src/daemon-cli-path.ts +1 -5
  255. package/packages/omo-codex/plugin/components/lsp/test/codex-hook-unavailable.test.ts +6 -7
  256. package/packages/omo-codex/plugin/components/lsp/test/codex-hook.test.ts +1 -2
  257. package/packages/omo-codex/plugin/components/lsp/test/package-smoke.test.ts +11 -1
  258. package/packages/omo-codex/plugin/components/rules/AGENTS.md +12 -0
  259. package/packages/omo-codex/plugin/components/rules/biome.json +2 -2
  260. package/packages/omo-codex/plugin/components/rules/dist/cli.js +60 -45
  261. package/packages/omo-codex/plugin/components/rules/hooks/hooks.json +4 -4
  262. package/packages/omo-codex/plugin/components/rules/package.json +7 -7
  263. package/packages/omo-codex/plugin/components/rules/src/config.ts +1 -2
  264. package/packages/omo-codex/plugin/components/rules/src/persistent-cache.ts +1 -2
  265. package/packages/omo-codex/plugin/components/rules/src/post-compact-budget.ts +9 -5
  266. package/packages/omo-codex/plugin/components/rules/src/rules-engine-factory.ts +1 -4
  267. package/packages/omo-codex/plugin/components/rules/src/static-injection.ts +4 -9
  268. package/packages/omo-codex/plugin/components/rules/test/bundled-rules-priority.test.ts +11 -16
  269. package/packages/omo-codex/plugin/components/rules/test/bundled-rules.test.ts +17 -25
  270. package/packages/omo-codex/plugin/components/rules/test/codex-hook-post-compact-budget.test.ts +9 -7
  271. package/packages/omo-codex/plugin/components/rules/test/codex-hook-post-compact-context.test.ts +0 -6
  272. package/packages/omo-codex/plugin/components/rules/test/codex-hook-post-compact-dedup.test.ts +6 -4
  273. package/packages/omo-codex/plugin/components/rules/test/codex-hook-post-compact-directive.test.ts +12 -9
  274. package/packages/omo-codex/plugin/components/rules/test/codex-hook.test.ts +28 -37
  275. package/packages/omo-codex/plugin/components/rules/test/dynamic-target-fingerprints.test.ts +1 -2
  276. package/packages/omo-codex/plugin/components/rules/test/engine.test.ts +7 -4
  277. package/packages/omo-codex/plugin/components/rules/test/finder.test.ts +2 -3
  278. package/packages/omo-codex/plugin/components/rules/test/formatter.test.ts +39 -72
  279. package/packages/omo-codex/plugin/components/rules/test/hephaestus-model-variant.test.ts +1 -2
  280. package/packages/omo-codex/plugin/components/rules/test/hook-output.test.ts +2 -3
  281. package/packages/omo-codex/plugin/components/rules/test/matcher.test.ts +2 -3
  282. package/packages/omo-codex/plugin/components/rules/test/package-smoke.test.ts +1 -1
  283. package/packages/omo-codex/plugin/components/rules/test/parser.test.ts +1 -2
  284. package/packages/omo-codex/plugin/components/rules/test/post-compact-budget.test.ts +5 -6
  285. package/packages/omo-codex/plugin/components/rules/test/rules-engine-consumption.test.ts +3 -6
  286. package/packages/omo-codex/plugin/components/rules/test/scanner.test.ts +1 -2
  287. package/packages/omo-codex/plugin/components/rules/test/sources.test.ts +2 -5
  288. package/packages/omo-codex/plugin/components/rules/test/windows-git-bash-bundled-rule.test.ts +2 -17
  289. package/packages/omo-codex/plugin/components/teammode/hooks/hooks.json +1 -1
  290. package/packages/omo-codex/plugin/components/teammode/package.json +5 -5
  291. package/packages/omo-codex/plugin/components/teammode/test/thread-title-hook.test.ts +3 -9
  292. package/packages/omo-codex/plugin/components/telemetry/AGENTS.md +8 -0
  293. package/packages/omo-codex/plugin/components/telemetry/biome.json +2 -2
  294. package/packages/omo-codex/plugin/components/telemetry/dist/cli.js +2463 -437
  295. package/packages/omo-codex/plugin/components/telemetry/dist/posthog.js +2467 -441
  296. package/packages/omo-codex/plugin/components/telemetry/hooks/hooks.json +1 -1
  297. package/packages/omo-codex/plugin/components/telemetry/package.json +5 -5
  298. package/packages/omo-codex/plugin/components/telemetry/src/codex-hook.ts +1 -4
  299. package/packages/omo-codex/plugin/components/telemetry/src/posthog.ts +4 -14
  300. package/packages/omo-codex/plugin/components/telemetry/src/product-identity.ts +1 -1
  301. package/packages/omo-codex/plugin/components/telemetry/test/diagnostics.test.ts +2 -5
  302. package/packages/omo-codex/plugin/components/ultrawork/AGENTS.md +5 -0
  303. package/packages/omo-codex/plugin/components/ultrawork/biome.json +2 -2
  304. package/packages/omo-codex/plugin/components/ultrawork/directive.md +13 -1
  305. package/packages/omo-codex/plugin/components/ultrawork/hooks/hooks.json +1 -1
  306. package/packages/omo-codex/plugin/components/ultrawork/package.json +5 -5
  307. package/packages/omo-codex/plugin/components/ultrawork/skills/ultrawork/SKILL.md +13 -1
  308. package/packages/omo-codex/plugin/components/ultrawork/skills/ulw-plan/SKILL.md +6 -6
  309. package/packages/omo-codex/plugin/components/ultrawork/skills/ulw-plan/references/full-workflow.md +31 -7
  310. package/packages/omo-codex/plugin/components/ultrawork/skills/ulw-plan/references/intent-clear.md +2 -1
  311. package/packages/omo-codex/plugin/components/ultrawork/skills/ulw-plan/references/intent-unclear.md +5 -5
  312. package/packages/omo-codex/plugin/components/ultrawork/test/codex-hook-trigger-policy.test.ts +9 -1
  313. package/packages/omo-codex/plugin/components/ultrawork/test/codex-hook.test.ts +0 -136
  314. package/packages/omo-codex/plugin/components/ultrawork/test/skill-pointer.test.ts +0 -2
  315. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/AGENTS.md +5 -4
  316. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/NOTICE +1 -1
  317. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/README.md +5 -5
  318. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/biome.json +2 -2
  319. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/directive.md +6 -6
  320. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/dist/cli.js +12 -12
  321. package/packages/omo-codex/plugin/components/ulw-execute-continuation/hooks/hooks.json +28 -0
  322. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/package.json +12 -12
  323. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/boulder-reader.ts +1 -1
  324. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/cli.ts +1 -1
  325. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/codex-hook.ts +3 -3
  326. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/directive.ts +1 -1
  327. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/index.ts +1 -1
  328. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/boulder-reader.test.ts +3 -3
  329. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/cli.test.ts +1 -4
  330. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/codex-hook.test.ts +8 -22
  331. package/packages/omo-codex/plugin/components/ulw-loop/AGENTS.md +16 -0
  332. package/packages/omo-codex/plugin/components/ulw-loop/CHANGELOG.md +1 -1
  333. package/packages/omo-codex/plugin/components/ulw-loop/biome.json +2 -2
  334. package/packages/omo-codex/plugin/components/ulw-loop/directive.md +13 -1
  335. package/packages/omo-codex/plugin/components/ulw-loop/dist/cli-commands.js +5 -1
  336. package/packages/omo-codex/plugin/components/ulw-loop/dist/cli-output.d.ts +2 -1
  337. package/packages/omo-codex/plugin/components/ulw-loop/dist/cli-output.js +11 -1
  338. package/packages/omo-codex/plugin/components/ulw-loop/dist/cli.js +24 -14
  339. package/packages/omo-codex/plugin/components/ulw-loop/dist/codex-goal-snapshot.js +1 -1
  340. package/packages/omo-codex/plugin/components/ulw-loop/dist/paths.js +1 -1
  341. package/packages/omo-codex/plugin/components/ulw-loop/dist/stop-resume-hook.js +3 -3
  342. package/packages/omo-codex/plugin/components/ulw-loop/hooks/hooks.json +4 -4
  343. package/packages/omo-codex/plugin/components/ulw-loop/package.json +5 -5
  344. package/packages/omo-codex/plugin/components/ulw-loop/skills/ulw-loop/SKILL.md +3 -2
  345. package/packages/omo-codex/plugin/components/ulw-loop/skills/ulw-loop/references/define-goal.md +108 -0
  346. package/packages/omo-codex/plugin/components/ulw-loop/skills/ulw-loop/references/full-workflow.md +1 -0
  347. package/packages/omo-codex/plugin/components/ulw-loop/src/cli-commands.ts +5 -1
  348. package/packages/omo-codex/plugin/components/ulw-loop/src/cli-output.ts +13 -1
  349. package/packages/omo-codex/plugin/components/ulw-loop/src/cli.ts +3 -5
  350. package/packages/omo-codex/plugin/components/ulw-loop/src/codex-goal-snapshot.ts +3 -1
  351. package/packages/omo-codex/plugin/components/ulw-loop/src/codex-hook.ts +3 -1
  352. package/packages/omo-codex/plugin/components/ulw-loop/src/paths.ts +1 -1
  353. package/packages/omo-codex/plugin/components/ulw-loop/src/stop-resume-hook.ts +3 -3
  354. package/packages/omo-codex/plugin/components/ulw-loop/test/checkpoint-continuation.test.ts +0 -1
  355. package/packages/omo-codex/plugin/components/ulw-loop/test/cli-create-goals.test.ts +25 -0
  356. package/packages/omo-codex/plugin/components/ulw-loop/test/cli-entrypoint.test.ts +26 -2
  357. package/packages/omo-codex/plugin/components/ulw-loop/test/codex-goal-instruction.test.ts +2 -2
  358. package/packages/omo-codex/plugin/components/ulw-loop/test/codex-goal-snapshot.test.ts +18 -0
  359. package/packages/omo-codex/plugin/components/ulw-loop/test/codex-hook.test.ts +0 -3
  360. package/packages/omo-codex/plugin/components/ulw-loop/test/package-smoke.test.ts +5 -37
  361. package/packages/omo-codex/plugin/components/ulw-loop/test/paths.test.ts +9 -0
  362. package/packages/omo-codex/plugin/components/ulw-loop/test/steering.test.ts +8 -5
  363. package/packages/omo-codex/plugin/components/ulw-loop/test/stop-resume-hook.test.ts +1 -1
  364. package/packages/omo-codex/plugin/components/ulw-loop/test/ultrawork-directive.test.ts +4 -5
  365. package/packages/omo-codex/plugin/components/ulw-loop/vitest.config.ts +1 -0
  366. package/packages/omo-codex/plugin/hooks/post-compact-resetting-git-bash-mcp-reminder.json +1 -1
  367. package/packages/omo-codex/plugin/hooks/post-compact-resetting-lsp-diagnostics-cache.json +1 -1
  368. package/packages/omo-codex/plugin/hooks/post-compact-resetting-project-rule-cache.json +1 -1
  369. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-codegraph-init-guidance.json +1 -1
  370. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-comments.json +1 -1
  371. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-lsp-diagnostics.json +1 -1
  372. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-thread-title-hygiene.json +1 -1
  373. package/packages/omo-codex/plugin/hooks/post-tool-use-matching-project-rules.json +1 -1
  374. package/packages/omo-codex/plugin/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json +1 -1
  375. package/packages/omo-codex/plugin/hooks/pre-tool-use-guarding-ulw-loop-spawns.json +1 -1
  376. package/packages/omo-codex/plugin/hooks/pre-tool-use-recommending-git-bash-mcp.json +1 -1
  377. package/packages/omo-codex/plugin/hooks/session-start-checking-auto-update.json +1 -1
  378. package/packages/omo-codex/plugin/hooks/session-start-checking-bootstrap-provisioning.json +1 -1
  379. package/packages/omo-codex/plugin/hooks/session-start-checking-codegraph-bootstrap.json +1 -1
  380. package/packages/omo-codex/plugin/hooks/session-start-loading-project-rules.json +1 -1
  381. package/packages/omo-codex/plugin/hooks/session-start-recording-session-telemetry.json +1 -1
  382. package/packages/omo-codex/plugin/hooks/stop-checking-ulw-execute-continuation.json +17 -0
  383. package/packages/omo-codex/plugin/hooks/stop-checking-ulw-loop-resume.json +1 -1
  384. package/packages/omo-codex/plugin/hooks/subagent-stop-checking-ulw-execute-continuation.json +17 -0
  385. package/packages/omo-codex/plugin/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json +1 -1
  386. package/packages/omo-codex/plugin/hooks/user-prompt-submit-checking-ultrawork-trigger.json +1 -1
  387. package/packages/omo-codex/plugin/hooks/user-prompt-submit-checking-ulw-loop-steering.json +1 -1
  388. package/packages/omo-codex/plugin/hooks/user-prompt-submit-loading-project-rules.json +1 -1
  389. package/packages/omo-codex/plugin/model-catalog.json +3 -3
  390. package/packages/omo-codex/plugin/package-lock.json +681 -395
  391. package/packages/omo-codex/plugin/package.json +2 -2
  392. package/packages/omo-codex/plugin/scripts/AGENTS.md +40 -0
  393. package/packages/omo-codex/plugin/scripts/auto-update-plan.mjs +1 -1
  394. package/packages/omo-codex/plugin/scripts/migrate-codex-config/catalog.mjs +3 -3
  395. package/packages/omo-codex/plugin/scripts/sync-skills.mjs +11 -11
  396. package/packages/omo-codex/plugin/shared/package.json +3 -4
  397. package/packages/omo-codex/plugin/skills/ast-grep/AGENTS.md +51 -0
  398. package/packages/omo-codex/plugin/skills/coding-agent-sessions/AGENTS.md +62 -0
  399. package/packages/omo-codex/plugin/skills/coding-agent-sessions/SKILL.md +3 -2
  400. package/packages/omo-codex/plugin/skills/coding-agent-sessions/references/all-platforms.md +1 -1
  401. package/packages/omo-codex/plugin/skills/coding-agent-sessions/references/senpi.md +4 -4
  402. package/packages/omo-codex/plugin/skills/coding-agent-sessions/scripts/agent_sessions/pi_family.py +1 -1
  403. package/packages/omo-codex/plugin/skills/data-scientist/SKILL.md +99 -239
  404. package/packages/omo-codex/plugin/skills/data-scientist/references/execution-surfaces.md +91 -0
  405. package/packages/omo-codex/plugin/skills/data-scientist/references/placement.md +74 -0
  406. package/packages/omo-codex/plugin/skills/data-scientist/references/polars-lane.md +95 -0
  407. package/packages/omo-codex/plugin/skills/data-scientist/references/uv-setup.md +1 -1
  408. package/packages/omo-codex/plugin/skills/data-scientist/references/visualization.md +64 -0
  409. package/packages/omo-codex/plugin/skills/data-scientist/scripts/ensure-js-deps.sh +28 -0
  410. package/packages/omo-codex/plugin/skills/data-scientist/scripts/ensure-py-deps.sh +37 -0
  411. package/packages/omo-codex/plugin/skills/debugging/SKILL.md +2 -0
  412. package/packages/omo-codex/plugin/skills/debugging/references/methodology/00-setup.md +12 -0
  413. package/packages/omo-codex/plugin/skills/debugging/references/methodology/02-investigate.md +21 -0
  414. package/packages/omo-codex/plugin/skills/debugging/references/runtimes/go.md +15 -1
  415. package/packages/omo-codex/plugin/skills/debugging/references/runtimes/native-binary.md +38 -0
  416. package/packages/omo-codex/plugin/skills/debugging/references/runtimes/node.md +25 -0
  417. package/packages/omo-codex/plugin/skills/debugging/references/runtimes/python.md +13 -0
  418. package/packages/omo-codex/plugin/skills/debugging/references/runtimes/rust.md +41 -0
  419. package/packages/omo-codex/plugin/skills/debugging/references/scripts/dap.mjs +267 -0
  420. package/packages/omo-codex/plugin/skills/debugging/references/scripts/fixture-adapter.mjs +59 -0
  421. package/packages/omo-codex/plugin/skills/debugging/references/tools/dap.md +103 -0
  422. package/packages/omo-codex/plugin/skills/debugging/references/tools/frida.md +193 -0
  423. package/packages/omo-codex/plugin/skills/frontend/SKILL.md +11 -7
  424. package/packages/omo-codex/plugin/skills/frontend/references/design/_INDEX.md +1 -0
  425. package/packages/omo-codex/plugin/skills/frontend/references/design/print-paged-media.md +76 -0
  426. package/packages/omo-codex/plugin/skills/frontend/references/design/stylegallery.md +80 -0
  427. package/packages/omo-codex/plugin/skills/frontend/references/designpowers/README.md +1 -1
  428. package/packages/omo-codex/plugin/skills/frontend/references/designpowers/lane-a-direction.md +1 -1
  429. package/packages/omo-codex/plugin/skills/frontend/references/designpowers/lane-b-execution.md +11 -11
  430. package/packages/omo-codex/plugin/skills/frontend/references/designpowers/lane-d-memory.md +3 -3
  431. package/packages/omo-codex/plugin/skills/frontend/references/designpowers/orchestration.md +1 -1
  432. package/packages/omo-codex/plugin/skills/frontend/references/designpowers/routing.md +5 -5
  433. package/packages/omo-codex/plugin/skills/review-work/SKILL.md +4 -4
  434. package/packages/omo-codex/plugin/skills/ultimate-browsing/ATTRIBUTION.md +37 -10
  435. package/packages/omo-codex/plugin/skills/ultimate-browsing/SKILL.md +2 -0
  436. package/packages/omo-codex/plugin/skills/ultimate-browsing/engine/AGENTS.md +179 -0
  437. package/packages/omo-codex/plugin/skills/ultimate-browsing/engine/templates/package.json +1 -1
  438. package/packages/omo-codex/plugin/skills/ultimate-browsing/references/chrome-stealth.md +13 -11
  439. package/packages/omo-codex/plugin/skills/ultrawork/SKILL.md +13 -1
  440. package/packages/omo-codex/plugin/skills/{start-work → ulw-execute}/SKILL.md +12 -11
  441. package/packages/omo-codex/plugin/skills/ulw-execute/agents/openai.yaml +2 -0
  442. package/packages/omo-codex/plugin/skills/ulw-loop/SKILL.md +3 -2
  443. package/packages/omo-codex/plugin/skills/ulw-loop/references/define-goal.md +108 -0
  444. package/packages/omo-codex/plugin/skills/ulw-loop/references/full-workflow.md +1 -0
  445. package/packages/omo-codex/plugin/skills/ulw-plan/SKILL.md +6 -6
  446. package/packages/omo-codex/plugin/skills/ulw-plan/references/full-workflow.md +31 -7
  447. package/packages/omo-codex/plugin/skills/ulw-plan/references/intent-clear.md +2 -1
  448. package/packages/omo-codex/plugin/skills/ulw-plan/references/intent-unclear.md +5 -5
  449. package/packages/omo-codex/plugin/skills/ulw-research/SKILL.md +4 -2
  450. package/packages/omo-codex/plugin/skills/visual-qa/AGENTS.md +58 -0
  451. package/packages/omo-codex/plugin/skills/visual-qa/SKILL.md +3 -2
  452. package/packages/omo-codex/plugin/test/AGENTS.md +47 -0
  453. package/packages/omo-codex/plugin/test/aggregate-agents.test.mjs +19 -173
  454. package/packages/omo-codex/plugin/test/aggregate-hooks.test.mjs +8 -28
  455. package/packages/omo-codex/plugin/test/aggregate-manifest.test.mjs +1 -1
  456. package/packages/omo-codex/plugin/test/aggregate-model-catalog.test.mjs +1 -1
  457. package/packages/omo-codex/plugin/test/aggregate-plugin-fixture.mjs +175 -13
  458. package/packages/omo-codex/plugin/test/aggregate.test.mjs +78 -2
  459. package/packages/omo-codex/plugin/test/auto-update-release-notes.test.mjs +19 -33
  460. package/packages/omo-codex/plugin/test/auto-update.test.mjs +2 -2
  461. package/packages/omo-codex/plugin/test/component-bin-names.test.mjs +2 -2
  462. package/packages/omo-codex/plugin/test/component-bundled-cli.test.mjs +1 -1
  463. package/packages/omo-codex/plugin/test/component-hook-contract-cases.mjs +2 -2
  464. package/packages/omo-codex/plugin/test/hook-status-message.test.mjs +4 -4
  465. package/packages/omo-codex/plugin/test/lcx-contribute-bug-fix-template.test.mjs +21 -27
  466. package/packages/omo-codex/plugin/test/migrate-codex-config.test.mjs +8 -8
  467. package/packages/omo-codex/plugin/test/scaffold-plan.test.mjs +0 -36
  468. package/packages/omo-codex/plugin/test/sync-skills-codex-compatibility.test.mjs +101 -0
  469. package/packages/omo-codex/plugin/test/sync-skills-test-support.mjs +12 -12
  470. package/packages/omo-codex/plugin/test/sync-skills.test.mjs +1 -119
  471. package/packages/omo-codex/plugin/test/teammode-archive-ambiguity.test.mjs +0 -40
  472. package/packages/omo-codex/plugin/test/teammode-communication.test.mjs +6 -62
  473. package/packages/omo-codex/plugin/test/teammode-thread-links.test.mjs +3 -36
  474. package/packages/omo-codex/plugin/test/teammode-transport.test.mjs +0 -44
  475. package/packages/omo-codex/plugin/test/teammode-worktree.test.mjs +2 -6
  476. package/packages/omo-codex/plugin/test/ultrawork-skill-pointer.test.mjs +0 -3
  477. package/packages/omo-codex/plugin/test/ulw-plan-review-state-contract.test.mjs +0 -3
  478. package/packages/omo-codex/scripts/AGENTS.md +36 -0
  479. package/packages/omo-codex/scripts/install-config-reasoning.test.mjs +2 -2
  480. package/packages/omo-codex/scripts/install-dist/install-local.mjs +2637 -549
  481. package/packages/omo-codex/scripts/install-lazycodex-version-stamp.test.mjs +7 -2
  482. package/packages/shared-skills/skills/ast-grep/AGENTS.md +51 -0
  483. package/packages/shared-skills/skills/coding-agent-sessions/AGENTS.md +62 -0
  484. package/packages/shared-skills/skills/coding-agent-sessions/SKILL.md +3 -2
  485. package/packages/shared-skills/skills/coding-agent-sessions/references/all-platforms.md +1 -1
  486. package/packages/shared-skills/skills/coding-agent-sessions/references/senpi.md +4 -4
  487. package/packages/shared-skills/skills/coding-agent-sessions/scripts/agent_sessions/pi_family.py +1 -1
  488. package/packages/shared-skills/skills/data-scientist/SKILL.md +99 -239
  489. package/packages/shared-skills/skills/data-scientist/references/execution-surfaces.md +91 -0
  490. package/packages/shared-skills/skills/data-scientist/references/placement.md +74 -0
  491. package/packages/shared-skills/skills/data-scientist/references/polars-lane.md +95 -0
  492. package/packages/shared-skills/skills/data-scientist/references/uv-setup.md +1 -1
  493. package/packages/shared-skills/skills/data-scientist/references/visualization.md +64 -0
  494. package/packages/shared-skills/skills/data-scientist/scripts/ensure-js-deps.sh +28 -0
  495. package/packages/shared-skills/skills/data-scientist/scripts/ensure-py-deps.sh +37 -0
  496. package/packages/shared-skills/skills/debugging/SKILL.md +2 -0
  497. package/packages/shared-skills/skills/debugging/references/methodology/00-setup.md +12 -0
  498. package/packages/shared-skills/skills/debugging/references/methodology/02-investigate.md +21 -0
  499. package/packages/shared-skills/skills/debugging/references/runtimes/go.md +15 -1
  500. package/packages/shared-skills/skills/debugging/references/runtimes/native-binary.md +38 -0
  501. package/packages/shared-skills/skills/debugging/references/runtimes/node.md +25 -0
  502. package/packages/shared-skills/skills/debugging/references/runtimes/python.md +13 -0
  503. package/packages/shared-skills/skills/debugging/references/runtimes/rust.md +41 -0
  504. package/packages/shared-skills/skills/debugging/references/scripts/dap.mjs +267 -0
  505. package/packages/shared-skills/skills/debugging/references/scripts/dap.test.ts +86 -0
  506. package/packages/shared-skills/skills/debugging/references/scripts/fixture-adapter.mjs +59 -0
  507. package/packages/shared-skills/skills/debugging/references/tools/dap.md +103 -0
  508. package/packages/shared-skills/skills/debugging/references/tools/frida.md +193 -0
  509. package/packages/shared-skills/skills/frontend/SKILL.md +11 -7
  510. package/packages/shared-skills/skills/frontend/references/design/_INDEX.md +1 -0
  511. package/packages/shared-skills/skills/frontend/references/design/print-paged-media.md +76 -0
  512. package/packages/shared-skills/skills/frontend/references/design/stylegallery.md +80 -0
  513. package/packages/shared-skills/skills/frontend/references/designpowers/README.md +1 -1
  514. package/packages/shared-skills/skills/frontend/references/designpowers/lane-a-direction.md +1 -1
  515. package/packages/shared-skills/skills/frontend/references/designpowers/lane-b-execution.md +11 -11
  516. package/packages/shared-skills/skills/frontend/references/designpowers/lane-d-memory.md +3 -3
  517. package/packages/shared-skills/skills/frontend/references/designpowers/orchestration.md +1 -1
  518. package/packages/shared-skills/skills/frontend/references/designpowers/routing.md +5 -5
  519. package/packages/shared-skills/skills/review-work/SKILL.md +3 -3
  520. package/packages/shared-skills/skills/ultimate-browsing/ATTRIBUTION.md +37 -10
  521. package/packages/shared-skills/skills/ultimate-browsing/SKILL.md +2 -0
  522. package/packages/shared-skills/skills/ultimate-browsing/engine/AGENTS.md +179 -0
  523. package/packages/shared-skills/skills/ultimate-browsing/engine/templates/package.json +1 -1
  524. package/packages/shared-skills/skills/ultimate-browsing/references/chrome-stealth.md +13 -11
  525. package/packages/shared-skills/skills/{start-work → ulw-execute}/SKILL.md +9 -8
  526. package/packages/shared-skills/skills/ulw-plan/SKILL.md +6 -6
  527. package/packages/shared-skills/skills/ulw-plan/references/full-workflow.md +31 -7
  528. package/packages/shared-skills/skills/ulw-plan/references/intent-clear.md +2 -1
  529. package/packages/shared-skills/skills/ulw-plan/references/intent-unclear.md +5 -5
  530. package/packages/shared-skills/skills/ulw-research/SKILL.md +4 -2
  531. package/packages/shared-skills/skills/visual-qa/AGENTS.md +58 -0
  532. package/packages/shared-skills/skills/visual-qa/SKILL.md +3 -2
  533. package/script/qa/web-terminal-visual-qa.mjs +2 -0
  534. package/script/qa/xterm-live-terminal.mjs +18 -2
  535. package/dist/config/schema/start-work.d.ts +0 -5
  536. package/dist/features/builtin-commands/templates/start-work.d.ts +0 -1
  537. package/dist/hooks/start-work/start-work-hook.d.ts +0 -23
  538. package/dist/plugin/chat-message/start-work-message.d.ts +0 -5
  539. package/dist/skills/data-scientist/references/common-scenarios.md +0 -176
  540. package/dist/skills/data-scientist/references/execution-templates.md +0 -197
  541. package/dist/skills/data-scientist/references/integration-patterns.md +0 -153
  542. package/dist/skills/data-scientist/references/performance-benchmarks.md +0 -37
  543. package/dist/tools/call-omo-agent/background-agent-executor.d.ts +0 -5
  544. package/packages/omo-codex/plugin/components/start-work-continuation/hooks/hooks.json +0 -28
  545. package/packages/omo-codex/plugin/hooks/stop-checking-start-work-continuation.json +0 -17
  546. package/packages/omo-codex/plugin/hooks/subagent-stop-checking-start-work-continuation.json +0 -17
  547. package/packages/omo-codex/plugin/skills/data-scientist/references/common-scenarios.md +0 -176
  548. package/packages/omo-codex/plugin/skills/data-scientist/references/execution-templates.md +0 -197
  549. package/packages/omo-codex/plugin/skills/data-scientist/references/integration-patterns.md +0 -153
  550. package/packages/omo-codex/plugin/skills/data-scientist/references/performance-benchmarks.md +0 -37
  551. package/packages/omo-codex/plugin/skills/start-work/agents/openai.yaml +0 -2
  552. package/packages/omo-codex/plugin/test/aggregate-skills.test.mjs +0 -92
  553. package/packages/omo-codex/plugin/test/sync-skills-orchestration.test.mjs +0 -314
  554. package/packages/omo-codex/plugin/test/ulw-plan-scope-contract.test.mjs +0 -24
  555. package/packages/shared-skills/skills/data-scientist/references/common-scenarios.md +0 -176
  556. package/packages/shared-skills/skills/data-scientist/references/execution-templates.md +0 -197
  557. package/packages/shared-skills/skills/data-scientist/references/integration-patterns.md +0 -153
  558. package/packages/shared-skills/skills/data-scientist/references/performance-benchmarks.md +0 -37
  559. /package/dist/hooks/{start-work → ulw-execute}/context-info-formatters.d.ts +0 -0
  560. /package/dist/hooks/{start-work → ulw-execute}/explicit-plan-context.d.ts +0 -0
  561. /package/dist/hooks/{start-work → ulw-execute}/notepad-scaffold.d.ts +0 -0
  562. /package/dist/hooks/{start-work → ulw-execute}/parse-user-request.d.ts +0 -0
  563. /package/dist/hooks/{start-work → ulw-execute}/plan-discovery-context.d.ts +0 -0
  564. /package/dist/hooks/{start-work → ulw-execute}/plan-selection.d.ts +0 -0
  565. /package/dist/hooks/{start-work → ulw-execute}/session-plan-affinity.d.ts +0 -0
  566. /package/dist/hooks/{start-work → ulw-execute}/work-initializer.d.ts +0 -0
  567. /package/dist/hooks/{start-work → ulw-execute}/worktree-block.d.ts +0 -0
  568. /package/dist/hooks/{start-work → ulw-execute}/worktree-detector.d.ts +0 -0
  569. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/.gitattributes +0 -0
  570. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/CHANGELOG.md +0 -0
  571. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/LICENSE +0 -0
  572. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/plan-checklist.ts +0 -0
  573. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/types.ts +0 -0
  574. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/boulder-completed.json +0 -0
  575. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/boulder-mixed-platforms.json +0 -0
  576. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/boulder-single-codex-work.json +0 -0
  577. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/plan-all-done.md +0 -0
  578. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/plan-scaffold.md +0 -0
  579. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/plan-with-nested-checkboxes.md +0 -0
  580. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/plan-with-unchecked.md +0 -0
  581. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/tsconfig.build.json +0 -0
  582. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/tsconfig.json +0 -0
  583. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/vitest.config.ts +0 -0
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // omo-codex-install:7bc4b0f020f0a1b4448cc75385a7e3c60042e3b270e304d4c1a43a859e81a4c2:83a9041418efce98ae46a8f3601b363e3e6c9f6bc17b39665cb73cb77bc99833
2
+ // omo-codex-install:819e258f7485f9ccdcbb64a54ac0097bf81cd8e2980d7f907017f224b1f99b98:e19da597bc0859c4e499399c6f394680812dba1e8cc6d69a408177a8def55fd7
3
3
  var __defProp = Object.defineProperty;
4
4
  var __returnValue = (v) => v;
5
5
  function __exportSetter(name, newValue) {
@@ -47,9 +47,12 @@ import {
47
47
  fsyncSync,
48
48
  openSync,
49
49
  renameSync,
50
+ rmSync,
50
51
  unlinkSync,
51
52
  writeFileSync
52
53
  } from "node:fs";
54
+ import { randomUUID } from "node:crypto";
55
+ import { dirname as dirname10 } from "node:path";
53
56
  function isToleratedFsyncError(error) {
54
57
  if (!(error instanceof Error))
55
58
  return false;
@@ -65,24 +68,36 @@ function tolerantFsyncSync(fileDescriptor, fsyncImpl) {
65
68
  }
66
69
  }
67
70
  function writeFileAtomically(filePath, content, options = {}) {
68
- const tempPath = `${filePath}.tmp`;
69
- writeFileSync(tempPath, content, "utf-8");
70
- const tempFileDescriptor = openSync(tempPath, "r+");
71
- try {
72
- tolerantFsyncSync(tempFileDescriptor, options.fsyncSync ?? fsyncSync);
73
- } finally {
74
- closeSync(tempFileDescriptor);
75
- }
71
+ const platform = options.platform ?? process.platform;
72
+ const fsyncImpl = options.fsyncSync ?? fsyncSync;
73
+ const tempPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
76
74
  try {
77
- renameSync(tempPath, filePath);
78
- } catch (error) {
79
- const isPermissionError = error instanceof Error && (error.message.includes("EPERM") || error.message.includes("EACCES"));
80
- if ((options.platform ?? process.platform) === "win32" && isPermissionError) {
75
+ writeFileSync(tempPath, content, "utf-8");
76
+ const tempFileDescriptor = openSync(tempPath, "r+");
77
+ try {
78
+ tolerantFsyncSync(tempFileDescriptor, fsyncImpl);
79
+ } finally {
80
+ closeSync(tempFileDescriptor);
81
+ }
82
+ try {
83
+ renameSync(tempPath, filePath);
84
+ } catch (error) {
85
+ const isPermissionError = error instanceof Error && (error.message.includes("EPERM") || error.message.includes("EACCES"));
86
+ if (platform !== "win32" || !isPermissionError)
87
+ throw error;
81
88
  unlinkSync(filePath);
82
89
  renameSync(tempPath, filePath);
90
+ }
91
+ if (platform === "win32")
83
92
  return;
93
+ const directoryFileDescriptor = openSync(dirname10(filePath), "r");
94
+ try {
95
+ tolerantFsyncSync(directoryFileDescriptor, fsyncImpl);
96
+ } finally {
97
+ closeSync(directoryFileDescriptor);
84
98
  }
85
- throw error;
99
+ } finally {
100
+ rmSync(tempPath, { force: true });
86
101
  }
87
102
  }
88
103
  var TOLERATED_FSYNC_CODES;
@@ -177,7 +192,7 @@ var init_activity_state = __esm(() => {
177
192
  });
178
193
 
179
194
  // packages/telemetry-core/src/constants.ts
180
- var DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com", DEFAULT_POSTHOG_API_KEY = "phc_CFJhj5HyvA62QPhvyaUCtaq23aUfznnijg5VaaGkNk74";
195
+ var DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com", DEFAULT_POSTHOG_API_KEY = "phc_CFJhj5HyvA62QPhvyaUCtaq23aUfznnijg5VaaGkNk74", UNCONFIGURED_POSTHOG_API_KEY = "phc_REPLACE_ME_OMO_NATIVE";
181
196
 
182
197
  // packages/telemetry-core/src/diagnostics.ts
183
198
  import { appendFileSync, existsSync as existsSync6, mkdirSync as mkdirSync3, readFileSync as readFileSync3 } from "node:fs";
@@ -315,6 +330,9 @@ function shouldDisableTelemetry(input) {
315
330
  const env = input.env ?? process.env;
316
331
  const globalPrefix = input.globalEnvPrefix ?? "OMO";
317
332
  const prefixes = Array.from(new Set([globalPrefix, input.productEnvPrefix]));
333
+ if (isDisableFlag(env["DO_NOT_TRACK"])) {
334
+ return true;
335
+ }
318
336
  for (const prefix of prefixes) {
319
337
  if (isDisableFlag(env[`${prefix}_DISABLE_POSTHOG`])) {
320
338
  return true;
@@ -328,6 +346,13 @@ function shouldDisableTelemetry(input) {
328
346
  function getTelemetryApiKey(env = process.env, defaultApiKey = DEFAULT_POSTHOG_API_KEY) {
329
347
  return env["POSTHOG_API_KEY"]?.trim() ?? defaultApiKey;
330
348
  }
349
+ function isConfiguredTelemetryApiKey(apiKey) {
350
+ const normalized = apiKey.trim();
351
+ return normalized.length > 0 && normalized !== UNCONFIGURED_POSTHOG_API_KEY;
352
+ }
353
+ function hasTelemetryApiKey(env, defaultApiKey) {
354
+ return isConfiguredTelemetryApiKey(getTelemetryApiKey(env, defaultApiKey));
355
+ }
331
356
  function getTelemetryHost(env = process.env, defaultHost = DEFAULT_POSTHOG_HOST) {
332
357
  return env["POSTHOG_HOST"]?.trim() || defaultHost;
333
358
  }
@@ -337,19 +362,8 @@ var init_env = __esm(() => {
337
362
  SEND_OPT_OUT_VALUES = ["0", "false", "no", "yes"];
338
363
  });
339
364
 
340
- // packages/telemetry-core/src/machine-id.ts
341
- import { createHash as createHash3 } from "node:crypto";
342
- import os2 from "node:os";
343
- function getDefaultTelemetryOsProvider() {
344
- return os2;
345
- }
346
- function getTelemetryDistinctId(machineIdPrefix, osProvider = getDefaultTelemetryOsProvider()) {
347
- return createHash3("sha256").update(`${machineIdPrefix}${osProvider.hostname()}`).digest("hex");
348
- }
349
- var init_machine_id = () => {};
350
-
351
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs
352
- import { dirname as dirname10, posix as posix2, sep as sep7 } from "node:path";
365
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs
366
+ import { dirname as dirname11, posix as posix2, sep as sep7 } from "node:path";
353
367
  function createModulerModifier() {
354
368
  const getModuleFromFileName = createGetModuleFromFilename();
355
369
  return async (frames) => {
@@ -358,7 +372,7 @@ function createModulerModifier() {
358
372
  return frames;
359
373
  };
360
374
  }
361
- function createGetModuleFromFilename(basePath = process.argv[1] ? dirname10(process.argv[1]) : process.cwd(), isWindows = sep7 === "\\") {
375
+ function createGetModuleFromFilename(basePath = process.argv[1] ? dirname11(process.argv[1]) : process.cwd(), isWindows = sep7 === "\\") {
362
376
  const normalizedBase = isWindows ? normalizeWindowsPath(basePath) : basePath;
363
377
  return (filename) => {
364
378
  if (!filename)
@@ -385,7 +399,7 @@ function normalizeWindowsPath(path2) {
385
399
  }
386
400
  var init_module_node = () => {};
387
401
 
388
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/featureFlagUtils.mjs
402
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/featureFlagUtils.mjs
389
403
  function getFlagDetailFromFlagAndPayload(key, value, payload) {
390
404
  return {
391
405
  key,
@@ -450,10 +464,71 @@ var normalizeFlagsResponse = (flagsResponse) => {
450
464
  } catch {
451
465
  return response;
452
466
  }
467
+ }, MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES, MINIMAL_FLAG_CALLED_EVENT_PROPERTIES, minimizeFlagCalledEventProperties = (properties, transportKeys = []) => {
468
+ const minimal = {};
469
+ const copyKey = (key) => {
470
+ if (properties[key] !== undefined)
471
+ minimal[key] = properties[key];
472
+ };
473
+ MINIMAL_FLAG_CALLED_EVENT_PROPERTIES.forEach(copyKey);
474
+ transportKeys.forEach(copyKey);
475
+ return minimal;
453
476
  };
454
- var init_featureFlagUtils = () => {};
477
+ var init_featureFlagUtils = __esm(() => {
478
+ MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES = [
479
+ "utm_source",
480
+ "utm_medium",
481
+ "utm_campaign",
482
+ "utm_content",
483
+ "utm_term",
484
+ "gad_source",
485
+ "mc_cid",
486
+ "gclid",
487
+ "gclsrc",
488
+ "dclid",
489
+ "gbraid",
490
+ "wbraid",
491
+ "fbclid",
492
+ "msclkid",
493
+ "twclid",
494
+ "li_fat_id",
495
+ "igshid",
496
+ "ttclid",
497
+ "rdt_cid",
498
+ "epik",
499
+ "qclid",
500
+ "sccid",
501
+ "irclid",
502
+ "_kx"
503
+ ];
504
+ MINIMAL_FLAG_CALLED_EVENT_PROPERTIES = [
505
+ "$feature_flag",
506
+ "$feature_flag_response",
507
+ "$feature_flag_has_experiment",
508
+ "$feature_flag_id",
509
+ "$feature_flag_version",
510
+ "$feature_flag_reason",
511
+ "$feature_flag_request_id",
512
+ "$feature_flag_evaluated_at",
513
+ "$feature_flag_error",
514
+ "locally_evaluated",
515
+ "$groups",
516
+ "$process_person_profile",
517
+ "$geoip_disable",
518
+ "$current_url",
519
+ "$pathname",
520
+ "$referring_domain",
521
+ ...MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES,
522
+ "$session_id",
523
+ "$window_id",
524
+ "$lib",
525
+ "$lib_version",
526
+ "$device_id",
527
+ "$is_server"
528
+ ];
529
+ });
455
530
 
456
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/types.mjs
531
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/types.mjs
457
532
  var types_PostHogPersistedProperty;
458
533
  var init_types = __esm(() => {
459
534
  types_PostHogPersistedProperty = /* @__PURE__ */ function(PostHogPersistedProperty) {
@@ -470,6 +545,8 @@ var init_types = __esm(() => {
470
545
  PostHogPersistedProperty["BootstrapFeatureFlagPayloads"] = "bootstrap_feature_flag_payloads";
471
546
  PostHogPersistedProperty["OverrideFeatureFlags"] = "override_feature_flags";
472
547
  PostHogPersistedProperty["Queue"] = "queue";
548
+ PostHogPersistedProperty["AiQueue"] = "ai_queue";
549
+ PostHogPersistedProperty["AiCaptureQueue"] = "ai_capture_queue";
473
550
  PostHogPersistedProperty["LogsQueue"] = "logs_queue";
474
551
  PostHogPersistedProperty["OptedOut"] = "opted_out";
475
552
  PostHogPersistedProperty["SessionId"] = "session_id";
@@ -480,6 +557,8 @@ var init_types = __esm(() => {
480
557
  PostHogPersistedProperty["InstalledAppBuild"] = "installed_app_build";
481
558
  PostHogPersistedProperty["InstalledAppVersion"] = "installed_app_version";
482
559
  PostHogPersistedProperty["SessionReplay"] = "session_replay";
560
+ PostHogPersistedProperty["PushRegistered"] = "push_registered";
561
+ PostHogPersistedProperty["SessionReplayEventTriggerActivatedSession"] = "session_replay_event_trigger_activated_session";
483
562
  PostHogPersistedProperty["SurveyLastSeenDate"] = "survey_last_seen_date";
484
563
  PostHogPersistedProperty["SurveysSeen"] = "surveys_seen";
485
564
  PostHogPersistedProperty["Surveys"] = "surveys";
@@ -490,14 +569,14 @@ var init_types = __esm(() => {
490
569
  }({});
491
570
  });
492
571
 
493
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/gzip.mjs
572
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/gzip.mjs
494
573
  function isGzipSupported() {
495
574
  return "CompressionStream" in globalThis && "TextEncoder" in globalThis && "Response" in globalThis && typeof Response.prototype.blob == "function";
496
575
  }
497
576
  async function gzipCompress(input, isDebug = true, options) {
498
577
  try {
499
578
  const inputBytes = new TextEncoder().encode(input);
500
- const compressedStream = new CompressionStream("gzip");
579
+ const compressedStream = new globalThis.CompressionStream("gzip");
501
580
  const writer = compressedStream.writable.getWriter();
502
581
  const writePromise = writer.write(inputBytes).then(() => writer.close()).catch(async (err) => {
503
582
  try {
@@ -558,7 +637,30 @@ var init_gzip = __esm(() => {
558
637
  init_types();
559
638
  });
560
639
 
561
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/bot-detection.mjs
640
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/json-utils.mjs
641
+ function sanitizeString(value) {
642
+ let output = "";
643
+ for (let index = 0;index < value.length; index++) {
644
+ const codeUnit = value.charCodeAt(index);
645
+ if (codeUnit >= 55296 && codeUnit <= 56319) {
646
+ const nextCodeUnit = value.charCodeAt(index + 1);
647
+ if (nextCodeUnit >= 56320 && nextCodeUnit <= 57343) {
648
+ output += value[index] + value[index + 1];
649
+ index++;
650
+ } else
651
+ output += "�";
652
+ } else
653
+ output += codeUnit >= 56320 && codeUnit <= 57343 ? "�" : value[index];
654
+ }
655
+ return output;
656
+ }
657
+ var MAX_JSON_SAFE_VALUE_DEPTH = 20, MAX_JSON_SAFE_VALUE_ITEMS = 1000, MAX_JSON_SAFE_VALUE_NODES = 1e4, CIRCULAR_VALUE = "[Circular]", TRUNCATED_VALUE = "[Truncated]", UNSERIALIZABLE_VALUE = "[Unserializable]", FUNCTION_VALUE = "[Function]", dateGetTime, dateToISOString;
658
+ var init_json_utils = __esm(() => {
659
+ dateGetTime = Date.prototype.getTime;
660
+ dateToISOString = Date.prototype.toISOString;
661
+ });
662
+
663
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/bot-detection.mjs
562
664
  var DEFAULT_BLOCKED_UA_STRS, isBlockedUA = function(ua, customBlockedUserAgents = []) {
563
665
  if (!ua)
564
666
  return false;
@@ -650,16 +752,56 @@ var init_bot_detection = __esm(() => {
650
752
  ];
651
753
  });
652
754
 
653
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/string-utils.mjs
755
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/string-utils.mjs
756
+ function safeJsonStringify(value) {
757
+ const ancestors = [];
758
+ return JSON.stringify(value, function(_key, replacementValue) {
759
+ if (typeof replacementValue == "bigint")
760
+ return replacementValue.toString();
761
+ if (typeof replacementValue == "function" || typeof replacementValue == "symbol")
762
+ return;
763
+ if (replacementValue instanceof Error)
764
+ return {
765
+ name: replacementValue.name,
766
+ message: replacementValue.message,
767
+ stack: replacementValue.stack
768
+ };
769
+ if (replacementValue && typeof replacementValue == "object") {
770
+ while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this)
771
+ ancestors.pop();
772
+ if (ancestors.includes(replacementValue))
773
+ return "[Circular]";
774
+ ancestors.push(replacementValue);
775
+ }
776
+ return replacementValue;
777
+ }) ?? "null";
778
+ }
654
779
  var init_string_utils = () => {};
655
780
 
656
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/type-utils.mjs
781
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/browser-utils.mjs
782
+ var init_browser_utils = __esm(() => {
783
+ init_string_utils();
784
+ });
785
+
786
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/type-utils.mjs
657
787
  function isPrimitive(value) {
658
788
  return value === null || typeof value != "object";
659
789
  }
660
790
  function isBuiltin(candidate, className) {
661
791
  return Object.prototype.toString.call(candidate) === `[object ${className}]`;
662
792
  }
793
+ function isError(candidate) {
794
+ switch (Object.prototype.toString.call(candidate)) {
795
+ case "[object Error]":
796
+ case "[object Exception]":
797
+ case "[object DOMException]":
798
+ case "[object DOMError]":
799
+ case "[object WebAssembly.Exception]":
800
+ return true;
801
+ default:
802
+ return isInstanceOf(candidate, Error);
803
+ }
804
+ }
663
805
  function isErrorEvent(event) {
664
806
  return isBuiltin(event, "ErrorEvent");
665
807
  }
@@ -676,7 +818,7 @@ function isInstanceOf(candidate, base) {
676
818
  return false;
677
819
  }
678
820
  }
679
- var nativeIsArray, ObjProto, type_utils_hasOwnProperty, type_utils_toString, isArray, isObject = (x) => x === Object(x) && !isArray(x), isUndefined = (x) => x === undefined, isString = (x) => type_utils_toString.call(x) == "[object String]", isEmptyString = (x) => isString(x) && x.trim().length === 0, isNumber = (x) => type_utils_toString.call(x) == "[object Number]" && x === x, isPlainError = (x) => x instanceof Error;
821
+ var nativeIsArray, ObjProto, type_utils_hasOwnProperty, type_utils_toString, isArray, isObject = (x) => x === Object(x) && !isArray(x), isUndefined = (x) => x === undefined, isString = (x) => type_utils_toString.call(x) == "[object String]", isEmptyString = (x) => isString(x) && x.trim().length === 0, isNull = (x) => x === null, isNullish = (x) => isUndefined(x) || isNull(x), isNumber = (x) => type_utils_toString.call(x) == "[object Number]" && x === x, isBoolean = (x) => type_utils_toString.call(x) === "[object Boolean]";
680
822
  var init_type_utils = __esm(() => {
681
823
  init_types();
682
824
  init_string_utils();
@@ -689,7 +831,7 @@ var init_type_utils = __esm(() => {
689
831
  };
690
832
  });
691
833
 
692
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/number-utils.mjs
834
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/number-utils.mjs
693
835
  function clampToRange(value, min, max, logger, fallbackValue) {
694
836
  if (min > max) {
695
837
  logger.warn("min cannot be greater than max.");
@@ -712,7 +854,14 @@ var init_number_utils = __esm(() => {
712
854
  init_type_utils();
713
855
  });
714
856
 
715
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/bucketed-rate-limiter.mjs
857
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/bucketed-rate-limiter.mjs
858
+ function resolveExceptionRateLimiterConfig(config = {}) {
859
+ return {
860
+ refillRate: config.exceptionRateLimiterRefillRate ?? config.__exceptionRateLimiterRefillRate ?? DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE,
861
+ bucketSize: config.exceptionRateLimiterBucketSize ?? config.__exceptionRateLimiterBucketSize ?? DEFAULT_EXCEPTION_RATE_LIMITER_BUCKET_SIZE
862
+ };
863
+ }
864
+
716
865
  class BucketedRateLimiter {
717
866
  constructor(options) {
718
867
  this._buckets = {};
@@ -754,12 +903,12 @@ class BucketedRateLimiter {
754
903
  this._buckets = {};
755
904
  }
756
905
  }
757
- var ONE_DAY_IN_MS = 86400000;
906
+ var ONE_DAY_IN_MS = 86400000, DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE = 1, DEFAULT_EXCEPTION_RATE_LIMITER_BUCKET_SIZE = 10;
758
907
  var init_bucketed_rate_limiter = __esm(() => {
759
908
  init_number_utils();
760
909
  });
761
910
 
762
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/vendor/uuidv7.mjs
911
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/vendor/uuidv7.mjs
763
912
  class UUID {
764
913
  constructor(bytes) {
765
914
  this.bytes = bytes;
@@ -934,37 +1083,49 @@ var init_uuidv7 = __esm(() => {
934
1083
  /*! For license information please see uuidv7.mjs.LICENSE.txt */
935
1084
  });
936
1085
 
937
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/promise-queue.mjs
1086
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/promise-queue.mjs
938
1087
  class PromiseQueue {
939
1088
  add(promise) {
940
1089
  const promiseUUID = uuidv7();
941
- this.promiseByIds[promiseUUID] = promise;
1090
+ const id = ++this.nextId;
1091
+ this.promiseByIds[promiseUUID] = {
1092
+ id,
1093
+ promise
1094
+ };
942
1095
  promise.catch(() => {}).finally(() => {
943
1096
  delete this.promiseByIds[promiseUUID];
944
1097
  });
945
1098
  return promise;
946
1099
  }
947
1100
  async join() {
948
- let promises = Object.values(this.promiseByIds);
1101
+ let promises = Object.values(this.promiseByIds).map((item) => item.promise);
949
1102
  let length = promises.length;
950
1103
  while (length > 0) {
951
1104
  await Promise.all(promises);
952
- promises = Object.values(this.promiseByIds);
1105
+ promises = Object.values(this.promiseByIds).map((item) => item.promise);
953
1106
  length = promises.length;
954
1107
  }
955
1108
  }
1109
+ getPromises(ignoredPromises = [], maxId = this.nextId) {
1110
+ const ignoredPromiseSet = new Set(ignoredPromises);
1111
+ return Object.values(this.promiseByIds).filter((item) => item.id <= maxId && !ignoredPromiseSet.has(item.promise)).map((item) => item.promise);
1112
+ }
1113
+ get maxId() {
1114
+ return this.nextId;
1115
+ }
956
1116
  get length() {
957
1117
  return Object.keys(this.promiseByIds).length;
958
1118
  }
959
1119
  constructor() {
960
1120
  this.promiseByIds = {};
1121
+ this.nextId = 0;
961
1122
  }
962
1123
  }
963
1124
  var init_promise_queue = __esm(() => {
964
1125
  init_uuidv7();
965
1126
  });
966
1127
 
967
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/logger.mjs
1128
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/logger.mjs
968
1129
  function createConsole(consoleLike = console) {
969
1130
  const lockedMethods = {
970
1131
  log: consoleLike.log.bind(consoleLike),
@@ -1006,8 +1167,8 @@ var _createLogger = (prefix, maybeCall, consoleLike) => {
1006
1167
  }, passThrough = (fn) => fn();
1007
1168
  var init_logger = () => {};
1008
1169
 
1009
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/user-agent-utils.mjs
1010
- var MOBILE = "Mobile", IOS = "iOS", ANDROID = "Android", TABLET = "Tablet", ANDROID_TABLET, APPLE = "Apple", APPLE_WATCH, SAFARI = "Safari", BLACKBERRY = "BlackBerry", SAMSUNG = "Samsung", SAMSUNG_BROWSER, SAMSUNG_INTERNET, CHROME = "Chrome", CHROME_OS, CHROME_IOS, INTERNET_EXPLORER = "Internet Explorer", INTERNET_EXPLORER_MOBILE, OPERA = "Opera", OPERA_MINI, EDGE = "Edge", MICROSOFT_EDGE, FIREFOX = "Firefox", FIREFOX_IOS, NINTENDO = "Nintendo", PLAYSTATION = "PlayStation", XBOX = "Xbox", ANDROID_MOBILE, MOBILE_SAFARI, WINDOWS = "Windows", WINDOWS_PHONE, GENERIC = "Generic", GENERIC_MOBILE, GENERIC_TABLET, KONQUEROR = "Konqueror", OCULUS_BROWSER = "Oculus Browser", VIVALDI = "Vivaldi", YANDEX = "Yandex", WHALE = "Whale", DUCKDUCKGO = "DuckDuckGo", PALE_MOON = "Pale Moon", WATERFOX = "Waterfox", BRAVE = "Brave", BROWSER_VERSION_REGEX_SUFFIX = "(\\d+(\\.\\d+)?)", DEFAULT_BROWSER_VERSION_REGEX, XBOX_REGEX, PLAYSTATION_REGEX, NINTENDO_REGEX, BLACKBERRY_REGEX, windowsVersionMap, versionRegexes, osMatchers;
1170
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/user-agent-utils.mjs
1171
+ var MOBILE = "Mobile", IOS = "iOS", ANDROID = "Android", TABLET = "Tablet", ANDROID_TABLET, APPLE = "Apple", APPLE_WATCH, SAFARI = "Safari", BLACKBERRY = "BlackBerry", SAMSUNG = "Samsung", SAMSUNG_BROWSER, SAMSUNG_INTERNET, CHROME = "Chrome", CHROME_OS, CHROME_IOS, INTERNET_EXPLORER = "Internet Explorer", INTERNET_EXPLORER_MOBILE, OPERA = "Opera", OPERA_MINI, EDGE = "Edge", MICROSOFT_EDGE, FIREFOX = "Firefox", FIREFOX_IOS, NINTENDO = "Nintendo", PLAYSTATION = "PlayStation", XBOX = "Xbox", ANDROID_MOBILE, MOBILE_SAFARI, WINDOWS = "Windows", WINDOWS_PHONE, GENERIC = "Generic", GENERIC_MOBILE, GENERIC_TABLET, KONQUEROR = "Konqueror", OCULUS_BROWSER = "Oculus Browser", VIVALDI = "Vivaldi", YANDEX = "Yandex", WHALE = "Whale", DUCKDUCKGO = "DuckDuckGo", PALE_MOON = "Pale Moon", WATERFOX = "Waterfox", BRAVE = "Brave", GOOGLE_SEARCH_APP = "Google Search App", BROWSER_VERSION_REGEX_SUFFIX = "(\\d+(\\.\\d+)?)", DEFAULT_BROWSER_VERSION_REGEX, XBOX_REGEX, PLAYSTATION_REGEX, NINTENDO_REGEX, BLACKBERRY_REGEX, windowsVersionMap, versionRegexes, osMatchers;
1011
1172
  var init_user_agent_utils = __esm(() => {
1012
1173
  init_string_utils();
1013
1174
  init_type_utils();
@@ -1112,6 +1273,9 @@ var init_user_agent_utils = __esm(() => {
1112
1273
  [WATERFOX]: [
1113
1274
  new RegExp(WATERFOX + "\\/" + BROWSER_VERSION_REGEX_SUFFIX)
1114
1275
  ],
1276
+ [GOOGLE_SEARCH_APP]: [
1277
+ new RegExp("GSA\\/" + BROWSER_VERSION_REGEX_SUFFIX)
1278
+ ],
1115
1279
  [INTERNET_EXPLORER]: [
1116
1280
  new RegExp("(rv:|MSIE )" + BROWSER_VERSION_REGEX_SUFFIX)
1117
1281
  ],
@@ -1272,7 +1436,13 @@ var init_user_agent_utils = __esm(() => {
1272
1436
  ];
1273
1437
  });
1274
1438
 
1275
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/index.mjs
1439
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/index.mjs
1440
+ function isValidUUID(value) {
1441
+ return typeof value == "string" && UUID_REGEX.test(value);
1442
+ }
1443
+ function getEventUuid(uuid, generateUuid) {
1444
+ return isValidUUID(uuid) ? uuid : generateUuid();
1445
+ }
1276
1446
  function removeTrailingSlash(url) {
1277
1447
  return url?.replace(/\/+$/, "");
1278
1448
  }
@@ -1300,6 +1470,26 @@ function safeSetTimeout(fn, timeout) {
1300
1470
  t?.unref && t?.unref();
1301
1471
  return t;
1302
1472
  }
1473
+ async function raceWithTimeout(promise, timeoutMs, onTimeout) {
1474
+ let timeoutHandle;
1475
+ try {
1476
+ return await Promise.race([
1477
+ promise,
1478
+ new Promise((resolve9, reject) => {
1479
+ timeoutHandle = safeSetTimeout(() => {
1480
+ try {
1481
+ onTimeout?.();
1482
+ resolve9();
1483
+ } catch (error) {
1484
+ reject(error);
1485
+ }
1486
+ }, timeoutMs);
1487
+ })
1488
+ ]);
1489
+ } finally {
1490
+ clearTimeout(timeoutHandle);
1491
+ }
1492
+ }
1303
1493
  function allSettled(promises) {
1304
1494
  return Promise.all(promises.map((p) => (p ?? Promise.resolve()).then((value) => ({
1305
1495
  status: "fulfilled",
@@ -1309,9 +1499,11 @@ function allSettled(promises) {
1309
1499
  reason
1310
1500
  }))));
1311
1501
  }
1312
- var STRING_FORMAT = "utf8", isError = (x) => x instanceof Error;
1502
+ var STRING_FORMAT = "utf8", UUID_REGEX;
1313
1503
  var init_utils = __esm(() => {
1504
+ init_json_utils();
1314
1505
  init_bot_detection();
1506
+ init_browser_utils();
1315
1507
  init_bucketed_rate_limiter();
1316
1508
  init_number_utils();
1317
1509
  init_string_utils();
@@ -1319,12 +1511,168 @@ var init_utils = __esm(() => {
1319
1511
  init_promise_queue();
1320
1512
  init_logger();
1321
1513
  init_user_agent_utils();
1514
+ UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1322
1515
  });
1323
1516
 
1324
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/logs/logs-utils.mjs
1325
- var OTLP_SEVERITY_MAP, DEFAULT_OTLP_SEVERITY;
1517
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/logs/logs-utils.mjs
1518
+ function newState() {
1519
+ return {
1520
+ ancestors: new WeakSet,
1521
+ remainingNodes: MAX_JSON_SAFE_VALUE_NODES
1522
+ };
1523
+ }
1524
+ function toOtlpKeyValueList(attrs, logger2) {
1525
+ try {
1526
+ return encodeKeyValueList(attrs, logger2, newState(), 0);
1527
+ } catch {
1528
+ return [];
1529
+ }
1530
+ }
1531
+ function encodeAnyValue(value, logger2, state, depth) {
1532
+ if (state.remainingNodes <= 0)
1533
+ return {
1534
+ stringValue: TRUNCATED_VALUE
1535
+ };
1536
+ state.remainingNodes--;
1537
+ if (isBoolean(value))
1538
+ return {
1539
+ boolValue: value
1540
+ };
1541
+ if (typeof value == "number") {
1542
+ if (!Number.isFinite(value))
1543
+ return {
1544
+ stringValue: String(value)
1545
+ };
1546
+ if (Number.isInteger(value)) {
1547
+ if (Number.isSafeInteger(value))
1548
+ return {
1549
+ intValue: String(value)
1550
+ };
1551
+ if (typeof BigInt == "undefined")
1552
+ return {
1553
+ stringValue: String(value)
1554
+ };
1555
+ const decimal = BigInt(value).toString();
1556
+ if (value >= INT64_RANGE_LIMIT || value < -INT64_RANGE_LIMIT) {
1557
+ logger2?.debug(`Attribute ${decimal} is outside the int64 range; encoding it as a string`);
1558
+ return {
1559
+ stringValue: decimal
1560
+ };
1561
+ }
1562
+ return {
1563
+ intValue: decimal
1564
+ };
1565
+ }
1566
+ return {
1567
+ doubleValue: value
1568
+ };
1569
+ }
1570
+ if (typeof value == "string")
1571
+ return {
1572
+ stringValue: sanitizeString(value)
1573
+ };
1574
+ if (typeof value == "function")
1575
+ return {
1576
+ stringValue: FUNCTION_VALUE
1577
+ };
1578
+ if (typeof value == "symbol")
1579
+ return {
1580
+ stringValue: String(value)
1581
+ };
1582
+ if (typeof value == "object" && value !== null) {
1583
+ if (state.ancestors.has(value))
1584
+ return {
1585
+ stringValue: CIRCULAR_VALUE
1586
+ };
1587
+ if (depth >= MAX_JSON_SAFE_VALUE_DEPTH)
1588
+ return {
1589
+ stringValue: TRUNCATED_VALUE
1590
+ };
1591
+ if (value instanceof Date) {
1592
+ const time = value.getTime();
1593
+ const iso = Number.isFinite(time) ? value.toISOString() : String(value);
1594
+ return {
1595
+ stringValue: typeof iso == "string" ? sanitizeString(iso) : String(iso)
1596
+ };
1597
+ }
1598
+ state.ancestors.add(value);
1599
+ try {
1600
+ try {
1601
+ const toJSON = value.toJSON;
1602
+ if (typeof toJSON == "function")
1603
+ return encodeAnyValue(toJSON.call(value), logger2, state, depth + 1);
1604
+ } catch {}
1605
+ if (isArray(value))
1606
+ return {
1607
+ arrayValue: {
1608
+ values: encodeArrayValues(value, logger2, state, depth + 1)
1609
+ }
1610
+ };
1611
+ return {
1612
+ kvlistValue: {
1613
+ values: encodeKeyValueList(value, logger2, state, depth + 1)
1614
+ }
1615
+ };
1616
+ } finally {
1617
+ state.ancestors.delete(value);
1618
+ }
1619
+ }
1620
+ return {
1621
+ stringValue: sanitizeString(String(value))
1622
+ };
1623
+ }
1624
+ function encodeArrayValues(values, logger2, state, depth) {
1625
+ const result = [];
1626
+ const itemCount = Math.min(values.length, MAX_JSON_SAFE_VALUE_ITEMS);
1627
+ let index = 0;
1628
+ for (;index < itemCount && state.remainingNodes > 0; index++)
1629
+ try {
1630
+ const element = index in values ? values[index] : undefined;
1631
+ if (isNullish(element))
1632
+ continue;
1633
+ result.push(encodeAnyValue(element, logger2, state, depth));
1634
+ } catch {
1635
+ result.push({
1636
+ stringValue: UNSERIALIZABLE_VALUE
1637
+ });
1638
+ }
1639
+ if (values.length > index)
1640
+ result.push({
1641
+ stringValue: TRUNCATED_VALUE
1642
+ });
1643
+ return result;
1644
+ }
1645
+ function encodeKeyValueList(attrs, logger2, state, depth) {
1646
+ const result = [];
1647
+ for (const key in attrs)
1648
+ if (propertyIsEnumerable.call(attrs, key)) {
1649
+ if (result.length >= MAX_JSON_SAFE_VALUE_ITEMS || state.remainingNodes <= 0) {
1650
+ logger2?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");
1651
+ break;
1652
+ }
1653
+ try {
1654
+ const value = attrs[key];
1655
+ if (isNull(value) || isUndefined(value))
1656
+ continue;
1657
+ result.push({
1658
+ key: sanitizeString(key),
1659
+ value: encodeAnyValue(value, logger2, state, depth)
1660
+ });
1661
+ } catch {
1662
+ result.push({
1663
+ key: sanitizeString(key),
1664
+ value: {
1665
+ stringValue: UNSERIALIZABLE_VALUE
1666
+ }
1667
+ });
1668
+ }
1669
+ }
1670
+ return result;
1671
+ }
1672
+ var OTLP_SEVERITY_MAP, DEFAULT_OTLP_SEVERITY, INT64_RANGE_LIMIT = 9223372036854776000, propertyIsEnumerable;
1326
1673
  var init_logs_utils = __esm(() => {
1327
1674
  init_utils();
1675
+ init_json_utils();
1328
1676
  OTLP_SEVERITY_MAP = {
1329
1677
  trace: {
1330
1678
  text: "TRACE",
@@ -1352,27 +1700,444 @@ var init_logs_utils = __esm(() => {
1352
1700
  }
1353
1701
  };
1354
1702
  DEFAULT_OTLP_SEVERITY = OTLP_SEVERITY_MAP.info;
1703
+ propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
1355
1704
  });
1356
1705
 
1357
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/logs/index.mjs
1706
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/logs/index.mjs
1358
1707
  var init_logs = __esm(() => {
1359
1708
  init_logs_utils();
1360
1709
  init_types();
1361
1710
  init_utils();
1362
1711
  });
1363
1712
 
1364
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/surveys/validation.mjs
1713
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/metrics/metrics-utils.mjs
1714
+ function msToUnixNano(ms) {
1715
+ return String(ms) + "000000";
1716
+ }
1717
+ function seriesKey(type, name, unit, attributes) {
1718
+ let attrsKey = "";
1719
+ if (attributes) {
1720
+ const keys = Object.keys(attributes).sort();
1721
+ attrsKey = keys.map((k) => `${JSON.stringify(k)}:${JSON.stringify(attributes[k])}`).join(",");
1722
+ }
1723
+ return `${type}\x00${name}\x00${unit ?? ""}\x00${attrsKey}`;
1724
+ }
1725
+ function bucketIndexFor(value, bounds) {
1726
+ for (let i = 0;i < bounds.length; i++)
1727
+ if (value <= bounds[i])
1728
+ return i;
1729
+ return bounds.length;
1730
+ }
1731
+ function buildMetricsResourceAttributes(config, scopeName, scopeVersion) {
1732
+ return {
1733
+ ...config.resourceAttributes,
1734
+ "service.name": config.serviceName || "unknown_service",
1735
+ ...config.environment && {
1736
+ "deployment.environment": config.environment
1737
+ },
1738
+ ...config.serviceVersion && {
1739
+ "service.version": config.serviceVersion
1740
+ },
1741
+ "telemetry.sdk.name": scopeName,
1742
+ "telemetry.sdk.version": scopeVersion
1743
+ };
1744
+ }
1745
+ function buildOtlpMetricsPayload(metrics, resourceAttributes, scopeName, scopeVersion) {
1746
+ return {
1747
+ resourceMetrics: [
1748
+ {
1749
+ resource: {
1750
+ attributes: toOtlpKeyValueList(resourceAttributes)
1751
+ },
1752
+ scopeMetrics: [
1753
+ {
1754
+ scope: {
1755
+ name: scopeName,
1756
+ version: scopeVersion
1757
+ },
1758
+ metrics
1759
+ }
1760
+ ]
1761
+ }
1762
+ ]
1763
+ };
1764
+ }
1765
+ var DEFAULT_HISTOGRAM_BOUNDS;
1766
+ var init_metrics_utils = __esm(() => {
1767
+ init_logs_utils();
1768
+ DEFAULT_HISTOGRAM_BOUNDS = [
1769
+ 0,
1770
+ 5,
1771
+ 10,
1772
+ 25,
1773
+ 50,
1774
+ 75,
1775
+ 100,
1776
+ 250,
1777
+ 500,
1778
+ 750,
1779
+ 1000,
1780
+ 2500,
1781
+ 5000,
1782
+ 7500,
1783
+ 1e4
1784
+ ];
1785
+ });
1786
+
1787
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/metrics/config.mjs
1788
+ function resolveMetricsConfig(config) {
1789
+ const resourceAttributes = config?.resourceAttributes;
1790
+ return {
1791
+ serviceName: resourceAttributes?.["service.name"] ?? config?.serviceName,
1792
+ serviceVersion: resourceAttributes?.["service.version"] ?? config?.serviceVersion,
1793
+ environment: resourceAttributes?.["deployment.environment"] ?? config?.environment,
1794
+ resourceAttributes,
1795
+ beforeSend: config?.beforeSend,
1796
+ flushIntervalMs: config?.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,
1797
+ maxSeriesPerFlush: config?.maxSeriesPerFlush ?? DEFAULT_MAX_SERIES_PER_FLUSH
1798
+ };
1799
+ }
1800
+ var DEFAULT_FLUSH_INTERVAL_MS = 1e4, DEFAULT_MAX_SERIES_PER_FLUSH = 1000;
1801
+ var init_config = () => {};
1802
+
1803
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/metrics/index.mjs
1804
+ class PostHogMetrics {
1805
+ constructor(_instance, _config, _logger) {
1806
+ this._instance = _instance;
1807
+ this._config = _config;
1808
+ this._logger = _logger;
1809
+ this._series = new Map;
1810
+ this._flushPromise = null;
1811
+ this._seriesCapWarned = false;
1812
+ this._typeByName = new Map;
1813
+ this._typeCollisionWarned = new Set;
1814
+ this._generation = 0;
1815
+ }
1816
+ count(name, value = 1, options) {
1817
+ this._capture({
1818
+ name,
1819
+ type: "count",
1820
+ value,
1821
+ unit: options?.unit,
1822
+ attributes: options?.attributes
1823
+ });
1824
+ }
1825
+ gauge(name, value, options) {
1826
+ this._capture({
1827
+ name,
1828
+ type: "gauge",
1829
+ value,
1830
+ unit: options?.unit,
1831
+ attributes: options?.attributes
1832
+ });
1833
+ }
1834
+ histogram(name, value, options) {
1835
+ this._capture({
1836
+ name,
1837
+ type: "histogram",
1838
+ value,
1839
+ unit: options?.unit,
1840
+ attributes: options?.attributes
1841
+ });
1842
+ }
1843
+ flush() {
1844
+ const prev = this._flushPromise;
1845
+ const run = async () => {
1846
+ if (prev)
1847
+ await prev.catch(() => {});
1848
+ await this._doFlush();
1849
+ };
1850
+ const p = run().finally(() => {
1851
+ if (this._flushPromise === p)
1852
+ this._flushPromise = null;
1853
+ });
1854
+ this._flushPromise = p;
1855
+ return p;
1856
+ }
1857
+ drainWindow() {
1858
+ if (this._series.size === 0)
1859
+ return null;
1860
+ const window = this._series;
1861
+ this._series = new Map;
1862
+ this._seriesCapWarned = false;
1863
+ this._typeByName = new Map;
1864
+ this._typeCollisionWarned = new Set;
1865
+ return this._buildPayload(window);
1866
+ }
1867
+ reset() {
1868
+ this._generation++;
1869
+ this._clearFlushTimer();
1870
+ this._series = new Map;
1871
+ this._flushPromise = null;
1872
+ this._seriesCapWarned = false;
1873
+ this._typeByName = new Map;
1874
+ this._typeCollisionWarned = new Set;
1875
+ }
1876
+ _capture(sample) {
1877
+ if (this._instance.isDisabled || this._instance.optedOut)
1878
+ return;
1879
+ const filtered = this._runBeforeSend(sample);
1880
+ if (filtered === null)
1881
+ return;
1882
+ if (!filtered.name || typeof filtered.name != "string")
1883
+ return void this._logger.warn("Dropping metric with empty name");
1884
+ if (typeof filtered.value != "number" || !Number.isFinite(filtered.value))
1885
+ return void this._logger.warn(`Dropping metric '${filtered.name}': value must be a finite number`);
1886
+ if (filtered.type === "count" && filtered.value < 0)
1887
+ return void this._logger.warn(`Dropping count '${filtered.name}': counters are monotonic, value must be >= 0`);
1888
+ let attributes;
1889
+ let key;
1890
+ try {
1891
+ attributes = filtered.attributes ? {
1892
+ ...filtered.attributes
1893
+ } : undefined;
1894
+ key = seriesKey(filtered.type, filtered.name, filtered.unit, attributes);
1895
+ } catch (e) {
1896
+ this._logger.warn(`Dropping metric '${filtered.name}': attributes could not be serialized`, e);
1897
+ return;
1898
+ }
1899
+ let state = this._series.get(key);
1900
+ if (!state) {
1901
+ if (!this._admitNewSeries())
1902
+ return;
1903
+ state = {
1904
+ name: filtered.name,
1905
+ type: filtered.type,
1906
+ unit: filtered.unit,
1907
+ attributes,
1908
+ windowStartMs: Date.now()
1909
+ };
1910
+ this._series.set(key, state);
1911
+ }
1912
+ const seenType = this._typeByName.get(filtered.name);
1913
+ if (seenType === undefined)
1914
+ this._typeByName.set(filtered.name, filtered.type);
1915
+ else if (seenType !== filtered.type && !this._typeCollisionWarned.has(filtered.name)) {
1916
+ this._typeCollisionWarned.add(filtered.name);
1917
+ 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.`);
1918
+ }
1919
+ this._fold(state, filtered.value);
1920
+ this._armFlushTimer();
1921
+ }
1922
+ _admitNewSeries() {
1923
+ if (this._series.size < this._config.maxSeriesPerFlush)
1924
+ return true;
1925
+ if (!this._seriesCapWarned) {
1926
+ this._seriesCapWarned = true;
1927
+ this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`);
1928
+ }
1929
+ return false;
1930
+ }
1931
+ _fold(state, value) {
1932
+ switch (state.type) {
1933
+ case "count":
1934
+ state.total = (state.total ?? 0) + value;
1935
+ break;
1936
+ case "gauge":
1937
+ state.last = value;
1938
+ break;
1939
+ case "histogram": {
1940
+ if (!state.hist)
1941
+ state.hist = {
1942
+ count: 0,
1943
+ sum: 0,
1944
+ min: value,
1945
+ max: value,
1946
+ bucketCounts: new Array(DEFAULT_HISTOGRAM_BOUNDS.length + 1).fill(0)
1947
+ };
1948
+ const hist = state.hist;
1949
+ hist.count += 1;
1950
+ hist.sum += value;
1951
+ hist.min = Math.min(hist.min, value);
1952
+ hist.max = Math.max(hist.max, value);
1953
+ hist.bucketCounts[bucketIndexFor(value, DEFAULT_HISTOGRAM_BOUNDS)] += 1;
1954
+ break;
1955
+ }
1956
+ }
1957
+ }
1958
+ _runBeforeSend(sample) {
1959
+ const beforeSend = this._config.beforeSend;
1960
+ if (!beforeSend)
1961
+ return sample;
1962
+ const fns = isArray(beforeSend) ? beforeSend : [
1963
+ beforeSend
1964
+ ];
1965
+ let result = sample;
1966
+ for (const fn of fns)
1967
+ try {
1968
+ const next = fn(result);
1969
+ if (!next) {
1970
+ this._logger.info("Metric was rejected in beforeSend function");
1971
+ return null;
1972
+ }
1973
+ result = next;
1974
+ } catch (e) {
1975
+ this._logger.error("Error in beforeSend function for metric:", e);
1976
+ return null;
1977
+ }
1978
+ return result;
1979
+ }
1980
+ _armFlushTimer() {
1981
+ if (this._flushTimer)
1982
+ return;
1983
+ this._flushTimer = safeSetTimeout(() => {
1984
+ this._flushTimer = undefined;
1985
+ this.flush().catch((e) => {
1986
+ this._logger.error("Metrics flush failed:", e);
1987
+ });
1988
+ }, this._config.flushIntervalMs);
1989
+ }
1990
+ _clearFlushTimer() {
1991
+ if (this._flushTimer) {
1992
+ clearTimeout(this._flushTimer);
1993
+ this._flushTimer = undefined;
1994
+ }
1995
+ }
1996
+ async _doFlush() {
1997
+ if (this._series.size === 0)
1998
+ return;
1999
+ const window = this._series;
2000
+ this._series = new Map;
2001
+ this._seriesCapWarned = false;
2002
+ this._typeByName = new Map;
2003
+ this._typeCollisionWarned = new Set;
2004
+ const generation = this._generation;
2005
+ const outcome = await this._instance._sendMetricsBatch(this._buildPayload(window));
2006
+ if (generation !== this._generation)
2007
+ return;
2008
+ switch (outcome.kind) {
2009
+ case "ok":
2010
+ return;
2011
+ case "retry-later":
2012
+ this._mergeWindowBack(window);
2013
+ this._armFlushTimer();
2014
+ return;
2015
+ case "too-large":
2016
+ this._logger.warn("Metrics batch exceeded the server size limit and was dropped");
2017
+ return;
2018
+ case "fatal":
2019
+ this._logger.error("Failed to send metrics batch:", outcome.error);
2020
+ return;
2021
+ }
2022
+ }
2023
+ _buildPayload(window) {
2024
+ return buildOtlpMetricsPayload(this._buildMetrics(window), buildMetricsResourceAttributes(this._config, this._instance.getLibraryId(), this._instance.getLibraryVersion()), this._instance.getLibraryId(), this._instance.getLibraryVersion());
2025
+ }
2026
+ _buildMetrics(window) {
2027
+ const nowNano = msToUnixNano(Date.now());
2028
+ const byMetric = new Map;
2029
+ for (const state of window.values()) {
2030
+ const metricKey = seriesKey(state.type, state.name, state.unit, undefined);
2031
+ let metric = byMetric.get(metricKey);
2032
+ if (!metric) {
2033
+ metric = {
2034
+ name: state.name,
2035
+ ...state.unit && {
2036
+ unit: state.unit
2037
+ }
2038
+ };
2039
+ if (state.type === "count")
2040
+ metric.sum = {
2041
+ aggregationTemporality: OTLP_TEMPORALITY_DELTA,
2042
+ isMonotonic: true,
2043
+ dataPoints: []
2044
+ };
2045
+ else if (state.type === "gauge")
2046
+ metric.gauge = {
2047
+ dataPoints: []
2048
+ };
2049
+ else
2050
+ metric.histogram = {
2051
+ aggregationTemporality: OTLP_TEMPORALITY_DELTA,
2052
+ dataPoints: []
2053
+ };
2054
+ byMetric.set(metricKey, metric);
2055
+ }
2056
+ const attributes = toOtlpKeyValueList(state.attributes ?? {}, this._logger);
2057
+ const startNano = msToUnixNano(state.windowStartMs);
2058
+ if (state.type === "count") {
2059
+ const dp = {
2060
+ attributes,
2061
+ startTimeUnixNano: startNano,
2062
+ timeUnixNano: nowNano,
2063
+ asDouble: state.total ?? 0
2064
+ };
2065
+ metric.sum.dataPoints.push(dp);
2066
+ } else if (state.type === "gauge") {
2067
+ const dp = {
2068
+ attributes,
2069
+ timeUnixNano: nowNano,
2070
+ asDouble: state.last ?? 0
2071
+ };
2072
+ metric.gauge.dataPoints.push(dp);
2073
+ } else if (state.hist) {
2074
+ const dp = {
2075
+ attributes,
2076
+ startTimeUnixNano: startNano,
2077
+ timeUnixNano: nowNano,
2078
+ count: state.hist.count,
2079
+ sum: state.hist.sum,
2080
+ min: state.hist.min,
2081
+ max: state.hist.max,
2082
+ bucketCounts: state.hist.bucketCounts,
2083
+ explicitBounds: DEFAULT_HISTOGRAM_BOUNDS
2084
+ };
2085
+ metric.histogram.dataPoints.push(dp);
2086
+ }
2087
+ }
2088
+ return Array.from(byMetric.values());
2089
+ }
2090
+ _mergeWindowBack(window) {
2091
+ for (const [key, old] of window) {
2092
+ const current = this._series.get(key);
2093
+ if (!current) {
2094
+ if (this._admitNewSeries())
2095
+ this._series.set(key, old);
2096
+ continue;
2097
+ }
2098
+ current.windowStartMs = Math.min(current.windowStartMs, old.windowStartMs);
2099
+ switch (current.type) {
2100
+ case "count":
2101
+ current.total = (current.total ?? 0) + (old.total ?? 0);
2102
+ break;
2103
+ case "gauge":
2104
+ break;
2105
+ case "histogram":
2106
+ if (old.hist)
2107
+ if (current.hist) {
2108
+ current.hist.count += old.hist.count;
2109
+ current.hist.sum += old.hist.sum;
2110
+ current.hist.min = Math.min(current.hist.min, old.hist.min);
2111
+ current.hist.max = Math.max(current.hist.max, old.hist.max);
2112
+ for (let i = 0;i < current.hist.bucketCounts.length; i++)
2113
+ current.hist.bucketCounts[i] += old.hist.bucketCounts[i];
2114
+ } else
2115
+ current.hist = old.hist;
2116
+ break;
2117
+ }
2118
+ }
2119
+ }
2120
+ }
2121
+ var OTLP_TEMPORALITY_DELTA = 1;
2122
+ var init_metrics = __esm(() => {
2123
+ init_utils();
2124
+ init_logs_utils();
2125
+ init_metrics_utils();
2126
+ init_config();
2127
+ });
2128
+
2129
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/surveys/validation.mjs
1365
2130
  var init_validation = __esm(() => {
1366
2131
  init_types();
1367
2132
  });
1368
2133
 
1369
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/cookie.mjs
2134
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/cookie.mjs
1370
2135
  var init_cookie = __esm(() => {
1371
2136
  init_utils();
1372
2137
  init_uuidv7();
1373
2138
  });
1374
2139
 
1375
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/eventemitter.mjs
2140
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/eventemitter.mjs
1376
2141
  class SimpleEventEmitter {
1377
2142
  constructor() {
1378
2143
  this.events = {};
@@ -1395,7 +2160,7 @@ class SimpleEventEmitter {
1395
2160
  }
1396
2161
  var init_eventemitter = () => {};
1397
2162
 
1398
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/chunk-ids.mjs
2163
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/chunk-ids.mjs
1399
2164
  function getFilenameToChunkIdMap(stackParser) {
1400
2165
  const chunkIdMap = globalThis._posthogChunkIds;
1401
2166
  if (!chunkIdMap)
@@ -1433,7 +2198,7 @@ function getFilenameToChunkIdMap(stackParser) {
1433
2198
  var parsedStackResults, lastKeysCount, cachedFilenameChunkIds;
1434
2199
  var init_chunk_ids = () => {};
1435
2200
 
1436
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/error-properties-builder.mjs
2201
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/error-properties-builder.mjs
1437
2202
  class ErrorPropertiesBuilder {
1438
2203
  constructor(coercers, stackParser, modifiers = []) {
1439
2204
  this.coercers = coercers;
@@ -1559,13 +2324,13 @@ var init_error_properties_builder = __esm(() => {
1559
2324
  init_chunk_ids();
1560
2325
  });
1561
2326
 
1562
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/base.mjs
2327
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/base.mjs
1563
2328
  function createFrame(platform, filename, func, lineno, colno) {
1564
2329
  const frame = {
1565
2330
  platform,
1566
2331
  filename,
1567
2332
  function: func === "<anonymous>" ? UNKNOWN_FUNCTION : func,
1568
- in_app: true
2333
+ in_app: !filename?.startsWith(MASKED_URL_PREFIX) && filename !== ANONYMOUS_FILENAME
1569
2334
  };
1570
2335
  if (!isUndefined(lineno))
1571
2336
  frame.lineno = lineno;
@@ -1573,12 +2338,12 @@ function createFrame(platform, filename, func, lineno, colno) {
1573
2338
  frame.colno = colno;
1574
2339
  return frame;
1575
2340
  }
1576
- var UNKNOWN_FUNCTION = "?";
2341
+ var UNKNOWN_FUNCTION = "?", MASKED_URL_PREFIX = "webkit-masked-url://", ANONYMOUS_FILENAME = "<anonymous>";
1577
2342
  var init_base = __esm(() => {
1578
2343
  init_utils();
1579
2344
  });
1580
2345
 
1581
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/safari.mjs
2346
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/safari.mjs
1582
2347
  var extractSafariExtensionDetails = (func, filename) => {
1583
2348
  const isSafariExtension = func.indexOf("safari-extension") !== -1;
1584
2349
  const isSafariWebExtension = func.indexOf("safari-web-extension") !== -1;
@@ -1594,7 +2359,7 @@ var init_safari = __esm(() => {
1594
2359
  init_base();
1595
2360
  });
1596
2361
 
1597
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/chrome.mjs
2362
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/chrome.mjs
1598
2363
  var chromeRegexNoFnName, chromeRegex, chromeEvalRegex, chromeStackLineParser = (line, platform) => {
1599
2364
  const noFnParts = chromeRegexNoFnName.exec(line);
1600
2365
  if (noFnParts) {
@@ -1624,7 +2389,7 @@ var init_chrome = __esm(() => {
1624
2389
  chromeEvalRegex = /\((\S*)(?::(\d+))(?::(\d+))\)/;
1625
2390
  });
1626
2391
 
1627
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/gecko.mjs
2392
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/gecko.mjs
1628
2393
  var geckoREgex, geckoEvalRegex, geckoStackLineParser = (line, platform) => {
1629
2394
  const parts = geckoREgex.exec(line);
1630
2395
  if (parts) {
@@ -1651,7 +2416,7 @@ var init_gecko = __esm(() => {
1651
2416
  geckoEvalRegex = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
1652
2417
  });
1653
2418
 
1654
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/winjs.mjs
2419
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/winjs.mjs
1655
2420
  var winjsRegex, winjsStackLineParser = (line, platform) => {
1656
2421
  const parts = winjsRegex.exec(line);
1657
2422
  return parts ? createFrame(platform, parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : undefined) : undefined;
@@ -1661,7 +2426,7 @@ var init_winjs = __esm(() => {
1661
2426
  winjsRegex = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
1662
2427
  });
1663
2428
 
1664
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/opera.mjs
2429
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/opera.mjs
1665
2430
  var opera10Regex, opera10StackLineParser = (line, platform) => {
1666
2431
  const parts = opera10Regex.exec(line);
1667
2432
  return parts ? createFrame(platform, parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : undefined;
@@ -1675,7 +2440,7 @@ var init_opera = __esm(() => {
1675
2440
  opera11Regex = / line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i;
1676
2441
  });
1677
2442
 
1678
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/node.mjs
2443
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/node.mjs
1679
2444
  function filenameIsInApp(filename, isNative = false) {
1680
2445
  const isInternal = isNative || filename && !filename.startsWith("/") && !filename.match(/^[A-Z]:/) && !filename.startsWith(".") && !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//);
1681
2446
  return !isInternal && filename !== undefined && !filename.includes("node_modules/");
@@ -1683,7 +2448,7 @@ function filenameIsInApp(filename, isNative = false) {
1683
2448
  function _parseIntOrUndefined(input) {
1684
2449
  return parseInt(input || "", 10) || undefined;
1685
2450
  }
1686
- var FILENAME_MATCH, FULL_MATCH, nodeStackLineParser = (line, platform) => {
2451
+ var FILENAME_MATCH, FULL_MATCH, PROMISE_COMBINATOR, PROMISE_INDEX, PROMISE_FRAME_FILENAME = "node:internal/promise", nodeStackLineParser = (line, platform) => {
1687
2452
  const lineMatch = line.match(FULL_MATCH);
1688
2453
  if (lineMatch) {
1689
2454
  let object;
@@ -1725,6 +2490,8 @@ var FILENAME_MATCH, FULL_MATCH, nodeStackLineParser = (line, platform) => {
1725
2490
  filename = filename.slice(1);
1726
2491
  if (!filename && lineMatch[5] && !isNative)
1727
2492
  filename = lineMatch[5];
2493
+ if (PROMISE_COMBINATOR.test(functionName) && PROMISE_INDEX.test(filename || ""))
2494
+ filename = PROMISE_FRAME_FILENAME;
1728
2495
  return {
1729
2496
  filename: filename ? decodeURI(filename) : undefined,
1730
2497
  module: undefined,
@@ -1745,9 +2512,11 @@ var init_node = __esm(() => {
1745
2512
  init_base();
1746
2513
  FILENAME_MATCH = /^\s*[-]{4,}$/;
1747
2514
  FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;
2515
+ PROMISE_COMBINATOR = /^Promise\.(?:all|any)$/;
2516
+ PROMISE_INDEX = /^index \d+$/;
1748
2517
  });
1749
2518
 
1750
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/index.mjs
2519
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/index.mjs
1751
2520
  function reverseAndStripFrames(stack) {
1752
2521
  if (!stack.length)
1753
2522
  return [];
@@ -1801,7 +2570,7 @@ var init_parsers = __esm(() => {
1801
2570
  WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
1802
2571
  });
1803
2572
 
1804
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/dom-exception-coercer.mjs
2573
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/dom-exception-coercer.mjs
1805
2574
  class DOMExceptionCoercer {
1806
2575
  match(err) {
1807
2576
  return this.isDOMException(err) || this.isDOMError(err);
@@ -1835,18 +2604,20 @@ var init_dom_exception_coercer = __esm(() => {
1835
2604
  init_utils();
1836
2605
  });
1837
2606
 
1838
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/error-coercer.mjs
2607
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/error-coercer.mjs
1839
2608
  class ErrorCoercer {
1840
2609
  match(err) {
1841
- return isPlainError(err);
2610
+ return isError(err);
1842
2611
  }
1843
2612
  coerce(err, ctx) {
2613
+ const stack = this.getStack(err);
2614
+ const synthetic = stack === undefined;
1844
2615
  return {
1845
2616
  type: this.getType(err),
1846
2617
  value: this.getMessage(err, ctx),
1847
- stack: this.getStack(err),
2618
+ stack: stack ?? ctx.syntheticException?.stack,
1848
2619
  cause: err.cause ? ctx.next(err.cause) : undefined,
1849
- synthetic: false
2620
+ synthetic
1850
2621
  };
1851
2622
  }
1852
2623
  getType(err) {
@@ -1863,32 +2634,48 @@ class ErrorCoercer {
1863
2634
  }
1864
2635
  }
1865
2636
  var init_error_coercer = __esm(() => {
1866
- init_utils();
2637
+ init_type_utils();
1867
2638
  });
1868
2639
 
1869
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/error-event-coercer.mjs
2640
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/error-event-coercer.mjs
1870
2641
  class ErrorEventCoercer {
1871
2642
  constructor() {}
1872
2643
  match(err) {
1873
- return isErrorEvent(err) && err.error != null;
2644
+ if (!isErrorEvent(err))
2645
+ return false;
2646
+ const errorEvent = err;
2647
+ return errorEvent.error != null || this._hasUsableMessage(errorEvent);
1874
2648
  }
1875
2649
  coerce(err, ctx) {
1876
- const exceptionLike = ctx.apply(err.error);
1877
- if (!exceptionLike)
1878
- return {
1879
- type: "ErrorEvent",
1880
- value: err.message,
1881
- stack: ctx.syntheticException?.stack,
1882
- synthetic: true
1883
- };
1884
- return exceptionLike;
2650
+ if (err.error != null)
2651
+ return ctx.apply(err.error);
2652
+ const exceptionLike = ctx.apply(err.message);
2653
+ return {
2654
+ ...exceptionLike,
2655
+ stack: this._buildLocationStack(err) ?? exceptionLike.stack,
2656
+ synthetic: true
2657
+ };
2658
+ }
2659
+ _hasUsableMessage(err) {
2660
+ return isString(err.message) && err.message.length > 0;
2661
+ }
2662
+ _buildLocationStack(err) {
2663
+ const location = err;
2664
+ const lineno = location.lineno ?? 0;
2665
+ const colno = location.colno ?? 0;
2666
+ if (!isString(location.filename) || location.filename.length === 0)
2667
+ return;
2668
+ if (lineno === 0)
2669
+ return;
2670
+ return `Error
2671
+ at ${location.filename}:${lineno}:${colno}`;
1885
2672
  }
1886
2673
  }
1887
2674
  var init_error_event_coercer = __esm(() => {
1888
2675
  init_utils();
1889
2676
  });
1890
2677
 
1891
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/string-coercer.mjs
2678
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/string-coercer.mjs
1892
2679
  class StringCoercer {
1893
2680
  match(input) {
1894
2681
  return typeof input == "string";
@@ -1921,7 +2708,7 @@ var init_string_coercer = __esm(() => {
1921
2708
  ERROR_TYPES_PATTERN = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;
1922
2709
  });
1923
2710
 
1924
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/types.mjs
2711
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/types.mjs
1925
2712
  var severityLevels;
1926
2713
  var init_types2 = __esm(() => {
1927
2714
  severityLevels = [
@@ -1934,7 +2721,7 @@ var init_types2 = __esm(() => {
1934
2721
  ];
1935
2722
  });
1936
2723
 
1937
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/utils.mjs
2724
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/utils.mjs
1938
2725
  function extractExceptionKeysForMessage(err, maxLength = 40) {
1939
2726
  const keys = Object.keys(err);
1940
2727
  keys.sort();
@@ -1952,7 +2739,7 @@ function extractExceptionKeysForMessage(err, maxLength = 40) {
1952
2739
  }
1953
2740
  var init_utils2 = () => {};
1954
2741
 
1955
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.mjs
2742
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.mjs
1956
2743
  class ObjectCoercer {
1957
2744
  match(candidate) {
1958
2745
  return typeof candidate == "object" && candidate !== null;
@@ -1964,13 +2751,16 @@ class ObjectCoercer {
1964
2751
  return {
1965
2752
  type: this.getType(candidate),
1966
2753
  value: this.getValue(candidate),
1967
- stack: ctx.syntheticException?.stack,
2754
+ stack: this.getStack(candidate) ?? ctx.syntheticException?.stack,
1968
2755
  level: this.isSeverityLevel(candidate.level) ? candidate.level : "error",
1969
2756
  synthetic: true
1970
2757
  };
1971
2758
  }
1972
2759
  getType(err) {
1973
- return isEvent(err) ? err.constructor.name : "Error";
2760
+ if (isEvent(err))
2761
+ return err.constructor.name;
2762
+ const name = "name" in err ? err.name : undefined;
2763
+ return isString(name) && !isEmptyString(name) ? name : "Error";
1974
2764
  }
1975
2765
  getValue(err) {
1976
2766
  if ("name" in err && typeof err.name == "string") {
@@ -1988,6 +2778,15 @@ class ObjectCoercer {
1988
2778
  isSeverityLevel(x) {
1989
2779
  return isString(x) && !isEmptyString(x) && severityLevels.indexOf(x) >= 0;
1990
2780
  }
2781
+ getStack(candidate) {
2782
+ try {
2783
+ if (isString(candidate.stacktrace) && candidate.stacktrace.length > 0)
2784
+ return candidate.stacktrace;
2785
+ return isString(candidate.stack) && candidate.stack.length > 0 ? candidate.stack : undefined;
2786
+ } catch {
2787
+ return;
2788
+ }
2789
+ }
1991
2790
  getErrorPropertyFromObject(obj) {
1992
2791
  for (const prop in obj)
1993
2792
  if (Object.prototype.hasOwnProperty.call(obj, prop)) {
@@ -2011,7 +2810,7 @@ var init_object_coercer = __esm(() => {
2011
2810
  init_utils2();
2012
2811
  });
2013
2812
 
2014
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/event-coercer.mjs
2813
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/event-coercer.mjs
2015
2814
  class EventCoercer {
2016
2815
  match(err) {
2017
2816
  return isEvent(err);
@@ -2031,7 +2830,7 @@ var init_event_coercer = __esm(() => {
2031
2830
  init_utils2();
2032
2831
  });
2033
2832
 
2034
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/primitive-coercer.mjs
2833
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/primitive-coercer.mjs
2035
2834
  class PrimitiveCoercer {
2036
2835
  match(candidate) {
2037
2836
  return isPrimitive(candidate);
@@ -2049,7 +2848,7 @@ var init_primitive_coercer = __esm(() => {
2049
2848
  init_utils();
2050
2849
  });
2051
2850
 
2052
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/promise-rejection-event.mjs
2851
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/promise-rejection-event.mjs
2053
2852
  class PromiseRejectionEventCoercer {
2054
2853
  match(err) {
2055
2854
  return isBuiltin(err, "PromiseRejectionEvent") || this.isCustomEventWrappingRejection(err);
@@ -2089,7 +2888,7 @@ var init_promise_rejection_event = __esm(() => {
2089
2888
  init_utils();
2090
2889
  });
2091
2890
 
2092
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/index.mjs
2891
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/index.mjs
2093
2892
  var init_coercers = __esm(() => {
2094
2893
  init_dom_exception_coercer();
2095
2894
  init_error_coercer();
@@ -2101,7 +2900,7 @@ var init_coercers = __esm(() => {
2101
2900
  init_promise_rejection_event();
2102
2901
  });
2103
2902
 
2104
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/utils.mjs
2903
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/utils.mjs
2105
2904
  class ReduceableCache {
2106
2905
  constructor(_maxSize) {
2107
2906
  this._maxSize = _maxSize;
@@ -2128,7 +2927,7 @@ class ReduceableCache {
2128
2927
  }
2129
2928
  var init_utils3 = () => {};
2130
2929
 
2131
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/exception-steps.mjs
2930
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/exception-steps.mjs
2132
2931
  function resolveExceptionStepsConfig(config) {
2133
2932
  if (!config)
2134
2933
  return {
@@ -2211,9 +3010,12 @@ function normalizePositiveInteger(input, fallback) {
2211
3010
  return normalized;
2212
3011
  }
2213
3012
  function normalizeAndSerializeStep(step) {
2214
- const json = safeStringify(step);
2215
- if (!json)
3013
+ let json;
3014
+ try {
3015
+ json = safeJsonStringify(step);
3016
+ } catch {
2216
3017
  return;
3018
+ }
2217
3019
  try {
2218
3020
  const parsed = JSON.parse(json);
2219
3021
  if (!isObject(parsed))
@@ -2233,33 +3035,6 @@ function normalizeAndSerializeStep(step) {
2233
3035
  return;
2234
3036
  }
2235
3037
  }
2236
- function safeStringify(value) {
2237
- const seen = new WeakSet;
2238
- try {
2239
- return JSON.stringify(value, (_key, replacementValue) => {
2240
- if (typeof replacementValue == "bigint")
2241
- return replacementValue.toString();
2242
- if (typeof replacementValue == "function" || typeof replacementValue == "symbol")
2243
- return;
2244
- if (replacementValue instanceof Date)
2245
- return replacementValue.toISOString();
2246
- if (replacementValue instanceof Error)
2247
- return {
2248
- name: replacementValue.name,
2249
- message: replacementValue.message,
2250
- stack: replacementValue.stack
2251
- };
2252
- if (replacementValue && typeof replacementValue == "object") {
2253
- if (seen.has(replacementValue))
2254
- return "[Circular]";
2255
- seen.add(replacementValue);
2256
- }
2257
- return replacementValue;
2258
- });
2259
- } catch {
2260
- return;
2261
- }
2262
- }
2263
3038
  function getUtf8ByteLength(value) {
2264
3039
  if (typeof TextEncoder != "undefined")
2265
3040
  return new TextEncoder().encode(value).length;
@@ -2290,34 +3065,42 @@ var init_exception_steps = __esm(() => {
2290
3065
  };
2291
3066
  });
2292
3067
 
2293
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/index.mjs
3068
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/release.mjs
3069
+ function getInjectedReleaseId() {
3070
+ const injected = globalThis._posthogReleaseId;
3071
+ return typeof injected == "string" && injected.length > 0 ? injected : undefined;
3072
+ }
3073
+ var init_release = () => {};
3074
+
3075
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/index.mjs
2294
3076
  var exports_error_tracking = {};
2295
3077
  __export(exports_error_tracking, {
2296
- winjsStackLineParser: () => winjsStackLineParser,
2297
- stripReservedExceptionStepFields: () => stripReservedExceptionStepFields,
2298
- reverseAndStripFrames: () => reverseAndStripFrames,
2299
- resolveExceptionStepsConfig: () => resolveExceptionStepsConfig,
2300
- opera11StackLineParser: () => opera11StackLineParser,
2301
- opera10StackLineParser: () => opera10StackLineParser,
2302
- nodeStackLineParser: () => nodeStackLineParser,
2303
- getUtf8ByteLength: () => getUtf8ByteLength,
2304
- geckoStackLineParser: () => geckoStackLineParser,
2305
- createStackParser: () => createStackParser,
2306
- createDefaultStackParser: () => createDefaultStackParser,
2307
- chromeStackLineParser: () => chromeStackLineParser,
2308
- StringCoercer: () => StringCoercer,
2309
- ReduceableCache: () => ReduceableCache,
2310
- PromiseRejectionEventCoercer: () => PromiseRejectionEventCoercer,
2311
- PrimitiveCoercer: () => PrimitiveCoercer,
2312
- ObjectCoercer: () => ObjectCoercer,
2313
- ExceptionStepsBuffer: () => ExceptionStepsBuffer,
2314
- EventCoercer: () => EventCoercer,
2315
- ErrorPropertiesBuilder: () => ErrorPropertiesBuilder,
2316
- ErrorEventCoercer: () => ErrorEventCoercer,
2317
- ErrorCoercer: () => ErrorCoercer,
2318
- EXCEPTION_STEP_INTERNAL_FIELDS: () => EXCEPTION_STEP_INTERNAL_FIELDS,
3078
+ DEFAULT_EXCEPTION_STEPS_CONFIG: () => DEFAULT_EXCEPTION_STEPS_CONFIG,
2319
3079
  DOMExceptionCoercer: () => DOMExceptionCoercer,
2320
- DEFAULT_EXCEPTION_STEPS_CONFIG: () => DEFAULT_EXCEPTION_STEPS_CONFIG
3080
+ EXCEPTION_STEP_INTERNAL_FIELDS: () => EXCEPTION_STEP_INTERNAL_FIELDS,
3081
+ ErrorCoercer: () => ErrorCoercer,
3082
+ ErrorEventCoercer: () => ErrorEventCoercer,
3083
+ ErrorPropertiesBuilder: () => ErrorPropertiesBuilder,
3084
+ EventCoercer: () => EventCoercer,
3085
+ ExceptionStepsBuffer: () => ExceptionStepsBuffer,
3086
+ ObjectCoercer: () => ObjectCoercer,
3087
+ PrimitiveCoercer: () => PrimitiveCoercer,
3088
+ PromiseRejectionEventCoercer: () => PromiseRejectionEventCoercer,
3089
+ ReduceableCache: () => ReduceableCache,
3090
+ StringCoercer: () => StringCoercer,
3091
+ chromeStackLineParser: () => chromeStackLineParser,
3092
+ createDefaultStackParser: () => createDefaultStackParser,
3093
+ createStackParser: () => createStackParser,
3094
+ geckoStackLineParser: () => geckoStackLineParser,
3095
+ getInjectedReleaseId: () => getInjectedReleaseId,
3096
+ getUtf8ByteLength: () => getUtf8ByteLength,
3097
+ nodeStackLineParser: () => nodeStackLineParser,
3098
+ opera10StackLineParser: () => opera10StackLineParser,
3099
+ opera11StackLineParser: () => opera11StackLineParser,
3100
+ resolveExceptionStepsConfig: () => resolveExceptionStepsConfig,
3101
+ reverseAndStripFrames: () => reverseAndStripFrames,
3102
+ stripReservedExceptionStepFields: () => stripReservedExceptionStepFields,
3103
+ winjsStackLineParser: () => winjsStackLineParser
2321
3104
  });
2322
3105
  var init_error_tracking = __esm(() => {
2323
3106
  init_error_properties_builder();
@@ -2325,15 +3108,19 @@ var init_error_tracking = __esm(() => {
2325
3108
  init_coercers();
2326
3109
  init_utils3();
2327
3110
  init_exception_steps();
3111
+ init_release();
2328
3112
  });
2329
3113
 
2330
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/posthog-core-stateless.mjs
3114
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/posthog-core-stateless.mjs
2331
3115
  async function logFlushError(err) {
2332
3116
  if (err instanceof PostHogFetchHttpError) {
2333
3117
  let text = "";
2334
3118
  try {
2335
3119
  text = await err.text;
2336
- } catch {}
3120
+ } catch {
3121
+ if (err.bodyReadTimedOut)
3122
+ text = "<response body read timed out>";
3123
+ }
2337
3124
  console.error(`Error while flushing PostHog: message=${err.message}, response body=${text}`, err);
2338
3125
  } else
2339
3126
  console.error("Error while flushing PostHog", err);
@@ -2345,9 +3132,26 @@ function isPostHogFetchError(err) {
2345
3132
  function isPostHogFetchNetworkError(err) {
2346
3133
  return err instanceof PostHogFetchNetworkError;
2347
3134
  }
3135
+ function isRetryableFlagsFetchError(err) {
3136
+ if (err instanceof PostHogFetchHttpError)
3137
+ return err.status === 502 || err.status === 504;
3138
+ if (!(err instanceof PostHogFetchNetworkError))
3139
+ return false;
3140
+ const cause = err.error;
3141
+ const code = cause?.code ?? cause?.cause?.code;
3142
+ return code !== "ECONNREFUSED";
3143
+ }
2348
3144
  function isPostHogFetchContentTooLargeError(err) {
2349
3145
  return typeof err == "object" && err instanceof PostHogFetchHttpError && err.status === 413;
2350
3146
  }
3147
+ function isPostHogFetchRetryableError(err) {
3148
+ if (err instanceof PostHogFetchHttpError)
3149
+ return err.status === 408 || err.status === 429 || err.status >= 500;
3150
+ return isPostHogFetchNetworkError(err);
3151
+ }
3152
+ function isPostHogEventProperties(value) {
3153
+ return value !== null && typeof value == "object" && !Array.isArray(value);
3154
+ }
2351
3155
 
2352
3156
  class PostHogCoreStateless {
2353
3157
  getErrorPropertiesBuilder() {
@@ -2365,6 +3169,9 @@ class PostHogCoreStateless {
2365
3169
  }
2366
3170
  constructor(apiKey, options = {}) {
2367
3171
  this.flushPromise = null;
3172
+ this.pendingFlushPromise = null;
3173
+ this.flushPromises = new Set;
3174
+ this._dequeuedMessagesCount = 0;
2368
3175
  this.shutdownPromise = null;
2369
3176
  this.promiseQueue = new PromiseQueue;
2370
3177
  this._events = new SimpleEventEmitter;
@@ -2387,10 +3194,11 @@ class PostHogCoreStateless {
2387
3194
  this._retryOptions = {
2388
3195
  retryCount: options.fetchRetryCount ?? 3,
2389
3196
  retryDelay: options.fetchRetryDelay ?? 3000,
2390
- retryCheck: isPostHogFetchError
3197
+ retryCheck: isPostHogFetchRetryableError
2391
3198
  };
2392
3199
  this.requestTimeout = options.requestTimeout ?? 1e4;
2393
3200
  this.featureFlagsRequestTimeoutMs = options.featureFlagsRequestTimeoutMs ?? 3000;
3201
+ this.featureFlagsRequestMaxRetries = options.featureFlagsRequestMaxRetries ?? 1;
2394
3202
  this.remoteConfigRequestTimeoutMs = options.remoteConfigRequestTimeoutMs ?? 3000;
2395
3203
  this.disableGeoip = options.disableGeoip ?? true;
2396
3204
  this.disabled = (options.disabled ?? false) || missingApiKey;
@@ -2452,15 +3260,23 @@ class PostHogCoreStateless {
2452
3260
  return this.disabled;
2453
3261
  }
2454
3262
  buildPayload(payload) {
3263
+ const userProperties = payload.properties || {};
3264
+ let properties = {
3265
+ ...userProperties,
3266
+ ...this.getCommonEventProperties()
3267
+ };
3268
+ applyCallerFeatureFlagOverrides(properties, userProperties);
3269
+ if (payload.event === "$feature_flag_called" && properties.$feature_flag_has_experiment === false && this.isMinimalFlagCalledEventsEnabled())
3270
+ properties = minimizeFlagCalledEventProperties(properties);
2455
3271
  return {
2456
3272
  distinct_id: payload.distinct_id,
2457
3273
  event: payload.event,
2458
- properties: {
2459
- ...payload.properties || {},
2460
- ...this.getCommonEventProperties()
2461
- }
3274
+ properties
2462
3275
  };
2463
3276
  }
3277
+ isMinimalFlagCalledEventsEnabled() {
3278
+ return false;
3279
+ }
2464
3280
  addPendingPromise(promise) {
2465
3281
  return this.promiseQueue.add(promise);
2466
3282
  }
@@ -2545,6 +3361,19 @@ class PostHogCoreStateless {
2545
3361
  this.enqueue("capture", payload, options);
2546
3362
  });
2547
3363
  }
3364
+ async groupIdentifyStatelessImmediate(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
3365
+ const payload = this.buildPayload({
3366
+ distinct_id: distinctId || `$${groupType}_${groupKey}`,
3367
+ event: "$groupidentify",
3368
+ properties: {
3369
+ $group_type: groupType,
3370
+ $group_key: groupKey,
3371
+ $group_set: groupProperties || {},
3372
+ ...eventProperties || {}
3373
+ }
3374
+ });
3375
+ await this.sendImmediate("capture", payload, options);
3376
+ }
2548
3377
  async getRemoteConfig() {
2549
3378
  await this._initPromise;
2550
3379
  let host = this.host;
@@ -2561,8 +3390,11 @@ class PostHogCoreStateless {
2561
3390
  }
2562
3391
  };
2563
3392
  return this.fetchWithRetry(url, fetchOptions, {
3393
+ type: "required",
3394
+ consume: (response) => response.json()
3395
+ }, {
2564
3396
  retryCount: 0
2565
- }, this.remoteConfigRequestTimeoutMs).then((response) => response.json()).catch((error) => {
3397
+ }, this.remoteConfigRequestTimeoutMs).catch((error) => {
2566
3398
  this._logger.error("Remote config could not be loaded", error);
2567
3399
  this._events.emit("error", error);
2568
3400
  });
@@ -2593,8 +3425,12 @@ class PostHogCoreStateless {
2593
3425
  };
2594
3426
  this._logger.info("Flags URL", url);
2595
3427
  return this.fetchWithRetry(url, fetchOptions, {
2596
- retryCount: 0
2597
- }, this.featureFlagsRequestTimeoutMs).then((response) => response.json()).then((response) => ({
3428
+ type: "required",
3429
+ consume: (response) => response.json()
3430
+ }, {
3431
+ retryCount: this.featureFlagsRequestMaxRetries,
3432
+ retryCheck: isRetryableFlagsFetchError
3433
+ }, this.featureFlagsRequestTimeoutMs).then((response) => ({
2598
3434
  success: true,
2599
3435
  response: normalizeFlagsResponse(response)
2600
3436
  })).catch((error) => {
@@ -2694,9 +3530,9 @@ class PostHogCoreStateless {
2694
3530
  }
2695
3531
  async getFeatureFlagDetailsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
2696
3532
  await this._initPromise;
2697
- const extraPayload = {};
2698
- if (disableGeoip ?? this.disableGeoip)
2699
- extraPayload["geoip_disable"] = true;
3533
+ const extraPayload = {
3534
+ geoip_disable: disableGeoip ?? this.disableGeoip
3535
+ };
2700
3536
  if (flagKeysToEvaluate)
2701
3537
  extraPayload["flag_keys_to_evaluate"] = flagKeysToEvaluate;
2702
3538
  const result = await this.getFlags(distinctId, groups, personProperties, groupProperties, extraPayload);
@@ -2733,15 +3569,18 @@ class PostHogCoreStateless {
2733
3569
  "Content-Type": "application/json"
2734
3570
  }
2735
3571
  };
2736
- const response = await this.fetchWithRetry(url, fetchOptions).then((response2) => {
2737
- if (response2.status !== 200 || !response2.json) {
2738
- const msg = `Surveys API could not be loaded: ${response2.status}`;
2739
- const error = new Error(msg);
2740
- this._logger.error(error);
2741
- this._events.emit("error", new Error(msg));
2742
- return;
3572
+ const response = await this.fetchWithRetry(url, fetchOptions, {
3573
+ type: "required",
3574
+ consume: (response2) => {
3575
+ if (response2.status !== 200 || !response2.json) {
3576
+ const msg = `Surveys API could not be loaded: ${response2.status}`;
3577
+ const error = new Error(msg);
3578
+ this._logger.error(error);
3579
+ this._events.emit("error", new Error(msg));
3580
+ return Promise.resolve(undefined);
3581
+ }
3582
+ return response2.json();
2743
3583
  }
2744
- return response2.json();
2745
3584
  }).catch((error) => {
2746
3585
  this._logger.error("Surveys API could not be loaded", error);
2747
3586
  this._events.emit("error", error);
@@ -2778,23 +3617,39 @@ class PostHogCoreStateless {
2778
3617
  return message;
2779
3618
  }
2780
3619
  async flushStorage() {}
2781
- enqueue(type, _message, options) {
3620
+ getQueueRouteKey(_message) {
3621
+ return DEFAULT_QUEUE_ROUTE;
3622
+ }
3623
+ persistedQueueKeyForRoute(_route) {
3624
+ return types_PostHogPersistedProperty.Queue;
3625
+ }
3626
+ getActiveQueueRoutes() {
3627
+ return [
3628
+ DEFAULT_QUEUE_ROUTE
3629
+ ];
3630
+ }
3631
+ getRouteQueue(route) {
3632
+ return this.getPersistedProperty(this.persistedQueueKeyForRoute(route)) || [];
3633
+ }
3634
+ enqueue(type, _message, options, explicitRoute) {
2782
3635
  this.wrap(() => {
2783
3636
  if (this.optedOut)
2784
3637
  return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
2785
- let message = this.prepareMessage(type, _message, options);
3638
+ let message = this.prepareMessage(_message, options);
2786
3639
  message = this.processBeforeEnqueue(message);
2787
3640
  if (message === null)
2788
3641
  return;
2789
- const queue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
3642
+ message = this.normalizeMessage(message);
3643
+ const queueKey = this.persistedQueueKeyForRoute(explicitRoute ?? this.getQueueRouteKey(message));
3644
+ const queue = this.getPersistedProperty(queueKey) || [];
2790
3645
  if (queue.length >= this.maxQueueSize) {
2791
3646
  queue.shift();
2792
- this._logger.info("Queue is full, the oldest event is dropped.");
3647
+ this._logger.warn("Queue is full, the oldest event is dropped.");
2793
3648
  }
2794
3649
  queue.push({
2795
3650
  message
2796
3651
  });
2797
- this.setPersistedProperty(types_PostHogPersistedProperty.Queue, queue);
3652
+ this.setPersistedProperty(queueKey, queue);
2798
3653
  this._events.emit(type, message);
2799
3654
  if (queue.length >= this.flushAt)
2800
3655
  this.flushBackground();
@@ -2802,61 +3657,63 @@ class PostHogCoreStateless {
2802
3657
  this._flushTimer = safeSetTimeout(() => this.flushBackground(), this.flushInterval);
2803
3658
  });
2804
3659
  }
2805
- async sendImmediate(type, _message, options) {
3660
+ async sendImmediate(type, _message, options, explicitRoute) {
2806
3661
  if (this.disabled)
2807
3662
  return void this._logger.warn("The client is disabled");
2808
3663
  if (!this._isInitialized)
2809
3664
  await this._initPromise;
2810
3665
  if (this.optedOut)
2811
3666
  return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
2812
- let message = this.prepareMessage(type, _message, options);
3667
+ let message = this.prepareMessage(_message, options);
2813
3668
  message = this.processBeforeEnqueue(message);
2814
3669
  if (message === null)
2815
3670
  return;
2816
- const data = {
2817
- api_key: this.apiKey,
2818
- batch: [
2819
- message
2820
- ],
2821
- sent_at: currentISOTime()
2822
- };
2823
- if (this.historicalMigration)
2824
- data.historical_migration = true;
2825
- const payload = JSON.stringify(data);
2826
- const url = `${this.host}/batch/`;
2827
- const gzippedPayload = this.disableCompression ? null : await gzipCompress(payload, this.isDebug);
2828
- const fetchOptions = {
2829
- method: "POST",
2830
- headers: {
2831
- ...this.getCustomHeaders(),
2832
- "Content-Type": "application/json",
2833
- ...gzippedPayload !== null && {
2834
- "Content-Encoding": "gzip"
2835
- }
2836
- },
2837
- body: gzippedPayload || payload
2838
- };
3671
+ message = this.normalizeMessage(message);
2839
3672
  try {
2840
- const response = await this.fetchWithRetry(url, fetchOptions);
2841
- await response.body?.cancel()?.catch(() => {});
3673
+ await this.sendBatch([
3674
+ message
3675
+ ], undefined, explicitRoute ?? this.getQueueRouteKey(message));
2842
3676
  } catch (err) {
2843
3677
  this._events.emit("error", err);
2844
3678
  }
2845
3679
  }
2846
- prepareMessage(type, _message, options) {
3680
+ normalizeMessage(message) {
3681
+ const { type: _type, library, library_version, ...sanitizedMessage } = message;
3682
+ let properties = isPostHogEventProperties(sanitizedMessage.properties) ? sanitizedMessage.properties : undefined;
3683
+ if (library !== undefined && properties?.$lib === undefined)
3684
+ properties = {
3685
+ ...properties || {},
3686
+ $lib: library
3687
+ };
3688
+ if (library_version !== undefined && properties?.$lib_version === undefined)
3689
+ properties = {
3690
+ ...properties || {},
3691
+ $lib_version: library_version
3692
+ };
3693
+ if (properties)
3694
+ sanitizedMessage.properties = properties;
3695
+ sanitizedMessage.uuid = getEventUuid(sanitizedMessage.uuid, uuidv7);
3696
+ return sanitizedMessage;
3697
+ }
3698
+ normalizeTimestampForWire(timestamp) {
3699
+ const parsedTimestamp = timestamp instanceof Date ? timestamp : typeof timestamp == "string" ? new Date(timestamp) : null;
3700
+ if (!parsedTimestamp || Number.isNaN(parsedTimestamp.getTime()))
3701
+ return timestamp;
3702
+ const normalized = parsedTimestamp.toISOString();
3703
+ const fractionalSeconds = typeof timestamp == "string" ? timestamp.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1] : undefined;
3704
+ return fractionalSeconds && fractionalSeconds.length > 3 ? normalized.replace(/\.\d{3}Z$/, `.${fractionalSeconds}Z`) : normalized;
3705
+ }
3706
+ prepareMessage(_message, options) {
2847
3707
  const message = {
2848
3708
  ..._message,
2849
- type,
2850
- library: this.getLibraryId(),
2851
- library_version: this.getLibraryVersion(),
2852
3709
  timestamp: options?.timestamp ? options?.timestamp : currentISOTime(),
2853
- uuid: options?.uuid ? options.uuid : uuidv7()
3710
+ uuid: getEventUuid(options?.uuid, uuidv7)
2854
3711
  };
2855
3712
  const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip;
2856
3713
  if (addGeoipDisableProperty) {
2857
- if (!message.properties)
3714
+ if (!isPostHogEventProperties(message.properties))
2858
3715
  message.properties = {};
2859
- message["properties"]["$geoip_disable"] = true;
3716
+ message.properties["$geoip_disable"] = true;
2860
3717
  }
2861
3718
  if (message.distinctId) {
2862
3719
  message.distinct_id = message.distinctId;
@@ -2871,21 +3728,64 @@ class PostHogCoreStateless {
2871
3728
  }
2872
3729
  }
2873
3730
  flushBackground() {
3731
+ if (this.pendingFlushPromise)
3732
+ return;
2874
3733
  this.flush().catch(async (err) => {
2875
3734
  await logFlushError(err);
2876
3735
  });
2877
3736
  }
2878
- async flush() {
3737
+ async waitForPendingPromises(maxPromiseId, ignoredPromises = []) {
3738
+ const ignoredPendingPromises = ignoredPromises.filter((promise) => !!promise);
3739
+ let iteration = 0;
3740
+ while (true) {
3741
+ const promises = this.promiseQueue.getPromises([
3742
+ ...ignoredPendingPromises,
3743
+ ...this.flushPromises
3744
+ ], maxPromiseId);
3745
+ if (promises.length === 0)
3746
+ return;
3747
+ if (iteration > 0)
3748
+ this._logger.debug(`flush() re-checking ${promises.length} pending promise(s) before flushing`);
3749
+ await Promise.all(promises.map((promise) => promise.catch(() => {})));
3750
+ iteration++;
3751
+ }
3752
+ }
3753
+ flushWithPendingPromises() {
3754
+ return this.flushInternal(true);
3755
+ }
3756
+ flush() {
3757
+ return this.flushInternal(false);
3758
+ }
3759
+ flushInternal(waitForPendingPromises) {
2879
3760
  if (this.disabled)
2880
- return;
2881
- const nextFlushPromise = allSettled([
2882
- this.flushPromise
2883
- ]).then(() => this._flush());
3761
+ return Promise.resolve();
3762
+ if (!waitForPendingPromises && this.pendingFlushPromise)
3763
+ return this.pendingFlushPromise;
3764
+ const previousFlushPromise = this.flushPromise;
3765
+ const maxPromiseId = this.promiseQueue.maxId;
3766
+ const nextFlushPromise = Promise.resolve().then(() => {
3767
+ if (waitForPendingPromises)
3768
+ return this.waitForPendingPromises(maxPromiseId, [
3769
+ previousFlushPromise,
3770
+ nextFlushPromise
3771
+ ]);
3772
+ }).then(() => allSettled([
3773
+ previousFlushPromise
3774
+ ])).then(() => {
3775
+ if (this.pendingFlushPromise === nextFlushPromise)
3776
+ this.pendingFlushPromise = null;
3777
+ return this._flush();
3778
+ });
3779
+ this.pendingFlushPromise = nextFlushPromise;
2884
3780
  this.flushPromise = nextFlushPromise;
3781
+ this.flushPromises.add(nextFlushPromise);
2885
3782
  this.addPendingPromise(nextFlushPromise);
2886
3783
  allSettled([
2887
3784
  nextFlushPromise
2888
3785
  ]).then(() => {
3786
+ this.flushPromises.delete(nextFlushPromise);
3787
+ if (this.pendingFlushPromise === nextFlushPromise)
3788
+ this.pendingFlushPromise = null;
2889
3789
  if (this.flushPromise === nextFlushPromise)
2890
3790
  this.flushPromise = null;
2891
3791
  });
@@ -2898,55 +3798,102 @@ class PostHogCoreStateless {
2898
3798
  headers["User-Agent"] = customUserAgent;
2899
3799
  return headers;
2900
3800
  }
3801
+ compressPayload(payload) {
3802
+ return gzipCompress(payload, this.isDebug);
3803
+ }
3804
+ getBatchEndpointPath(_route) {
3805
+ return "/batch/";
3806
+ }
3807
+ async sendBatch(batchMessages, retryOptions, route = DEFAULT_QUEUE_ROUTE) {
3808
+ const data = {
3809
+ api_key: this.apiKey,
3810
+ batch: batchMessages.map((message) => {
3811
+ if (!message)
3812
+ return message;
3813
+ const timestamp = this.normalizeTimestampForWire(message.timestamp);
3814
+ return timestamp === message.timestamp ? message : {
3815
+ ...message,
3816
+ timestamp
3817
+ };
3818
+ }),
3819
+ sent_at: currentISOTime()
3820
+ };
3821
+ if (this.historicalMigration)
3822
+ data.historical_migration = true;
3823
+ const payload = safeJsonStringify(data);
3824
+ const url = `${this.host}${this.getBatchEndpointPath(route)}`;
3825
+ const gzippedPayload = this.disableCompression ? null : await this.compressPayload(payload);
3826
+ const fetchOptions = {
3827
+ method: "POST",
3828
+ headers: {
3829
+ ...this.getCustomHeaders(),
3830
+ "Content-Type": "application/json",
3831
+ ...gzippedPayload !== null && {
3832
+ "Content-Encoding": "gzip"
3833
+ }
3834
+ },
3835
+ body: gzippedPayload || payload
3836
+ };
3837
+ await this.fetchWithRetry(url, fetchOptions, {
3838
+ type: "successful-write"
3839
+ }, retryOptions);
3840
+ }
2901
3841
  async _flush() {
2902
3842
  this.clearFlushTimer();
2903
3843
  await this._initPromise;
2904
- let queue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
2905
- if (!queue.length)
3844
+ const routes = this.getActiveQueueRoutes();
3845
+ if (!routes.some((route) => this.getRouteQueue(route).length > 0))
2906
3846
  return;
2907
3847
  const sentMessages = [];
3848
+ let firstError;
3849
+ for (const route of routes)
3850
+ try {
3851
+ await this._flushRoute(route, sentMessages);
3852
+ } catch (err) {
3853
+ if (firstError === undefined)
3854
+ firstError = err;
3855
+ }
3856
+ if (firstError !== undefined)
3857
+ throw firstError;
3858
+ this._events.emit("flush", sentMessages);
3859
+ }
3860
+ async _flushRoute(route, sentMessages) {
3861
+ const queueKey = this.persistedQueueKeyForRoute(route);
3862
+ let queue = this.getPersistedProperty(queueKey) || [];
3863
+ if (!queue.length)
3864
+ return;
2908
3865
  const originalQueueLength = queue.length;
2909
- while (queue.length > 0 && sentMessages.length < originalQueueLength) {
3866
+ let sentFromRoute = 0;
3867
+ while (queue.length > 0 && sentFromRoute < originalQueueLength) {
2910
3868
  const batchItems = queue.slice(0, this.maxBatchSize);
2911
- const batchMessages = batchItems.map((item) => item.message);
3869
+ const batchMessages = batchItems.map((item) => item.message === undefined ? item.message : this.normalizeMessage(item.message));
2912
3870
  const persistQueueChange = async () => {
2913
- const refreshedQueue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
2914
- const newQueue = refreshedQueue.slice(batchItems.length);
2915
- this.setPersistedProperty(types_PostHogPersistedProperty.Queue, newQueue);
3871
+ const refreshedQueue = this.getPersistedProperty(queueKey) || [];
3872
+ const remainingBatchItems = [
3873
+ ...batchItems
3874
+ ];
3875
+ const newQueue = refreshedQueue.filter((item) => {
3876
+ const itemUuid = item.message?.uuid;
3877
+ const batchItemIndex = remainingBatchItems.findIndex((batchItem) => batchItem === item || typeof itemUuid == "string" && itemUuid.length > 0 && batchItem.message?.uuid === itemUuid);
3878
+ if (batchItemIndex === -1)
3879
+ return true;
3880
+ remainingBatchItems.splice(batchItemIndex, 1);
3881
+ return false;
3882
+ });
3883
+ this.setPersistedProperty(queueKey, newQueue);
2916
3884
  queue = newQueue;
3885
+ this._dequeuedMessagesCount += batchItems.length;
2917
3886
  await this.flushStorage();
2918
3887
  };
2919
- const data = {
2920
- api_key: this.apiKey,
2921
- batch: batchMessages,
2922
- sent_at: currentISOTime()
2923
- };
2924
- if (this.historicalMigration)
2925
- data.historical_migration = true;
2926
- const payload = JSON.stringify(data);
2927
- const url = `${this.host}/batch/`;
2928
- const gzippedPayload = this.disableCompression ? null : await gzipCompress(payload, this.isDebug);
2929
- const fetchOptions = {
2930
- method: "POST",
2931
- headers: {
2932
- ...this.getCustomHeaders(),
2933
- "Content-Type": "application/json",
2934
- ...gzippedPayload !== null && {
2935
- "Content-Encoding": "gzip"
2936
- }
2937
- },
2938
- body: gzippedPayload || payload
2939
- };
2940
3888
  const retryOptions = {
2941
3889
  retryCheck: (err) => {
2942
3890
  if (isPostHogFetchContentTooLargeError(err))
2943
3891
  return false;
2944
- return isPostHogFetchError(err);
3892
+ return isPostHogFetchRetryableError(err);
2945
3893
  }
2946
3894
  };
2947
3895
  try {
2948
- const response = await this.fetchWithRetry(url, fetchOptions, retryOptions);
2949
- await response.body?.cancel()?.catch(() => {});
3896
+ await this.sendBatch(batchMessages, retryOptions, route);
2950
3897
  } catch (err) {
2951
3898
  if (isPostHogFetchContentTooLargeError(err) && batchMessages.length > 1) {
2952
3899
  this.maxBatchSize = Math.max(1, Math.floor(batchMessages.length / 2));
@@ -2960,18 +3907,67 @@ class PostHogCoreStateless {
2960
3907
  }
2961
3908
  await persistQueueChange();
2962
3909
  sentMessages.push(...batchMessages);
3910
+ sentFromRoute += batchMessages.length;
3911
+ }
3912
+ }
3913
+ async _sendLogsBatch(payload) {
3914
+ if (this.disabled)
3915
+ return {
3916
+ kind: "fatal",
3917
+ error: new Error("The client is disabled")
3918
+ };
3919
+ const serialized = JSON.stringify(payload);
3920
+ const url = `${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`;
3921
+ const gzippedPayload = this.disableCompression ? null : await this.compressPayload(serialized);
3922
+ const fetchOptions = {
3923
+ method: "POST",
3924
+ headers: {
3925
+ ...this.getCustomHeaders(),
3926
+ "Content-Type": "application/json",
3927
+ ...gzippedPayload !== null && {
3928
+ "Content-Encoding": "gzip"
3929
+ }
3930
+ },
3931
+ body: gzippedPayload || serialized
3932
+ };
3933
+ try {
3934
+ await this.fetchWithRetry(url, fetchOptions, {
3935
+ type: "successful-write"
3936
+ }, {
3937
+ retryCheck: (err) => {
3938
+ if (isPostHogFetchContentTooLargeError(err))
3939
+ return false;
3940
+ return isPostHogFetchRetryableError(err);
3941
+ }
3942
+ });
3943
+ return {
3944
+ kind: "ok"
3945
+ };
3946
+ } catch (err) {
3947
+ if (isPostHogFetchContentTooLargeError(err))
3948
+ return {
3949
+ kind: "too-large"
3950
+ };
3951
+ if (err instanceof PostHogFetchNetworkError)
3952
+ return {
3953
+ kind: "retry-later",
3954
+ error: err
3955
+ };
3956
+ return {
3957
+ kind: "fatal",
3958
+ error: err
3959
+ };
2963
3960
  }
2964
- this._events.emit("flush", sentMessages);
2965
3961
  }
2966
- async _sendLogsBatch(payload) {
3962
+ async _sendMetricsBatch(payload) {
2967
3963
  if (this.disabled)
2968
3964
  return {
2969
3965
  kind: "fatal",
2970
3966
  error: new Error("The client is disabled")
2971
3967
  };
2972
3968
  const serialized = JSON.stringify(payload);
2973
- const url = `${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`;
2974
- const gzippedPayload = this.disableCompression ? null : await gzipCompress(serialized, this.isDebug);
3969
+ const url = `${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`;
3970
+ const gzippedPayload = this.disableCompression ? null : await this.compressPayload(serialized);
2975
3971
  const fetchOptions = {
2976
3972
  method: "POST",
2977
3973
  headers: {
@@ -2985,10 +3981,12 @@ class PostHogCoreStateless {
2985
3981
  };
2986
3982
  try {
2987
3983
  await this.fetchWithRetry(url, fetchOptions, {
3984
+ type: "successful-write"
3985
+ }, {
2988
3986
  retryCheck: (err) => {
2989
3987
  if (isPostHogFetchContentTooLargeError(err))
2990
3988
  return false;
2991
- return isPostHogFetchError(err);
3989
+ return isPostHogFetchRetryableError(err);
2992
3990
  }
2993
3991
  });
2994
3992
  return {
@@ -2999,7 +3997,7 @@ class PostHogCoreStateless {
2999
3997
  return {
3000
3998
  kind: "too-large"
3001
3999
  };
3002
- if (err instanceof PostHogFetchNetworkError)
4000
+ if (isPostHogFetchRetryableError(err))
3003
4001
  return {
3004
4002
  kind: "retry-later",
3005
4003
  error: err
@@ -3010,41 +4008,106 @@ class PostHogCoreStateless {
3010
4008
  };
3011
4009
  }
3012
4010
  }
3013
- async fetchWithRetry(url, options, retryOptions, requestTimeout) {
4011
+ async fetchWithRetry(url, options, responseHandling, retryOptions, requestTimeout) {
3014
4012
  const body = options.body ? options.body : "";
3015
4013
  let reqByteLength = -1;
3016
4014
  try {
3017
- reqByteLength = body instanceof Blob ? body.size : Buffer.byteLength(body, STRING_FORMAT);
4015
+ reqByteLength = body instanceof Blob ? body.size : body instanceof Uint8Array ? body.byteLength : Buffer.byteLength(body, STRING_FORMAT);
3018
4016
  } catch {
3019
4017
  if (body instanceof Blob)
3020
4018
  reqByteLength = body.size;
4019
+ else if (body instanceof Uint8Array)
4020
+ reqByteLength = body.byteLength;
3021
4021
  else {
3022
4022
  const encoded = new TextEncoder().encode(body);
3023
4023
  reqByteLength = encoded.length;
3024
4024
  }
3025
4025
  }
4026
+ const retriableOptions = {
4027
+ ...this._retryOptions,
4028
+ ...retryOptions
4029
+ };
4030
+ let attempt = 0;
3026
4031
  return await retriable(async () => {
4032
+ attempt++;
3027
4033
  const ctrl = new AbortController;
3028
4034
  const timeoutMs = requestTimeout ?? this.requestTimeout;
3029
- const timer = safeSetTimeout(() => ctrl.abort(), timeoutMs);
3030
- let res = null;
4035
+ const requestDeadline = Date.now() + timeoutMs;
4036
+ let timer;
4037
+ const deadline = new Promise((_resolve, reject) => {
4038
+ timer = safeSetTimeout(() => {
4039
+ const timeoutError = new Error(`Request timed out after ${timeoutMs}ms`);
4040
+ timeoutError.name = "AbortError";
4041
+ reject(timeoutError);
4042
+ ctrl.abort(timeoutError);
4043
+ }, timeoutMs);
4044
+ });
4045
+ let res;
4046
+ let responseAccepted = false;
4047
+ let cancellation;
4048
+ const cancelBody = () => cancellation ??= (async () => {
4049
+ try {
4050
+ await res?.body?.cancel();
4051
+ } catch {}
4052
+ })();
3031
4053
  try {
3032
- res = await this.fetch(url, {
3033
- signal: ctrl.signal,
3034
- ...options
3035
- });
3036
- } catch (e) {
3037
- throw new PostHogFetchNetworkError(e);
4054
+ let fetchPromise;
4055
+ try {
4056
+ fetchPromise = this.fetch(url, {
4057
+ signal: ctrl.signal,
4058
+ ...options
4059
+ });
4060
+ } catch (e) {
4061
+ throw new PostHogFetchNetworkError(e);
4062
+ }
4063
+ fetchPromise.then((lateResponse) => {
4064
+ if (ctrl.signal.aborted && !responseAccepted)
4065
+ Promise.resolve(lateResponse.body?.cancel()).catch(() => {});
4066
+ }).catch(() => {});
4067
+ try {
4068
+ res = await Promise.race([
4069
+ fetchPromise,
4070
+ deadline
4071
+ ]);
4072
+ responseAccepted = true;
4073
+ } catch (e) {
4074
+ throw new PostHogFetchNetworkError(e);
4075
+ }
4076
+ const isNoCors = options.mode === "no-cors";
4077
+ if (!isNoCors && (res.status < 200 || res.status >= 400))
4078
+ throw new PostHogFetchHttpError(res, reqByteLength, requestDeadline, ctrl);
4079
+ if (responseHandling.type === "successful-write") {
4080
+ try {
4081
+ await Promise.race([
4082
+ cancelBody(),
4083
+ deadline
4084
+ ]);
4085
+ } catch {}
4086
+ return;
4087
+ }
4088
+ try {
4089
+ return await Promise.race([
4090
+ responseHandling.consume(res),
4091
+ deadline
4092
+ ]);
4093
+ } catch (e) {
4094
+ if (ctrl.signal.aborted)
4095
+ throw new PostHogFetchNetworkError(e);
4096
+ throw e;
4097
+ }
3038
4098
  } finally {
3039
4099
  clearTimeout(timer);
4100
+ if (ctrl.signal.aborted && res)
4101
+ cancelBody();
3040
4102
  }
3041
- const isNoCors = options.mode === "no-cors";
3042
- if (!isNoCors && (res.status < 200 || res.status >= 400))
3043
- throw new PostHogFetchHttpError(res, reqByteLength);
3044
- return res;
3045
4103
  }, {
3046
- ...this._retryOptions,
3047
- ...retryOptions
4104
+ ...retriableOptions,
4105
+ retryCheck: (error) => {
4106
+ const shouldRetry = retriableOptions.retryCheck(error);
4107
+ if (shouldRetry && attempt <= retriableOptions.retryCount && error instanceof PostHogFetchHttpError)
4108
+ error.cancelResponseBody();
4109
+ return shouldRetry;
4110
+ }
3048
4111
  });
3049
4112
  }
3050
4113
  async _shutdown(shutdownTimeoutMs = 30000) {
@@ -3057,12 +4120,17 @@ class PostHogCoreStateless {
3057
4120
  try {
3058
4121
  await this.promiseQueue.join();
3059
4122
  while (true) {
3060
- const queue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
3061
- if (queue.length === 0)
4123
+ const hasQueuedEvents = this.getActiveQueueRoutes().some((route) => this.getRouteQueue(route).length > 0);
4124
+ if (!hasQueuedEvents)
3062
4125
  break;
4126
+ const dequeuedBeforeFlush = this._dequeuedMessagesCount;
3063
4127
  await this.flush();
3064
4128
  if (hasTimedOut)
3065
4129
  break;
4130
+ if (this._dequeuedMessagesCount === dequeuedBeforeFlush) {
4131
+ this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");
4132
+ break;
4133
+ }
3066
4134
  }
3067
4135
  } catch (e) {
3068
4136
  if (!isPostHogFetchError(e))
@@ -3070,21 +4138,12 @@ class PostHogCoreStateless {
3070
4138
  await logFlushError(e);
3071
4139
  }
3072
4140
  };
3073
- let timeoutHandle;
3074
- try {
3075
- return await Promise.race([
3076
- new Promise((_, reject) => {
3077
- timeoutHandle = safeSetTimeout(() => {
3078
- this._logger.error("Timed out while shutting down PostHog");
3079
- hasTimedOut = true;
3080
- reject("Timeout while shutting down PostHog. Some events may not have been sent.");
3081
- }, shutdownTimeoutMs);
3082
- }),
3083
- doShutdown()
3084
- ]);
3085
- } finally {
3086
- clearTimeout(timeoutHandle);
3087
- }
4141
+ return raceWithTimeout(doShutdown(), shutdownTimeoutMs, () => {
4142
+ this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.", {
4143
+ shutdownTimeoutMs
4144
+ });
4145
+ hasTimedOut = true;
4146
+ });
3088
4147
  }
3089
4148
  async shutdown(shutdownTimeoutMs = 30000) {
3090
4149
  if (this.shutdownPromise)
@@ -3096,7 +4155,11 @@ class PostHogCoreStateless {
3096
4155
  return this.shutdownPromise;
3097
4156
  }
3098
4157
  }
3099
- var PostHogFetchHttpError, PostHogFetchNetworkError;
4158
+ var PostHogFetchHttpError, PostHogFetchNetworkError, applyCallerFeatureFlagOverrides = (target, callerProperties) => {
4159
+ for (const key of Object.keys(callerProperties))
4160
+ if (key.startsWith("$feature/") || key === "$active_feature_flags")
4161
+ target[key] = callerProperties[key];
4162
+ }, DEFAULT_QUEUE_ROUTE = "default";
3100
4163
  var init_posthog_core_stateless = __esm(() => {
3101
4164
  init_eventemitter();
3102
4165
  init_featureFlagUtils();
@@ -3106,17 +4169,58 @@ var init_posthog_core_stateless = __esm(() => {
3106
4169
  init_uuidv7();
3107
4170
  init_error_tracking();
3108
4171
  PostHogFetchHttpError = class PostHogFetchHttpError extends Error {
3109
- constructor(response, reqByteLength) {
3110
- super("HTTP error while fetching PostHog: status=" + response.status + ", reqByteLength=" + reqByteLength), this.response = response, this.reqByteLength = reqByteLength, this.name = "PostHogFetchHttpError";
4172
+ constructor(response, reqByteLength, responseBodyDeadline, abortController) {
4173
+ 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;
3111
4174
  }
3112
4175
  get status() {
3113
4176
  return this.response.status;
3114
4177
  }
4178
+ get bodyReadTimedOut() {
4179
+ return this._bodyReadTimedOut;
4180
+ }
3115
4181
  get text() {
3116
- return this.response.text();
4182
+ if (!this.responseBodyTextPromise)
4183
+ if (Date.now() >= this.responseBodyDeadline) {
4184
+ this._bodyReadTimedOut = true;
4185
+ const timeoutError = new Error("Response body read timed out");
4186
+ timeoutError.name = "AbortError";
4187
+ this.cancelResponseBody(timeoutError);
4188
+ this.responseBodyTextPromise = Promise.reject(timeoutError);
4189
+ } else {
4190
+ const responseBodyTimeout = new Promise((_resolve, reject) => {
4191
+ this.responseBodyTimer = safeSetTimeout(() => {
4192
+ this._bodyReadTimedOut = true;
4193
+ const timeoutError = new Error("Response body read timed out");
4194
+ timeoutError.name = "AbortError";
4195
+ reject(timeoutError);
4196
+ this.cancelResponseBody(timeoutError);
4197
+ }, this.responseBodyDeadline - Date.now());
4198
+ });
4199
+ let responseBodyText;
4200
+ try {
4201
+ responseBodyText = Promise.resolve(this.response.text());
4202
+ } catch (error) {
4203
+ responseBodyText = Promise.reject(error);
4204
+ }
4205
+ this.responseBodyTextPromise = Promise.race([
4206
+ responseBodyText,
4207
+ responseBodyTimeout
4208
+ ]).finally(() => clearTimeout(this.responseBodyTimer));
4209
+ }
4210
+ return this.responseBodyTextPromise;
3117
4211
  }
3118
4212
  get json() {
3119
- return this.response.json();
4213
+ return this.text.then((text) => JSON.parse(text));
4214
+ }
4215
+ cancelResponseBody(reason) {
4216
+ clearTimeout(this.responseBodyTimer);
4217
+ if (!this.abortController.signal.aborted)
4218
+ this.abortController.abort(reason);
4219
+ (async () => {
4220
+ try {
4221
+ await this.response.body?.cancel();
4222
+ } catch {}
4223
+ })();
3120
4224
  }
3121
4225
  };
3122
4226
  PostHogFetchNetworkError = class PostHogFetchNetworkError extends Error {
@@ -3128,7 +4232,7 @@ var init_posthog_core_stateless = __esm(() => {
3128
4232
  };
3129
4233
  });
3130
4234
 
3131
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/posthog-core.mjs
4235
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/posthog-core.mjs
3132
4236
  var init_posthog_core = __esm(() => {
3133
4237
  init_featureFlagUtils();
3134
4238
  init_types();
@@ -3137,17 +4241,18 @@ var init_posthog_core = __esm(() => {
3137
4241
  init_utils();
3138
4242
  });
3139
4243
 
3140
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/tracing-headers.mjs
4244
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/tracing-headers.mjs
3141
4245
  var init_tracing_headers = __esm(() => {
3142
4246
  init_type_utils();
3143
4247
  });
3144
4248
 
3145
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/index.mjs
4249
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/index.mjs
3146
4250
  var init_dist = __esm(() => {
3147
4251
  init_featureFlagUtils();
3148
4252
  init_gzip();
3149
4253
  init_logs_utils();
3150
4254
  init_logs();
4255
+ init_metrics();
3151
4256
  init_uuidv7();
3152
4257
  init_validation();
3153
4258
  init_error_tracking();
@@ -3159,16 +4264,24 @@ var init_dist = __esm(() => {
3159
4264
  init_types();
3160
4265
  });
3161
4266
 
3162
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/context-lines.node.mjs
3163
- import { createReadStream } from "node:fs";
4267
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/context-lines.node.mjs
4268
+ import { constants as constants3 } from "node:fs";
4269
+ import { open as promises_open } from "node:fs/promises";
4270
+ import { isAbsolute as isAbsolute7 } from "node:path";
3164
4271
  import { createInterface } from "node:readline";
3165
- async function addSourceContext(frames) {
4272
+ async function addSourceContext(frames, openSourceFile = promises_open, logger2) {
3166
4273
  const filesToLines = {};
4274
+ let basePath;
4275
+ try {
4276
+ basePath = process.cwd();
4277
+ } catch {}
3167
4278
  for (let i = frames.length - 1;i >= 0; i--) {
3168
4279
  const frame = frames[i];
3169
4280
  const filename = frame?.filename;
3170
4281
  if (!frame || typeof filename != "string" || typeof frame.lineno != "number" || shouldSkipContextLinesForFile(filename) || shouldSkipContextLinesForFrame(frame))
3171
4282
  continue;
4283
+ if (!isAbsolute7(filename) && basePath === undefined)
4284
+ continue;
3172
4285
  const filesToLinesOutput = filesToLines[filename];
3173
4286
  if (!filesToLinesOutput)
3174
4287
  filesToLines[filename] = [];
@@ -3179,50 +4292,98 @@ async function addSourceContext(frames) {
3179
4292
  return frames;
3180
4293
  const readlinePromises = [];
3181
4294
  for (const file of files) {
3182
- if (LRU_FILE_CONTENTS_FS_READ_FAILED.get(file))
4295
+ const cacheKey = makeSourceCacheKey(file, basePath);
4296
+ if (cacheKey === undefined)
4297
+ continue;
4298
+ if (LRU_FILE_CONTENTS_FS_READ_FAILED.get(cacheKey))
3183
4299
  continue;
3184
4300
  const filesToLineRanges = filesToLines[file];
3185
4301
  if (!filesToLineRanges)
3186
4302
  continue;
3187
4303
  filesToLineRanges.sort((a, b) => a - b);
3188
4304
  const ranges = makeLineReaderRanges(filesToLineRanges);
3189
- if (ranges.every((r) => rangeExistsInContentCache(file, r)))
4305
+ if (ranges.every((r) => rangeExistsInContentCache(cacheKey, r)))
3190
4306
  continue;
3191
- const cache = emplace(LRU_FILE_CONTENTS_CACHE, file, {});
3192
- readlinePromises.push(getContextLinesFromFile(file, ranges, cache));
4307
+ const cache = emplace(LRU_FILE_CONTENTS_CACHE, cacheKey, {});
4308
+ readlinePromises.push(getContextLinesFromFile(file, ranges, cache, cacheKey, openSourceFile, logger2));
3193
4309
  }
3194
4310
  await Promise.all(readlinePromises).catch(() => {});
3195
4311
  if (frames && frames.length > 0)
3196
- addSourceContextToFrames(frames, LRU_FILE_CONTENTS_CACHE);
4312
+ addSourceContextToFrames(frames, LRU_FILE_CONTENTS_CACHE, basePath);
3197
4313
  LRU_FILE_CONTENTS_CACHE.reduce();
3198
4314
  return frames;
3199
4315
  }
3200
- function getContextLinesFromFile(path2, ranges, output) {
4316
+ async function openRegularSourceFile(path2, openSourceFile, logger2) {
4317
+ let fileHandle;
4318
+ let isValid = false;
4319
+ try {
4320
+ fileHandle = await openSourceFile(path2, constants3.O_RDONLY | constants3.O_NONBLOCK);
4321
+ const fileStat = await fileHandle.stat();
4322
+ if (!fileStat.isFile())
4323
+ return;
4324
+ if (fileStat.size > MAX_CONTEXTLINES_FILE_SIZE)
4325
+ return void logger2?.debug(`Skipping source context for oversized file ${path2}: ${fileStat.size} bytes exceeds ${MAX_CONTEXTLINES_FILE_SIZE}`);
4326
+ isValid = true;
4327
+ return fileHandle;
4328
+ } catch {
4329
+ return;
4330
+ } finally {
4331
+ if (fileHandle && !isValid)
4332
+ await fileHandle.close().catch(() => {});
4333
+ }
4334
+ }
4335
+ async function getContextLinesFromFile(path2, ranges, output, cacheKey, openSourceFile, logger2) {
4336
+ const fileHandle = await openRegularSourceFile(path2, openSourceFile, logger2);
4337
+ if (fileHandle === undefined)
4338
+ return void LRU_FILE_CONTENTS_FS_READ_FAILED.set(cacheKey, 1);
4339
+ const openedFileHandle = fileHandle;
3201
4340
  return new Promise((resolve9) => {
3202
- const stream = createReadStream(path2);
3203
- const lineReaded = createInterface({
3204
- input: stream
3205
- });
3206
- function destroyStreamAndResolve() {
3207
- stream.destroy();
3208
- resolve9();
4341
+ let finished = false;
4342
+ function destroyStreamAndResolve(stream2) {
4343
+ if (finished)
4344
+ return;
4345
+ finished = true;
4346
+ stream2?.destroy();
4347
+ openedFileHandle.close().then(resolve9, resolve9);
4348
+ }
4349
+ let stream;
4350
+ try {
4351
+ stream = openedFileHandle.createReadStream({
4352
+ autoClose: false,
4353
+ start: 0,
4354
+ end: MAX_CONTEXTLINES_FILE_SIZE - 1
4355
+ });
4356
+ } catch {
4357
+ LRU_FILE_CONTENTS_FS_READ_FAILED.set(cacheKey, 1);
4358
+ destroyStreamAndResolve();
4359
+ return;
4360
+ }
4361
+ let lineReaded;
4362
+ try {
4363
+ lineReaded = createInterface({
4364
+ input: stream
4365
+ });
4366
+ } catch {
4367
+ LRU_FILE_CONTENTS_FS_READ_FAILED.set(cacheKey, 1);
4368
+ destroyStreamAndResolve(stream);
4369
+ return;
3209
4370
  }
3210
4371
  let lineNumber = 0;
3211
4372
  let currentRangeIndex = 0;
3212
4373
  const range = ranges[currentRangeIndex];
3213
4374
  if (range === undefined)
3214
- return void destroyStreamAndResolve();
4375
+ return void destroyStreamAndResolve(stream);
3215
4376
  let rangeStart = range[0];
3216
4377
  let rangeEnd = range[1];
3217
4378
  function onStreamError() {
3218
- LRU_FILE_CONTENTS_FS_READ_FAILED.set(path2, 1);
4379
+ LRU_FILE_CONTENTS_FS_READ_FAILED.set(cacheKey, 1);
3219
4380
  lineReaded.close();
3220
4381
  lineReaded.removeAllListeners();
3221
- destroyStreamAndResolve();
4382
+ destroyStreamAndResolve(stream);
3222
4383
  }
3223
4384
  stream.on("error", onStreamError);
3224
4385
  lineReaded.on("error", onStreamError);
3225
- lineReaded.on("close", destroyStreamAndResolve);
4386
+ lineReaded.on("close", () => destroyStreamAndResolve(stream));
3226
4387
  lineReaded.on("line", (line) => {
3227
4388
  lineNumber++;
3228
4389
  if (lineNumber < rangeStart)
@@ -3247,10 +4408,11 @@ function getContextLinesFromFile(path2, ranges, output) {
3247
4408
  });
3248
4409
  });
3249
4410
  }
3250
- function addSourceContextToFrames(frames, cache) {
4411
+ function addSourceContextToFrames(frames, cache, basePath) {
3251
4412
  for (const frame of frames)
3252
4413
  if (frame.filename && frame.context_line === undefined && typeof frame.lineno == "number") {
3253
- const contents = cache.get(frame.filename);
4414
+ const cacheKey = makeSourceCacheKey(frame.filename, basePath);
4415
+ const contents = cacheKey === undefined ? undefined : cache.get(cacheKey);
3254
4416
  if (contents === undefined)
3255
4417
  continue;
3256
4418
  addContextToFrame(frame.lineno, frame, contents);
@@ -3293,8 +4455,19 @@ function shouldSkipContextLinesForFrame(frame) {
3293
4455
  return true;
3294
4456
  return false;
3295
4457
  }
3296
- function rangeExistsInContentCache(file, range) {
3297
- const contents = LRU_FILE_CONTENTS_CACHE.get(file);
4458
+ function makeSourceCacheKey(path2, basePath) {
4459
+ if (isAbsolute7(path2))
4460
+ return JSON.stringify([
4461
+ null,
4462
+ path2
4463
+ ]);
4464
+ return basePath === undefined ? undefined : JSON.stringify([
4465
+ basePath,
4466
+ path2
4467
+ ]);
4468
+ }
4469
+ function rangeExistsInContentCache(cacheKey, range) {
4470
+ const contents = LRU_FILE_CONTENTS_CACHE.get(cacheKey);
3298
4471
  if (contents === undefined)
3299
4472
  return false;
3300
4473
  for (let i = range[0];i <= range[1]; i++)
@@ -3371,15 +4544,15 @@ function snipLine(line, colno) {
3371
4544
  newLine += "...";
3372
4545
  return newLine;
3373
4546
  }
3374
- var LRU_FILE_CONTENTS_CACHE, LRU_FILE_CONTENTS_FS_READ_FAILED, DEFAULT_LINES_OF_CONTEXT = 7, MAX_CONTEXTLINES_COLNO = 1000, MAX_CONTEXTLINES_LINENO = 1e4;
4547
+ var LRU_FILE_CONTENTS_CACHE, LRU_FILE_CONTENTS_FS_READ_FAILED, DEFAULT_LINES_OF_CONTEXT = 7, MAX_CONTEXTLINES_COLNO = 1000, MAX_CONTEXTLINES_LINENO = 1e4, MAX_CONTEXTLINES_FILE_SIZE = 10485760;
3375
4548
  var init_context_lines_node = __esm(() => {
3376
4549
  init_dist();
3377
4550
  LRU_FILE_CONTENTS_CACHE = new exports_error_tracking.ReduceableCache(25);
3378
4551
  LRU_FILE_CONTENTS_FS_READ_FAILED = new exports_error_tracking.ReduceableCache(20);
3379
4552
  });
3380
4553
 
3381
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/relative-path.node.mjs
3382
- import { isAbsolute as isAbsolute7, relative as relative4, sep as sep8 } from "node:path";
4554
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/relative-path.node.mjs
4555
+ import { isAbsolute as isAbsolute8, relative as relative4, sep as sep8 } from "node:path";
3383
4556
  function createRelativePathModifier(basePath = process.cwd()) {
3384
4557
  const isWindows = sep8 === "\\";
3385
4558
  const toUnix = (p) => isWindows ? p.replace(/\\/g, "/") : p;
@@ -3387,7 +4560,7 @@ function createRelativePathModifier(basePath = process.cwd()) {
3387
4560
  return async (frames) => {
3388
4561
  for (const frame of frames)
3389
4562
  if (!(!frame.filename || frame.filename.startsWith("node:") || frame.filename.startsWith("data:"))) {
3390
- if (isAbsolute7(frame.filename))
4563
+ if (isAbsolute8(frame.filename))
3391
4564
  frame.filename = toUnix(relative4(normalizedBase, toUnix(frame.filename)));
3392
4565
  }
3393
4566
  return frames;
@@ -3395,11 +4568,11 @@ function createRelativePathModifier(basePath = process.cwd()) {
3395
4568
  }
3396
4569
  var init_relative_path_node = () => {};
3397
4570
 
3398
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/version.mjs
3399
- var version = "5.35.12";
4571
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/version.mjs
4572
+ var version = "5.51.1";
3400
4573
  var init_version = () => {};
3401
4574
 
3402
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/types.mjs
4575
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/types.mjs
3403
4576
  var FeatureFlagError2;
3404
4577
  var init_types3 = __esm(() => {
3405
4578
  FeatureFlagError2 = {
@@ -3410,7 +4583,7 @@ var init_types3 = __esm(() => {
3410
4583
  };
3411
4584
  });
3412
4585
 
3413
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/feature-flag-evaluations.mjs
4586
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/feature-flag-evaluations.mjs
3414
4587
  class FeatureFlagEvaluations {
3415
4588
  constructor(init) {
3416
4589
  this._host = init.host;
@@ -3426,10 +4599,10 @@ class FeatureFlagEvaluations {
3426
4599
  this._accessed = init.accessed ?? new Set;
3427
4600
  this._isSlice = init.isSlice ?? false;
3428
4601
  }
3429
- isEnabled(key) {
4602
+ isEnabled(key, options = {}) {
3430
4603
  const flag = this._flags[key];
3431
4604
  this._recordAccess(key);
3432
- return flag?.enabled ?? false;
4605
+ return flag?.enabled ?? options.defaultValue ?? false;
3433
4606
  }
3434
4607
  getFlag(key) {
3435
4608
  const flag = this._flags[key];
@@ -3519,6 +4692,8 @@ class FeatureFlagEvaluations {
3519
4692
  $feature_flag_request_id: this._requestId,
3520
4693
  $feature_flag_evaluated_at: flag?.locallyEvaluated ? Date.now() : this._evaluatedAt
3521
4694
  };
4695
+ if (flag?.hasExperiment !== undefined)
4696
+ properties.$feature_flag_has_experiment = flag.hasExperiment;
3522
4697
  if (flag?.locallyEvaluated && this._flagDefinitionsLoadedAt !== undefined)
3523
4698
  properties.$feature_flag_definitions_loaded_at = this._flagDefinitionsLoadedAt;
3524
4699
  const errors = [];
@@ -3544,7 +4719,7 @@ var init_feature_flag_evaluations = __esm(() => {
3544
4719
  init_types3();
3545
4720
  });
3546
4721
 
3547
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/feature-flags/crypto.mjs
4722
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/feature-flags/crypto.mjs
3548
4723
  async function hashSHA1(text) {
3549
4724
  const subtle = globalThis.crypto?.subtle;
3550
4725
  if (!subtle)
@@ -3555,12 +4730,19 @@ async function hashSHA1(text) {
3555
4730
  }
3556
4731
  var init_crypto = () => {};
3557
4732
 
3558
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/feature-flags/feature-flags.mjs
4733
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/feature-flags/feature-flags.mjs
4734
+ function setCustomErrorPrototype(error, constructor) {
4735
+ error.name = constructor.name;
4736
+ Error.captureStackTrace(error, constructor);
4737
+ Object.setPrototypeOf(error, constructor.prototype);
4738
+ }
4739
+
3559
4740
  class FeatureFlagsPoller {
3560
4741
  constructor({ pollingInterval, personalApiKey, projectApiKey, timeout, host, customHeaders, ...options }) {
3561
4742
  this.debugMode = false;
3562
4743
  this.shouldBeginExponentialBackoff = false;
3563
4744
  this.backOffCount = 0;
4745
+ this.pollerStopped = false;
3564
4746
  this.pollingInterval = pollingInterval;
3565
4747
  this.personalApiKey = personalApiKey;
3566
4748
  this.featureFlags = [];
@@ -3576,6 +4758,7 @@ class FeatureFlagsPoller {
3576
4758
  this.onError = options.onError;
3577
4759
  this.customHeaders = customHeaders;
3578
4760
  this.onLoad = options.onLoad;
4761
+ this.onMinimalFlagCalledEvents = options.onMinimalFlagCalledEvents;
3579
4762
  this.cacheProvider = options.cacheProvider;
3580
4763
  this.strictLocalEvaluation = options.strictLocalEvaluation ?? false;
3581
4764
  this.loadFeatureFlags();
@@ -3773,6 +4956,7 @@ class FeatureFlagsPoller {
3773
4956
  const flagFilters = flag.filters || {};
3774
4957
  const flagConditions = flagFilters.groups || [];
3775
4958
  const flagAggregation = flagFilters.aggregation_group_type_index;
4959
+ const earlyExitEnabled = flagFilters.early_exit ?? false;
3776
4960
  const { groups, groupProperties } = evaluationContext;
3777
4961
  let isInconclusive = false;
3778
4962
  let result;
@@ -3796,12 +4980,15 @@ class FeatureFlagsPoller {
3796
4980
  effectiveBucketingValue = groups[groupName];
3797
4981
  }
3798
4982
  }
3799
- if (await this.isConditionMatch(flag, effectiveBucketingValue, condition, effectiveProperties, evaluationContext)) {
4983
+ const matchResult = await this.isConditionMatch(flag, effectiveBucketingValue, condition, effectiveProperties, evaluationContext);
4984
+ if (matchResult === "match") {
3800
4985
  const variantOverride = condition.variant;
3801
4986
  const flagVariants = flagFilters.multivariate?.variants || [];
3802
4987
  result = variantOverride && flagVariants.some((variant) => variant.key === variantOverride) ? variantOverride : await this.getMatchingVariant(flag, effectiveBucketingValue) || true;
3803
4988
  break;
3804
4989
  }
4990
+ if (earlyExitEnabled && matchResult === "out_of_rollout_bound")
4991
+ return false;
3805
4992
  } catch (e) {
3806
4993
  if (e instanceof RequiresServerEvaluation)
3807
4994
  throw e;
@@ -3825,16 +5012,20 @@ class FeatureFlagsPoller {
3825
5012
  for (const prop of condition.properties) {
3826
5013
  const propertyType = prop.type;
3827
5014
  let matches = false;
3828
- 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);
5015
+ if (propertyType === "cohort") {
5016
+ const inCohort = await matchCohort(prop, properties, this.cohorts, this.debugMode, (depProp) => this.evaluateFlagDependency(depProp, properties, evaluationContext));
5017
+ matches = prop.operator === "not_in" ? !inCohort : inCohort;
5018
+ } else
5019
+ matches = propertyType === "flag" ? await this.evaluateFlagDependency(prop, properties, evaluationContext) : matchProperty(prop, properties, warnFunction);
3829
5020
  if (!matches)
3830
- return false;
5021
+ return "no_match";
3831
5022
  }
3832
5023
  if (rolloutPercentage == undefined)
3833
- return true;
5024
+ return "match";
3834
5025
  }
3835
5026
  if (rolloutPercentage != null && await _hash(flag.key, bucketingValue) > rolloutPercentage / 100)
3836
- return false;
3837
- return true;
5027
+ return "out_of_rollout_bound";
5028
+ return "match";
3838
5029
  }
3839
5030
  async getMatchingVariant(flag, bucketingValue) {
3840
5031
  const hashValue = await _hash(flag.key, bucketingValue, "variant");
@@ -3865,6 +5056,7 @@ class FeatureFlagsPoller {
3865
5056
  this.groupTypeMapping = flagData.groupTypeMapping;
3866
5057
  this.cohorts = flagData.cohorts;
3867
5058
  this.loadedSuccessfullyOnce = true;
5059
+ this.onMinimalFlagCalledEvents?.(flagData.minimalFlagCalledEvents === true);
3868
5060
  }
3869
5061
  warnAboutExperienceContinuityFlags(flags) {
3870
5062
  if (this.strictLocalEvaluation)
@@ -3928,7 +5120,6 @@ class FeatureFlagsPoller {
3928
5120
  clearTimeout(this.poller);
3929
5121
  this.poller = undefined;
3930
5122
  }
3931
- this.poller = setTimeout(() => this.loadFeatureFlags(true), this.getPollingInterval());
3932
5123
  try {
3933
5124
  let shouldFetch = true;
3934
5125
  if (this.cacheProvider)
@@ -3956,17 +5147,18 @@ class FeatureFlagsPoller {
3956
5147
  return;
3957
5148
  case 401:
3958
5149
  this.beginBackoff();
3959
- 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`);
5150
+ 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`);
3960
5151
  case 402:
3961
5152
  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");
3962
5153
  this.featureFlags = [];
3963
5154
  this.featureFlagsByKey = {};
3964
5155
  this.groupTypeMapping = {};
3965
5156
  this.cohorts = {};
5157
+ this.onMinimalFlagCalledEvents?.(false);
3966
5158
  return;
3967
5159
  case 403:
3968
5160
  this.beginBackoff();
3969
- 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`);
5161
+ 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`);
3970
5162
  case 429:
3971
5163
  this.beginBackoff();
3972
5164
  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`);
@@ -3978,7 +5170,8 @@ class FeatureFlagsPoller {
3978
5170
  const flagData = {
3979
5171
  flags: responseJson.flags ?? [],
3980
5172
  groupTypeMapping: responseJson.group_type_mapping || {},
3981
- cohorts: responseJson.cohorts || {}
5173
+ cohorts: responseJson.cohorts || {},
5174
+ minimalFlagCalledEvents: responseJson.minimal_flag_called_events === true
3982
5175
  };
3983
5176
  this.updateFlagState(flagData);
3984
5177
  this.flagDefinitionsLoadedAt = Date.now();
@@ -3999,6 +5192,9 @@ class FeatureFlagsPoller {
3999
5192
  } catch (err) {
4000
5193
  if (err instanceof ClientError)
4001
5194
  this.onError?.(err);
5195
+ } finally {
5196
+ if (!this.pollerStopped)
5197
+ this.poller = setTimeout(() => this.loadFeatureFlags(true), this.getPollingInterval());
4002
5198
  }
4003
5199
  }
4004
5200
  getPersonalApiKeyRequestOptions(method = "GET", etag) {
@@ -4014,7 +5210,7 @@ class FeatureFlagsPoller {
4014
5210
  headers
4015
5211
  };
4016
5212
  }
4017
- _requestFeatureFlagDefinitions() {
5213
+ async _requestFeatureFlagDefinitions() {
4018
5214
  const url = `${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`;
4019
5215
  const options = this.getPersonalApiKeyRequestOptions("GET", this.flagsEtag);
4020
5216
  let abortTimeout = null;
@@ -4025,23 +5221,49 @@ class FeatureFlagsPoller {
4025
5221
  }, this.timeout);
4026
5222
  options.signal = controller.signal;
4027
5223
  }
5224
+ const clearAbortTimeout = () => clearTimeout(abortTimeout);
4028
5225
  try {
4029
5226
  const fetch1 = this.fetch;
4030
- return fetch1(url, options);
4031
- } finally {
4032
- clearTimeout(abortTimeout);
5227
+ const res = await fetch1(url, options);
5228
+ if (res.status !== 200) {
5229
+ clearAbortTimeout();
5230
+ return res;
5231
+ }
5232
+ return {
5233
+ status: res.status,
5234
+ headers: res.headers,
5235
+ body: res.body,
5236
+ text: async () => {
5237
+ try {
5238
+ return await res.text();
5239
+ } finally {
5240
+ clearAbortTimeout();
5241
+ }
5242
+ },
5243
+ json: async () => {
5244
+ try {
5245
+ return await res.json();
5246
+ } finally {
5247
+ clearAbortTimeout();
5248
+ }
5249
+ }
5250
+ };
5251
+ } catch (err) {
5252
+ clearAbortTimeout();
5253
+ throw err;
4033
5254
  }
4034
5255
  }
4035
5256
  async stopPoller(timeoutMs = 30000) {
5257
+ this.pollerStopped = true;
4036
5258
  clearTimeout(this.poller);
5259
+ this.poller = undefined;
4037
5260
  if (this.cacheProvider)
4038
5261
  try {
4039
5262
  const shutdownResult = this.cacheProvider.shutdown();
4040
5263
  if (shutdownResult instanceof Promise)
4041
- await Promise.race([
4042
- shutdownResult,
4043
- new Promise((_, reject) => setTimeout(() => reject(new Error(`Cache shutdown timeout after ${timeoutMs}ms`)), timeoutMs))
4044
- ]);
5264
+ await raceWithTimeout(shutdownResult, timeoutMs, () => {
5265
+ throw new Error(`Cache shutdown timeout after ${timeoutMs}ms`);
5266
+ });
4045
5267
  } catch (err) {
4046
5268
  this.onError?.(new Error(`Error during cache shutdown: ${err}`));
4047
5269
  }
@@ -4096,6 +5318,14 @@ function matchProperty(property, propertyValues, warnFunction) {
4096
5318
  return String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
4097
5319
  case "not_icontains":
4098
5320
  return !String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
5321
+ case "starts_with":
5322
+ return String(overrideValue).toLowerCase().startsWith(String(value).toLowerCase());
5323
+ case "not_starts_with":
5324
+ return !String(overrideValue).toLowerCase().startsWith(String(value).toLowerCase());
5325
+ case "ends_with":
5326
+ return String(overrideValue).toLowerCase().endsWith(String(value).toLowerCase());
5327
+ case "not_ends_with":
5328
+ return !String(overrideValue).toLowerCase().endsWith(String(value).toLowerCase());
4099
5329
  case "regex":
4100
5330
  return isValidRegex(String(value)) && String(overrideValue).match(String(value)) !== null;
4101
5331
  case "not_regex":
@@ -4441,34 +5671,70 @@ var init_feature_flags = __esm(() => {
4441
5671
  InconclusiveMatchError = class InconclusiveMatchError extends Error {
4442
5672
  constructor(message) {
4443
5673
  super(message);
4444
- this.name = this.constructor.name;
4445
- Error.captureStackTrace(this, this.constructor);
4446
- Object.setPrototypeOf(this, InconclusiveMatchError.prototype);
5674
+ setCustomErrorPrototype(this, InconclusiveMatchError);
4447
5675
  }
4448
5676
  };
4449
5677
  RequiresServerEvaluation = class RequiresServerEvaluation extends Error {
4450
5678
  constructor(message) {
4451
5679
  super(message);
4452
- this.name = this.constructor.name;
4453
- Error.captureStackTrace(this, this.constructor);
4454
- Object.setPrototypeOf(this, RequiresServerEvaluation.prototype);
5680
+ setCustomErrorPrototype(this, RequiresServerEvaluation);
4455
5681
  }
4456
5682
  };
4457
5683
  });
4458
5684
 
4459
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/error-tracking/autocapture.mjs
5685
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/error-tracking/autocapture.mjs
5686
+ function splitNodeOptions(nodeOptions) {
5687
+ const args = [];
5688
+ let current = "";
5689
+ let isInString = false;
5690
+ for (let index = 0;index < nodeOptions.length; index++) {
5691
+ const character = nodeOptions[index];
5692
+ if (character === "\\" && isInString && index + 1 < nodeOptions.length)
5693
+ current += nodeOptions[++index];
5694
+ else if (character !== " " || isInString)
5695
+ if (character === '"')
5696
+ isInString = !isInString;
5697
+ else
5698
+ current += character;
5699
+ else if (current) {
5700
+ args.push(current);
5701
+ current = "";
5702
+ }
5703
+ }
5704
+ if (current)
5705
+ args.push(current);
5706
+ return args;
5707
+ }
5708
+ function findUnhandledRejectionMode(args) {
5709
+ let mode;
5710
+ for (let index = 0;index < args.length; index++) {
5711
+ const argument = args[index];
5712
+ const optionName = UNHANDLED_REJECTION_OPTION_NAMES.find((name) => argument === name || argument.startsWith(`${name}=`));
5713
+ if (!optionName)
5714
+ continue;
5715
+ const value = argument === optionName ? args[++index] : argument.slice(optionName.length + 1);
5716
+ if (UNHANDLED_REJECTION_MODES.has(value))
5717
+ mode = value;
5718
+ }
5719
+ return mode;
5720
+ }
5721
+ function getUnhandledRejectionMode(execArgv = STARTUP_EXEC_ARGV, nodeOptions = STARTUP_NODE_OPTIONS) {
5722
+ return findUnhandledRejectionMode(execArgv) ?? findUnhandledRejectionMode(splitNodeOptions(nodeOptions ?? "")) ?? "throw";
5723
+ }
5724
+ function captureUncaughtException(captureFn, error, origin) {
5725
+ captureFn(error, {
5726
+ mechanism: {
5727
+ type: origin === "unhandledRejection" ? "onunhandledrejection" : "onuncaughtexception",
5728
+ handled: false
5729
+ }
5730
+ });
5731
+ }
4460
5732
  function makeUncaughtExceptionHandler(captureFn, onFatalFn) {
4461
5733
  let calledFatalError = false;
4462
- return Object.assign((error) => {
5734
+ return Object.assign((error, origin) => {
4463
5735
  const userProvidedListenersCount = global.process.listeners("uncaughtException").filter((listener) => listener.name !== "domainUncaughtExceptionClear" && listener._posthogErrorHandler !== true).length;
4464
- const processWouldExit = userProvidedListenersCount === 0;
4465
- captureFn(error, {
4466
- mechanism: {
4467
- type: "onuncaughtexception",
4468
- handled: false
4469
- }
4470
- });
4471
- if (!calledFatalError && processWouldExit) {
5736
+ captureUncaughtException(captureFn, error, origin);
5737
+ if (!calledFatalError && userProvidedListenersCount === 0) {
4472
5738
  calledFatalError = true;
4473
5739
  onFatalFn(error);
4474
5740
  }
@@ -4476,28 +5742,55 @@ function makeUncaughtExceptionHandler(captureFn, onFatalFn) {
4476
5742
  _posthogErrorHandler: true
4477
5743
  });
4478
5744
  }
4479
- function addUncaughtExceptionListener(captureFn, onFatalFn) {
4480
- globalThis.process?.on("uncaughtException", makeUncaughtExceptionHandler(captureFn, onFatalFn));
5745
+ function addUncaughtExceptionListener(captureFn, onFatalFn, mode = STARTUP_UNHANDLED_REJECTION_MODE) {
5746
+ const process2 = globalThis.process;
5747
+ if (!process2)
5748
+ return;
5749
+ if (mode === "strict")
5750
+ return void process2.on("uncaughtExceptionMonitor", (error, origin) => captureUncaughtException(captureFn, error, origin));
5751
+ process2.on("uncaughtException", makeUncaughtExceptionHandler(captureFn, onFatalFn));
4481
5752
  }
4482
- function addUnhandledRejectionListener(captureFn) {
4483
- globalThis.process?.on("unhandledRejection", (reason) => captureFn(reason, {
4484
- mechanism: {
4485
- type: "onunhandledrejection",
4486
- handled: false
4487
- }
4488
- }));
5753
+ function addUnhandledRejectionListener(captureFn, mode = STARTUP_UNHANDLED_REJECTION_MODE) {
5754
+ const process2 = globalThis.process;
5755
+ if (!process2 || mode === "throw" || mode === "strict" || mode === "warn-with-error-code")
5756
+ return;
5757
+ process2.on("unhandledRejection", (reason) => {
5758
+ captureFn(reason, {
5759
+ mechanism: {
5760
+ type: "onunhandledrejection",
5761
+ handled: false
5762
+ }
5763
+ });
5764
+ });
4489
5765
  }
4490
- var init_autocapture = () => {};
5766
+ var UNHANDLED_REJECTION_OPTION_NAMES, UNHANDLED_REJECTION_MODES, STARTUP_EXEC_ARGV, STARTUP_NODE_OPTIONS, STARTUP_UNHANDLED_REJECTION_MODE;
5767
+ var init_autocapture = __esm(() => {
5768
+ UNHANDLED_REJECTION_OPTION_NAMES = [
5769
+ "--unhandled-rejections",
5770
+ "--unhandled_rejections"
5771
+ ];
5772
+ UNHANDLED_REJECTION_MODES = new Set([
5773
+ "throw",
5774
+ "strict",
5775
+ "warn",
5776
+ "warn-with-error-code",
5777
+ "none"
5778
+ ]);
5779
+ STARTUP_EXEC_ARGV = [
5780
+ ...globalThis.process?.execArgv ?? []
5781
+ ];
5782
+ STARTUP_NODE_OPTIONS = globalThis.process?.env?.NODE_OPTIONS;
5783
+ STARTUP_UNHANDLED_REJECTION_MODE = getUnhandledRejectionMode();
5784
+ });
4491
5785
 
4492
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/error-tracking/index.mjs
4493
- class ErrorTracking {
5786
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/error-tracking/index.mjs
5787
+ class error_tracking_ErrorTracking {
4494
5788
  constructor(client, options, _logger) {
4495
5789
  this.client = client;
4496
5790
  this._exceptionAutocaptureEnabled = options.enableExceptionAutocapture || false;
4497
5791
  this._logger = _logger;
4498
5792
  this._rateLimiter = new BucketedRateLimiter({
4499
- refillRate: 1,
4500
- bucketSize: 10,
5793
+ ...resolveExceptionRateLimiterConfig(options),
4501
5794
  refillInterval: 1e4,
4502
5795
  _logger: this._logger
4503
5796
  });
@@ -4506,76 +5799,536 @@ class ErrorTracking {
4506
5799
  static isPreviouslyCapturedError(x) {
4507
5800
  return isObject(x) && "__posthog_previously_captured_error" in x && x.__posthog_previously_captured_error === true;
4508
5801
  }
4509
- static async buildEventMessage(builder, error, hint, distinctId, additionalProperties) {
4510
- const properties = {
4511
- ...additionalProperties
4512
- };
4513
- const exceptionProperties = builder.buildFromUnknown(error, hint);
4514
- exceptionProperties.$exception_list = await builder.modifyFrames(exceptionProperties.$exception_list);
4515
- return {
4516
- event: "$exception",
4517
- distinctId,
4518
- properties: {
4519
- ...exceptionProperties,
4520
- ...properties
4521
- },
4522
- _originatedFromCaptureException: true
5802
+ static async buildEventMessage(builder, error, hint, distinctId, additionalProperties) {
5803
+ const properties = {
5804
+ ...additionalProperties
5805
+ };
5806
+ const exceptionProperties = builder.buildFromUnknown(error, hint);
5807
+ exceptionProperties.$exception_list = await builder.modifyFrames(exceptionProperties.$exception_list);
5808
+ const injectedReleaseId = exports_error_tracking.getInjectedReleaseId();
5809
+ if (injectedReleaseId)
5810
+ properties.$release_id = injectedReleaseId;
5811
+ return {
5812
+ event: "$exception",
5813
+ distinctId,
5814
+ properties: {
5815
+ ...exceptionProperties,
5816
+ ...properties
5817
+ },
5818
+ _originatedFromCaptureException: true
5819
+ };
5820
+ }
5821
+ startAutocaptureIfEnabled() {
5822
+ if (this.isEnabled()) {
5823
+ addUncaughtExceptionListener(this.onException.bind(this), this.onFatalError.bind(this));
5824
+ addUnhandledRejectionListener(this.onException.bind(this));
5825
+ }
5826
+ }
5827
+ onException(exception, hint) {
5828
+ this.client.addPendingPromise((async () => {
5829
+ if (!error_tracking_ErrorTracking.isPreviouslyCapturedError(exception)) {
5830
+ const eventMessage = await error_tracking_ErrorTracking.buildEventMessage(this.client.getErrorPropertiesBuilder(), exception, hint);
5831
+ const exceptionProperties = eventMessage.properties;
5832
+ const exceptionType = exceptionProperties?.$exception_list[0]?.type ?? "Exception";
5833
+ const isRateLimited = this._rateLimiter.consumeRateLimit(exceptionType);
5834
+ if (isRateLimited)
5835
+ return void this._logger.info("Skipping exception capture because of client rate limiting.", {
5836
+ exception: exceptionType
5837
+ });
5838
+ return this.client._capturePreparedEvent(eventMessage, false);
5839
+ }
5840
+ })());
5841
+ }
5842
+ async onFatalError(exception) {
5843
+ console.error(exception);
5844
+ await this.client.shutdown(SHUTDOWN_TIMEOUT);
5845
+ globalThis.process.exit(1);
5846
+ }
5847
+ isEnabled() {
5848
+ return !this.client.isDisabled && this._exceptionAutocaptureEnabled;
5849
+ }
5850
+ shutdown() {
5851
+ this._rateLimiter.stop();
5852
+ }
5853
+ }
5854
+ var SHUTDOWN_TIMEOUT = 2000;
5855
+ var init_error_tracking2 = __esm(() => {
5856
+ init_autocapture();
5857
+ init_dist();
5858
+ });
5859
+
5860
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/storage-memory.mjs
5861
+ class PostHogMemoryStorage {
5862
+ getProperty(key) {
5863
+ return this._memoryStorage[key];
5864
+ }
5865
+ setProperty(key, value) {
5866
+ this._memoryStorage[key] = value !== null ? value : undefined;
5867
+ }
5868
+ constructor() {
5869
+ this._memoryStorage = {};
5870
+ }
5871
+ }
5872
+ var init_storage_memory = () => {};
5873
+
5874
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/capture-v1/config.mjs
5875
+ function isCaptureMode(value) {
5876
+ return value === "v0" || value === "v1";
5877
+ }
5878
+ function resolveCaptureMode() {
5879
+ const envMode = typeof process != "undefined" ? process.env?.POSTHOG_CAPTURE_MODE : undefined;
5880
+ return isCaptureMode(envMode) ? envMode : "v0";
5881
+ }
5882
+ var init_config2 = () => {};
5883
+
5884
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/capture-v1/routing.mjs
5885
+ function isLegacyOnlyEvent(message) {
5886
+ return typeof message.event == "string" && message.event.startsWith(AI_EVENT_PREFIX);
5887
+ }
5888
+ var AI_EVENT_PREFIX = "$ai_", ANALYTICS_ROUTE = "analytics", AI_ROUTE = "ai";
5889
+ var init_routing = () => {};
5890
+
5891
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/capture-v1/errors.mjs
5892
+ var CaptureV1Error;
5893
+ var init_errors = __esm(() => {
5894
+ CaptureV1Error = class CaptureV1Error extends Error {
5895
+ constructor({ requestId, drops, retryExhausted, cause }) {
5896
+ super(CaptureV1Error.buildMessage(requestId, drops, retryExhausted, cause)), this.name = "CaptureV1Error";
5897
+ this.requestId = requestId;
5898
+ this.drops = drops;
5899
+ this.retryExhausted = retryExhausted;
5900
+ this.cause = cause;
5901
+ }
5902
+ static buildMessage(requestId, drops, retryExhausted, cause) {
5903
+ let message = `Capture V1 batch ${requestId} did not fully deliver: ${drops.length} dropped, ${retryExhausted.length} undelivered`;
5904
+ if (cause instanceof Error)
5905
+ message += ` (${cause.message})`;
5906
+ return message;
5907
+ }
5908
+ };
5909
+ });
5910
+
5911
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/capture-v1/transform.mjs
5912
+ function coerceBool(value) {
5913
+ if (typeof value == "boolean")
5914
+ return value;
5915
+ if (typeof value == "number")
5916
+ return value !== 0;
5917
+ if (typeof value == "string") {
5918
+ const normalized = value.trim().toLowerCase();
5919
+ if (normalized === "true" || normalized === "1")
5920
+ return true;
5921
+ if (normalized === "false" || normalized === "0")
5922
+ return false;
5923
+ }
5924
+ }
5925
+ function coerceString(value) {
5926
+ return typeof value == "string" ? value : undefined;
5927
+ }
5928
+ function isRecord3(value) {
5929
+ return typeof value == "object" && value !== null && !Array.isArray(value);
5930
+ }
5931
+ function toRfc3339(timestamp) {
5932
+ if (typeof timestamp == "string") {
5933
+ const asDate2 = new Date(timestamp);
5934
+ if (Number.isNaN(asDate2.getTime()))
5935
+ return new Date().toISOString();
5936
+ const normalized = asDate2.toISOString();
5937
+ const fractionalSeconds = timestamp.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];
5938
+ return fractionalSeconds && fractionalSeconds.length > 3 ? normalized.replace(/\.\d{3}Z$/, `.${fractionalSeconds}Z`) : normalized;
5939
+ }
5940
+ if (timestamp instanceof Date)
5941
+ return Number.isNaN(timestamp.getTime()) ? new Date().toISOString() : timestamp.toISOString();
5942
+ const asDate = timestamp == null ? new Date : new Date(timestamp);
5943
+ return Number.isNaN(asDate.getTime()) ? new Date().toISOString() : asDate.toISOString();
5944
+ }
5945
+ function relocateInto(properties, key, value) {
5946
+ if (value !== undefined && !(key in properties))
5947
+ properties[key] = value;
5948
+ }
5949
+ function buildV1Event(message) {
5950
+ const sourceProperties = isRecord3(message.properties) ? message.properties : {};
5951
+ const properties = {
5952
+ ...sourceProperties
5953
+ };
5954
+ const options = {};
5955
+ for (const { property, optionKey, coerce } of OPTION_SENTINELS)
5956
+ if (property in properties) {
5957
+ const coerced = coerce(properties[property]);
5958
+ if (coerced !== undefined)
5959
+ options[optionKey] = coerced;
5960
+ delete properties[property];
5961
+ }
5962
+ const topLevel = {};
5963
+ for (const { property, field } of TOPLEVEL_SENTINELS)
5964
+ if (property in properties) {
5965
+ const value = properties[property];
5966
+ if (typeof value == "string")
5967
+ topLevel[field] = value;
5968
+ delete properties[property];
5969
+ }
5970
+ delete properties.$lib;
5971
+ delete properties.$lib_version;
5972
+ relocateInto(properties, "$set", message.$set);
5973
+ relocateInto(properties, "$set_once", message.$set_once);
5974
+ return {
5975
+ event: String(message.event ?? ""),
5976
+ uuid: String(message.uuid ?? ""),
5977
+ distinct_id: String(message.distinct_id ?? ""),
5978
+ timestamp: toRfc3339(message.timestamp),
5979
+ ...topLevel,
5980
+ options,
5981
+ properties
5982
+ };
5983
+ }
5984
+ function buildV1Batch(messages, { createdAt, historicalMigration }) {
5985
+ const batch = {
5986
+ created_at: createdAt,
5987
+ batch: messages.map(buildV1Event)
5988
+ };
5989
+ if (historicalMigration)
5990
+ batch.historical_migration = true;
5991
+ return batch;
5992
+ }
5993
+ var OPTION_SENTINELS, TOPLEVEL_SENTINELS;
5994
+ var init_transform = __esm(() => {
5995
+ OPTION_SENTINELS = [
5996
+ {
5997
+ property: "$cookieless_mode",
5998
+ optionKey: "cookieless_mode",
5999
+ coerce: coerceBool
6000
+ },
6001
+ {
6002
+ property: "$ignore_sent_at",
6003
+ optionKey: "disable_skew_correction",
6004
+ coerce: coerceBool
6005
+ },
6006
+ {
6007
+ property: "$process_person_profile",
6008
+ optionKey: "process_person_profile",
6009
+ coerce: coerceBool
6010
+ },
6011
+ {
6012
+ property: "$product_tour_id",
6013
+ optionKey: "product_tour_id",
6014
+ coerce: coerceString
6015
+ }
6016
+ ];
6017
+ TOPLEVEL_SENTINELS = [
6018
+ {
6019
+ property: "$session_id",
6020
+ field: "session_id"
6021
+ },
6022
+ {
6023
+ property: "$window_id",
6024
+ field: "window_id"
6025
+ }
6026
+ ];
6027
+ });
6028
+
6029
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/capture-v1/sender.mjs
6030
+ class V1CaptureSender {
6031
+ constructor(config, hooks) {
6032
+ this.config = config;
6033
+ this.maxBackoffMs = config.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS;
6034
+ this.fetchFn = hooks.fetch;
6035
+ this.onError = hooks.onError;
6036
+ this.now = hooks.now ?? Date.now;
6037
+ this.sleep = hooks.sleep ?? ((ms) => new Promise((resolve9) => safeSetTimeout(resolve9, ms)));
6038
+ this.generateRequestId = hooks.generateRequestId ?? uuidv7;
6039
+ this.compress = hooks.compress ?? gzipCompress;
6040
+ }
6041
+ async sendV1Batch(messages) {
6042
+ if (messages.length === 0)
6043
+ return;
6044
+ const requestId = this.generateRequestId();
6045
+ const createdAt = new Date(this.now()).toISOString();
6046
+ const { batch } = buildV1Batch(messages, {
6047
+ createdAt,
6048
+ historicalMigration: this.config.historicalMigration
6049
+ });
6050
+ const url = `${this.config.host}${V1_ANALYTICS_PATH}`;
6051
+ const drops = [];
6052
+ let pending = batch;
6053
+ const maxAttempts = Math.max(1, this.config.maxAttempts);
6054
+ for (let attempt = 1;attempt <= maxAttempts; attempt++) {
6055
+ const isLastAttempt = attempt === maxAttempts;
6056
+ const payload = safeJsonStringify({
6057
+ created_at: createdAt,
6058
+ ...this.config.historicalMigration ? {
6059
+ historical_migration: true
6060
+ } : {},
6061
+ batch: pending
6062
+ });
6063
+ let captureAttempt;
6064
+ let retryDelayMs;
6065
+ try {
6066
+ captureAttempt = await this.sendOnce(url, payload, attempt, requestId);
6067
+ const { response, signal } = captureAttempt;
6068
+ const { status } = response;
6069
+ if (status < 200 || status >= 300)
6070
+ if (!isLastAttempt && RETRYABLE_STATUSES.has(status)) {
6071
+ const retryAfterMs = this.parseRetryAfter(response);
6072
+ await captureAttempt.waitFor(captureAttempt.cancelBody()).catch(() => {});
6073
+ retryDelayMs = this.backoffDelay(attempt, retryAfterMs);
6074
+ } else {
6075
+ const httpError = await this.buildHttpError(response, status, captureAttempt.waitFor);
6076
+ return this.surfaceBatchFailure(requestId, drops, pending, httpError);
6077
+ }
6078
+ else {
6079
+ let parsed;
6080
+ try {
6081
+ parsed = await captureAttempt.waitFor(this.parseResponse(response));
6082
+ } catch (error) {
6083
+ if (signal.aborted)
6084
+ throw error;
6085
+ return this.surfaceBatchFailure(requestId, drops, pending, new Error(`Capture V1 returned an unparseable ${status} response body`));
6086
+ }
6087
+ const retryable = this.classify(pending, parsed, drops);
6088
+ if (retryable.length === 0)
6089
+ return this.surfacePartialDrops(requestId, drops);
6090
+ if (isLastAttempt)
6091
+ return void this.onError(new CaptureV1Error({
6092
+ requestId,
6093
+ drops,
6094
+ retryExhausted: retryable.map((event) => event.uuid)
6095
+ }));
6096
+ pending = retryable;
6097
+ const retryAfterMs = this.parseRetryAfter(response);
6098
+ retryDelayMs = this.backoffDelay(attempt, retryAfterMs);
6099
+ }
6100
+ } catch (transportError) {
6101
+ if (captureAttempt && !captureAttempt.signal.aborted)
6102
+ throw transportError;
6103
+ if (isLastAttempt)
6104
+ return this.surfaceBatchFailure(requestId, drops, pending, transportError);
6105
+ retryDelayMs = this.backoffDelay(attempt);
6106
+ } finally {
6107
+ captureAttempt?.cleanup();
6108
+ }
6109
+ if (retryDelayMs !== undefined)
6110
+ await this.sleep(retryDelayMs);
6111
+ }
6112
+ }
6113
+ async sendOnce(url, payload, attempt, requestId) {
6114
+ const headers = this.buildHeaders(attempt, requestId);
6115
+ let body = payload;
6116
+ if (this.config.compressionEnabled) {
6117
+ const compressed = await this.compress(payload, this.config.isDebug);
6118
+ if (compressed !== null) {
6119
+ body = compressed;
6120
+ headers["Content-Encoding"] = "gzip";
6121
+ }
6122
+ }
6123
+ const controller = new AbortController;
6124
+ let timeoutPhase = "waiting for response headers";
6125
+ let timer;
6126
+ const deadline = new Promise((_resolve, reject) => {
6127
+ timer = safeSetTimeout(() => {
6128
+ const timeoutError = new Error(`Capture V1 request timed out ${timeoutPhase} after ${this.config.requestTimeoutMs}ms`);
6129
+ timeoutError.name = "AbortError";
6130
+ reject(timeoutError);
6131
+ controller.abort(timeoutError);
6132
+ }, this.config.requestTimeoutMs);
6133
+ });
6134
+ try {
6135
+ const fetchPromise = this.fetchFn(url, {
6136
+ method: "POST",
6137
+ headers,
6138
+ body,
6139
+ signal: controller.signal
6140
+ });
6141
+ let responseAccepted = false;
6142
+ fetchPromise.then((lateResponse) => {
6143
+ if (controller.signal.aborted && !responseAccepted)
6144
+ this.cancelBody(lateResponse);
6145
+ }).catch(() => {});
6146
+ const response = await Promise.race([
6147
+ fetchPromise,
6148
+ deadline
6149
+ ]);
6150
+ responseAccepted = true;
6151
+ timeoutPhase = "while reading the response body";
6152
+ let cleanedUp = false;
6153
+ let cancellation;
6154
+ const cancelBody = () => cancellation ??= this.cancelBody(response);
6155
+ return {
6156
+ response,
6157
+ signal: controller.signal,
6158
+ waitFor: (operation) => Promise.race([
6159
+ operation,
6160
+ deadline
6161
+ ]),
6162
+ cancelBody,
6163
+ cleanup: () => {
6164
+ if (cleanedUp)
6165
+ return;
6166
+ cleanedUp = true;
6167
+ clearTimeout(timer);
6168
+ if (controller.signal.aborted)
6169
+ cancelBody();
6170
+ }
6171
+ };
6172
+ } catch (error) {
6173
+ clearTimeout(timer);
6174
+ throw error;
6175
+ }
6176
+ }
6177
+ buildHeaders(attempt, requestId) {
6178
+ const sdkInfo = `${this.config.libraryId}/${this.config.libraryVersion}`;
6179
+ const headers = {
6180
+ "Content-Type": "application/json",
6181
+ Authorization: `Bearer ${this.config.apiKey}`,
6182
+ "PostHog-Sdk-Info": sdkInfo,
6183
+ "PostHog-Attempt": String(attempt),
6184
+ "PostHog-Request-Id": requestId,
6185
+ "PostHog-Request-Timestamp": new Date(this.now()).toISOString()
4523
6186
  };
6187
+ if (this.config.userAgent)
6188
+ headers["User-Agent"] = this.config.userAgent;
6189
+ return headers;
4524
6190
  }
4525
- startAutocaptureIfEnabled() {
4526
- if (this.isEnabled()) {
4527
- addUncaughtExceptionListener(this.onException.bind(this), this.onFatalError.bind(this));
4528
- addUnhandledRejectionListener(this.onException.bind(this));
4529
- }
4530
- }
4531
- onException(exception, hint) {
4532
- this.client.addPendingPromise((async () => {
4533
- if (!ErrorTracking.isPreviouslyCapturedError(exception)) {
4534
- const eventMessage = await ErrorTracking.buildEventMessage(this.client.getErrorPropertiesBuilder(), exception, hint);
4535
- const exceptionProperties = eventMessage.properties;
4536
- const exceptionType = exceptionProperties?.$exception_list[0]?.type ?? "Exception";
4537
- const isRateLimited = this._rateLimiter.consumeRateLimit(exceptionType);
4538
- if (isRateLimited)
4539
- return void this._logger.info("Skipping exception capture because of client rate limiting.", {
4540
- exception: exceptionType
6191
+ classify(pending, parsed, drops) {
6192
+ const results = parsed.results ?? {};
6193
+ const retryable = [];
6194
+ for (const event of pending) {
6195
+ const result = results[event.uuid];
6196
+ if (result) {
6197
+ if (result.result === "drop")
6198
+ drops.push({
6199
+ uuid: event.uuid,
6200
+ details: result.details ?? undefined
4541
6201
  });
4542
- return this.client.capture(eventMessage);
6202
+ else if (result.result === "retry")
6203
+ retryable.push(event);
4543
6204
  }
4544
- })());
6205
+ }
6206
+ return retryable;
4545
6207
  }
4546
- async onFatalError(exception) {
4547
- console.error(exception);
4548
- await this.client.shutdown(SHUTDOWN_TIMEOUT);
4549
- process.exit(1);
6208
+ backoffDelay(attempt, retryAfterMs) {
6209
+ const exponential = Math.min(this.config.initialRetryDelayMs * 2 ** (attempt - 1), this.maxBackoffMs);
6210
+ if (retryAfterMs === undefined)
6211
+ return exponential;
6212
+ return Math.max(exponential, Math.min(retryAfterMs, this.maxBackoffMs));
4550
6213
  }
4551
- isEnabled() {
4552
- return !this.client.isDisabled && this._exceptionAutocaptureEnabled;
6214
+ parseRetryAfter(response) {
6215
+ const raw = response.headers?.get("Retry-After");
6216
+ if (!raw)
6217
+ return;
6218
+ const trimmed = raw.trim();
6219
+ if (/^\d+$/.test(trimmed)) {
6220
+ const seconds = parseInt(trimmed, 10);
6221
+ return Number.isFinite(seconds) && seconds > 0 ? 1000 * seconds : undefined;
6222
+ }
6223
+ const dateMs = Date.parse(trimmed);
6224
+ if (Number.isNaN(dateMs))
6225
+ return;
6226
+ const delta = dateMs - this.now();
6227
+ return delta > 0 ? delta : undefined;
6228
+ }
6229
+ async parseResponse(response) {
6230
+ const text = await response.text();
6231
+ const parsed = JSON.parse(text);
6232
+ if (typeof parsed != "object" || parsed === null || Array.isArray(parsed))
6233
+ throw new Error("unexpected response shape");
6234
+ const results = parsed.results;
6235
+ if (results !== undefined && (typeof results != "object" || results === null || Array.isArray(results)))
6236
+ throw new Error("unexpected results shape");
6237
+ return {
6238
+ results: results ?? {}
6239
+ };
4553
6240
  }
4554
- shutdown() {
4555
- this._rateLimiter.stop();
6241
+ async buildHttpError(response, status, waitFor) {
6242
+ let bodyText = "";
6243
+ try {
6244
+ bodyText = (await waitFor(response.text())).slice(0, 512);
6245
+ } catch {}
6246
+ const suffix = bodyText ? `: ${bodyText}` : "";
6247
+ return new Error(`Capture V1 request failed with HTTP ${status}${suffix}`);
6248
+ }
6249
+ surfaceBatchFailure(requestId, drops, pending, cause) {
6250
+ this.onError(new CaptureV1Error({
6251
+ requestId,
6252
+ drops,
6253
+ retryExhausted: pending.map((event) => event.uuid),
6254
+ cause
6255
+ }));
6256
+ }
6257
+ surfacePartialDrops(requestId, drops) {
6258
+ if (drops.length > 0)
6259
+ this.onError(new CaptureV1Error({
6260
+ requestId,
6261
+ drops,
6262
+ retryExhausted: []
6263
+ }));
6264
+ }
6265
+ async cancelBody(response) {
6266
+ try {
6267
+ await response.body?.cancel();
6268
+ } catch {}
4556
6269
  }
4557
6270
  }
4558
- var SHUTDOWN_TIMEOUT = 2000;
4559
- var init_error_tracking2 = __esm(() => {
4560
- init_autocapture();
6271
+ var V1_ANALYTICS_PATH = "/i/v1/analytics/events", DEFAULT_MAX_BACKOFF_MS = 30000, RETRYABLE_STATUSES;
6272
+ var init_sender = __esm(() => {
4561
6273
  init_dist();
6274
+ init_errors();
6275
+ init_transform();
6276
+ RETRYABLE_STATUSES = new Set([
6277
+ 408,
6278
+ 500,
6279
+ 502,
6280
+ 503,
6281
+ 504
6282
+ ]);
4562
6283
  });
4563
6284
 
4564
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/storage-memory.mjs
4565
- class PostHogMemoryStorage {
4566
- getProperty(key) {
4567
- return this._memoryStorage[key];
4568
- }
4569
- setProperty(key, value) {
4570
- this._memoryStorage[key] = value !== null ? value : undefined;
4571
- }
4572
- constructor() {
4573
- this._memoryStorage = {};
6285
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/ai-capture/routing.mjs
6286
+ var AI_CAPTURE_ROUTE = "ai-capture", AI_CAPTURE_ENDPOINT_PATH = "/i/v0/ai/batch/", AI_MAX_EVENT_BYTES = 8388608, AI_BATCH_TARGET_BYTES = 5242880;
6287
+ var init_routing2 = () => {};
6288
+
6289
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/ai-capture/batching.mjs
6290
+ function eventByteSize(message) {
6291
+ return encoder.encode(safeJsonStringify(message)).length;
6292
+ }
6293
+ function partitionAiBatch(messages, maxEventBytes = AI_MAX_EVENT_BYTES, targetBatchBytes = AI_BATCH_TARGET_BYTES) {
6294
+ const batches = [];
6295
+ const dropped = [];
6296
+ let current = [];
6297
+ let currentBytes = 0;
6298
+ for (const message of messages) {
6299
+ if (message === undefined)
6300
+ continue;
6301
+ const bytes = eventByteSize(message);
6302
+ if (bytes > maxEventBytes) {
6303
+ dropped.push({
6304
+ event: typeof message.event == "string" ? message.event : "unknown",
6305
+ bytes
6306
+ });
6307
+ continue;
6308
+ }
6309
+ if (current.length > 0 && currentBytes + bytes > targetBatchBytes) {
6310
+ batches.push(current);
6311
+ current = [];
6312
+ currentBytes = 0;
6313
+ }
6314
+ current.push(message);
6315
+ currentBytes += bytes;
4574
6316
  }
6317
+ if (current.length > 0)
6318
+ batches.push(current);
6319
+ return {
6320
+ batches,
6321
+ dropped
6322
+ };
4575
6323
  }
4576
- var init_storage_memory = () => {};
6324
+ var encoder;
6325
+ var init_batching = __esm(() => {
6326
+ init_dist();
6327
+ init_routing2();
6328
+ encoder = new TextEncoder;
6329
+ });
4577
6330
 
4578
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/client.mjs
6331
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/client.mjs
4579
6332
  function emitDeprecationWarningOnce(id, message) {
4580
6333
  if (_emittedDeprecations.has(id))
4581
6334
  return;
@@ -4593,6 +6346,12 @@ function normalizeHost(value) {
4593
6346
  const normalizedValue = typeof value == "string" ? value.trim() : "";
4594
6347
  return normalizedValue || DEFAULT_NODE_HOST;
4595
6348
  }
6349
+ function normalizeUnsetPersonProperties(value) {
6350
+ const propertyNames = Array.isArray(value) ? value : [
6351
+ value
6352
+ ];
6353
+ return propertyNames.filter((propertyName) => typeof propertyName == "string" && propertyName.trim().length > 0);
6354
+ }
4596
6355
  function buildFlagEventProperties(flagValues) {
4597
6356
  if (!flagValues)
4598
6357
  return {};
@@ -4613,17 +6372,26 @@ var init_client = __esm(() => {
4613
6372
  init_feature_flags();
4614
6373
  init_error_tracking2();
4615
6374
  init_storage_memory();
6375
+ init_config2();
6376
+ init_routing();
6377
+ init_sender();
6378
+ init_batching();
6379
+ init_routing2();
4616
6380
  _emittedDeprecations = new Set;
4617
6381
  PostHogBackendClient = class PostHogBackendClient extends PostHogCoreStateless {
4618
6382
  constructor(apiKey, options = {}) {
4619
6383
  const normalizedApiKey = normalizeApiKey(apiKey);
4620
6384
  const normalizedOptions = {
4621
6385
  ...options,
6386
+ maxQueueSize: options.maxQueueSize ?? 1e4,
6387
+ flushInterval: options.flushInterval ?? 5000,
4622
6388
  host: normalizeHost(options.host),
4623
- personalApiKey: normalizePersonalApiKey(options.personalApiKey)
6389
+ personalApiKey: normalizePersonalApiKey(options.secretKey ?? options.personalApiKey)
4624
6390
  };
4625
- super(normalizedApiKey, normalizedOptions), this._memoryStorage = new PostHogMemoryStorage;
6391
+ super(normalizedApiKey, normalizedOptions), this._memoryStorage = new PostHogMemoryStorage, this._aiCaptureRouteActive = false, this._minimalFlagCalledEvents = false;
4626
6392
  this.options = normalizedOptions;
6393
+ this.captureMode = resolveCaptureMode();
6394
+ this.enableFullAiCapture = normalizedOptions.enableFullAiCapture === true;
4627
6395
  this.context = this.initializeContext();
4628
6396
  this.options.featureFlagsPollingInterval = typeof normalizedOptions.featureFlagsPollingInterval == "number" ? Math.max(normalizedOptions.featureFlagsPollingInterval, MINIMUM_POLLING_INTERVAL) : THIRTY_SECONDS;
4629
6397
  if (typeof normalizedOptions.waitUntilDebounceMs == "number")
@@ -4648,21 +6416,24 @@ var init_client = __esm(() => {
4648
6416
  onLoad: (count) => {
4649
6417
  this._events.emit("localEvaluationFlagsLoaded", count);
4650
6418
  },
6419
+ onMinimalFlagCalledEvents: (enabled) => {
6420
+ this._minimalFlagCalledEvents = enabled;
6421
+ },
4651
6422
  customHeaders: this.getCustomHeaders(),
4652
6423
  cacheProvider: normalizedOptions.flagDefinitionCacheProvider,
4653
6424
  strictLocalEvaluation: normalizedOptions.strictLocalEvaluation
4654
6425
  });
4655
6426
  }
4656
- this.errorTracking = new ErrorTracking(this, normalizedOptions, this._logger);
6427
+ this.errorTracking = new error_tracking_ErrorTracking(this, normalizedOptions, this._logger);
4657
6428
  this.distinctIdHasSentFlagCalls = {};
4658
6429
  this.maxCacheSize = normalizedOptions.maxCacheSize || MAX_CACHE_SIZE;
4659
6430
  }
4660
- enqueue(type, message, options) {
4661
- super.enqueue(type, message, options);
6431
+ enqueue(type, message, options, explicitRoute) {
6432
+ super.enqueue(type, message, options, explicitRoute);
4662
6433
  this.scheduleDebouncedFlush();
4663
6434
  }
4664
6435
  async flush() {
4665
- const flushPromise = super.flush();
6436
+ const flushPromise = this.flushWithPendingPromises();
4666
6437
  const waitUntil = this.options.waitUntil;
4667
6438
  if (waitUntil && !this._waitUntilCycle)
4668
6439
  try {
@@ -4715,7 +6486,7 @@ var init_client = __esm(() => {
4715
6486
  async resolveWaitUntilFlush() {
4716
6487
  const resolve9 = this._consumeWaitUntilCycle();
4717
6488
  try {
4718
- await super.flush();
6489
+ await this.flushWithPendingPromises();
4719
6490
  } catch {} finally {
4720
6491
  resolve9?.();
4721
6492
  }
@@ -4729,12 +6500,103 @@ var init_client = __esm(() => {
4729
6500
  fetch(url, options) {
4730
6501
  return this.options.fetch ? this.options.fetch(url, options) : fetch(url, options);
4731
6502
  }
6503
+ getQueueRouteKey(message) {
6504
+ return this.captureMode === "v1" && isLegacyOnlyEvent(message) ? AI_ROUTE : ANALYTICS_ROUTE;
6505
+ }
6506
+ persistedQueueKeyForRoute(route) {
6507
+ if (route === AI_CAPTURE_ROUTE)
6508
+ return types_PostHogPersistedProperty.AiCaptureQueue;
6509
+ return route === AI_ROUTE ? types_PostHogPersistedProperty.AiQueue : types_PostHogPersistedProperty.Queue;
6510
+ }
6511
+ getActiveQueueRoutes() {
6512
+ const routes = this.captureMode === "v1" ? [
6513
+ ANALYTICS_ROUTE,
6514
+ AI_ROUTE
6515
+ ] : [
6516
+ ANALYTICS_ROUTE
6517
+ ];
6518
+ if (this._aiCaptureRouteActive)
6519
+ routes.push(AI_CAPTURE_ROUTE);
6520
+ return routes;
6521
+ }
6522
+ getBatchEndpointPath(route) {
6523
+ return route === AI_CAPTURE_ROUTE ? AI_CAPTURE_ENDPOINT_PATH : super.getBatchEndpointPath(route);
6524
+ }
6525
+ async sendBatch(batchMessages, retryOptions, route = ANALYTICS_ROUTE) {
6526
+ if (route === AI_CAPTURE_ROUTE)
6527
+ return this.sendAiCaptureBatch(batchMessages, retryOptions);
6528
+ if (this.captureMode !== "v1" || route === AI_ROUTE)
6529
+ return super.sendBatch(batchMessages, retryOptions, route);
6530
+ const v1Events = batchMessages.filter((message) => message !== undefined);
6531
+ await this.getV1Sender().sendV1Batch(v1Events);
6532
+ }
6533
+ async sendAiCaptureBatch(batchMessages, retryOptions) {
6534
+ const { batches, dropped } = partitionAiBatch(batchMessages);
6535
+ for (const { event, bytes } of dropped) {
6536
+ const message = `Event ${event} (${bytes} bytes) exceeds the ${AI_MAX_EVENT_BYTES / 1048576}MiB limit for ${AI_CAPTURE_ENDPOINT_PATH}, dropping.`;
6537
+ this._logger.error(message);
6538
+ this._events.emit("error", new Error(message));
6539
+ }
6540
+ for (const batch of batches)
6541
+ await this.sendAiSubBatch(batch, retryOptions);
6542
+ }
6543
+ async sendAiSubBatch(batch, retryOptions) {
6544
+ try {
6545
+ await super.sendBatch(batch, retryOptions, AI_CAPTURE_ROUTE);
6546
+ } catch (err) {
6547
+ if (!isPostHogFetchContentTooLargeError(err))
6548
+ throw err;
6549
+ if (batch.length === 1) {
6550
+ const [event] = batch;
6551
+ const eventName = typeof event.event == "string" ? event.event : "unknown";
6552
+ const message = `Event ${eventName} (${eventByteSize(event)} bytes) was rejected with 413 by ${AI_CAPTURE_ENDPOINT_PATH} on its own, dropping.`;
6553
+ this._logger.error(message);
6554
+ this._events.emit("error", new Error(message));
6555
+ return;
6556
+ }
6557
+ const mid = Math.ceil(batch.length / 2);
6558
+ await this.sendAiSubBatch(batch.slice(0, mid), retryOptions);
6559
+ await this.sendAiSubBatch(batch.slice(mid), retryOptions);
6560
+ }
6561
+ }
6562
+ getV1Sender() {
6563
+ if (!this._v1Sender)
6564
+ this._v1Sender = new V1CaptureSender({
6565
+ host: this.host,
6566
+ apiKey: this.apiKey,
6567
+ libraryId: this.getLibraryId(),
6568
+ libraryVersion: this.getLibraryVersion(),
6569
+ userAgent: this.getCustomUserAgent() || undefined,
6570
+ historicalMigration: this.historicalMigration,
6571
+ compressionEnabled: !this.disableCompression,
6572
+ requestTimeoutMs: this.requestTimeout,
6573
+ maxAttempts: (this.options.fetchRetryCount ?? 3) + 1,
6574
+ initialRetryDelayMs: this.options.fetchRetryDelay ?? 3000,
6575
+ isDebug: this.isDebug
6576
+ }, {
6577
+ fetch: (url, fetchOptions) => this.fetch(url, fetchOptions),
6578
+ onError: (error) => this._events.emit("error", error),
6579
+ compress: (payload) => this.compressPayload(payload)
6580
+ });
6581
+ return this._v1Sender;
6582
+ }
4732
6583
  getLibraryVersion() {
4733
6584
  return version;
4734
6585
  }
6586
+ get metrics() {
6587
+ if (!this._metrics)
6588
+ this._metrics = new PostHogMetrics(this, resolveMetricsConfig(this.options.metrics), this._logger);
6589
+ return this._metrics;
6590
+ }
4735
6591
  getCustomUserAgent() {
4736
6592
  return `${this.getLibraryId()}/${this.getLibraryVersion()}`;
4737
6593
  }
6594
+ getCommonEventProperties() {
6595
+ const commonProperties = super.getCommonEventProperties();
6596
+ if (this.options.isServer ?? true)
6597
+ commonProperties.$is_server = true;
6598
+ return commonProperties;
6599
+ }
4738
6600
  enable() {
4739
6601
  return super.optIn();
4740
6602
  }
@@ -4745,33 +6607,69 @@ var init_client = __esm(() => {
4745
6607
  super.debug(enabled);
4746
6608
  this.featureFlagsPoller?.debug(enabled);
4747
6609
  }
4748
- capture(props) {
6610
+ _warnIfInvalidCapture(props, stringArgumentWarning, exceptionCaptureWarning) {
4749
6611
  if (typeof props == "string")
4750
- this._logger.warn("Called capture() with a string as the first argument when an object was expected.");
6612
+ this._logger.warn(stringArgumentWarning);
4751
6613
  if (props.event === "$exception" && !props._originatedFromCaptureException)
4752
- 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.");
4753
- this.addPendingPromise(this.prepareEventMessage(props).then(({ distinctId, event, properties, options }) => super.captureStateless(distinctId, event, properties, {
4754
- timestamp: options.timestamp,
4755
- disableGeoip: options.disableGeoip,
4756
- uuid: options.uuid
4757
- })).catch((err) => {
6614
+ this._logger.warn(exceptionCaptureWarning);
6615
+ }
6616
+ _sendPreparedEvent(type, props, immediate, prepareOptions, explicitRoute) {
6617
+ return this.addPendingPromise(this._prepareEventMessage(props, prepareOptions).then(({ distinctId, event, properties, options }) => {
6618
+ const captureOptions = {
6619
+ timestamp: options.timestamp,
6620
+ disableGeoip: options.disableGeoip,
6621
+ uuid: options.uuid
6622
+ };
6623
+ const message = {
6624
+ distinctId,
6625
+ event,
6626
+ properties: {
6627
+ ...properties,
6628
+ ...this.getCommonEventProperties()
6629
+ }
6630
+ };
6631
+ return immediate ? this.sendImmediate(type, message, captureOptions, explicitRoute) : this.enqueue(type, message, captureOptions, explicitRoute);
6632
+ }).catch((err) => {
4758
6633
  if (err)
4759
6634
  console.error(err);
4760
6635
  }));
4761
6636
  }
6637
+ _capturePreparedEvent(props, immediate) {
6638
+ return this._sendPreparedEvent("capture", props, immediate);
6639
+ }
6640
+ capture(props) {
6641
+ 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.");
6642
+ this._capturePreparedEvent(props, false);
6643
+ }
4762
6644
  async captureImmediate(props) {
4763
- if (typeof props == "string")
4764
- this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected.");
4765
- if (props.event === "$exception" && !props._originatedFromCaptureException)
4766
- 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.");
4767
- return this.addPendingPromise(this.prepareEventMessage(props).then(({ distinctId, event, properties, options }) => super.captureStatelessImmediate(distinctId, event, properties, {
4768
- timestamp: options.timestamp,
4769
- disableGeoip: options.disableGeoip,
4770
- uuid: options.uuid
4771
- })).catch((err) => {
4772
- if (err)
4773
- console.error(err);
4774
- }));
6645
+ 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.");
6646
+ return this._capturePreparedEvent(props, true);
6647
+ }
6648
+ captureAi(props) {
6649
+ if (this.disabled)
6650
+ return;
6651
+ const uuid = getEventUuid(props.uuid, uuidv7);
6652
+ this._sendPreparedAiEvent({
6653
+ ...props,
6654
+ uuid
6655
+ }, false);
6656
+ return uuid;
6657
+ }
6658
+ async captureAiImmediate(props) {
6659
+ if (this.disabled)
6660
+ return;
6661
+ const uuid = getEventUuid(props.uuid, uuidv7);
6662
+ await this._sendPreparedAiEvent({
6663
+ ...props,
6664
+ uuid
6665
+ }, true);
6666
+ return uuid;
6667
+ }
6668
+ _sendPreparedAiEvent(props, immediate) {
6669
+ if (typeof props?.event == "string" && !props.event.startsWith("$ai_"))
6670
+ this._logger.debug(`captureAi called with non-AI event ${props.event}; routing it to the AI endpoint anyway.`);
6671
+ this._aiCaptureRouteActive = true;
6672
+ return this._sendPreparedEvent("capture", props, immediate, undefined, AI_CAPTURE_ROUTE);
4775
6673
  }
4776
6674
  identify({ distinctId, properties = {}, disableGeoip }) {
4777
6675
  const { $set, $set_once, $anon_distinct_id, ...rest } = properties;
@@ -4782,8 +6680,13 @@ var init_client = __esm(() => {
4782
6680
  $set_once: setOnceProps,
4783
6681
  $anon_distinct_id: $anon_distinct_id ?? undefined
4784
6682
  };
4785
- super.identifyStateless(distinctId, eventProperties, {
6683
+ this._sendPreparedEvent("identify", {
6684
+ distinctId,
6685
+ event: "$identify",
6686
+ properties: eventProperties,
4786
6687
  disableGeoip
6688
+ }, false, {
6689
+ includeContextProperties: false
4787
6690
  });
4788
6691
  }
4789
6692
  async identifyImmediate({ distinctId, properties = {}, disableGeoip }) {
@@ -4795,18 +6698,65 @@ var init_client = __esm(() => {
4795
6698
  $set_once: setOnceProps,
4796
6699
  $anon_distinct_id: $anon_distinct_id ?? undefined
4797
6700
  };
4798
- await super.identifyStatelessImmediate(distinctId, eventProperties, {
6701
+ await this._sendPreparedEvent("identify", {
6702
+ distinctId,
6703
+ event: "$identify",
6704
+ properties: eventProperties,
4799
6705
  disableGeoip
6706
+ }, true, {
6707
+ includeContextProperties: false
6708
+ });
6709
+ }
6710
+ setPersonProperties({ distinctId, properties = {}, propertiesOnce = {} }) {
6711
+ if (Object.keys(properties).length === 0 && Object.keys(propertiesOnce).length === 0)
6712
+ return;
6713
+ const eventProperties = {};
6714
+ if (Object.keys(properties).length > 0)
6715
+ eventProperties.$set = properties;
6716
+ if (Object.keys(propertiesOnce).length > 0)
6717
+ eventProperties.$set_once = propertiesOnce;
6718
+ this.capture({
6719
+ distinctId,
6720
+ event: "$set",
6721
+ properties: eventProperties
6722
+ });
6723
+ }
6724
+ unsetPersonProperties({ distinctId, properties }) {
6725
+ const propertyNames = normalizeUnsetPersonProperties(properties);
6726
+ if (propertyNames.length === 0)
6727
+ return;
6728
+ this.capture({
6729
+ distinctId,
6730
+ event: "$set",
6731
+ properties: {
6732
+ $unset: propertyNames
6733
+ }
4800
6734
  });
4801
6735
  }
4802
6736
  alias(data) {
4803
- super.aliasStateless(data.alias, data.distinctId, undefined, {
6737
+ this._sendPreparedEvent("alias", {
6738
+ distinctId: data.distinctId,
6739
+ event: "$create_alias",
6740
+ properties: {
6741
+ distinct_id: data.distinctId,
6742
+ alias: data.alias
6743
+ },
4804
6744
  disableGeoip: data.disableGeoip
6745
+ }, false, {
6746
+ includeContextProperties: false
4805
6747
  });
4806
6748
  }
4807
6749
  async aliasImmediate(data) {
4808
- await super.aliasStatelessImmediate(data.alias, data.distinctId, undefined, {
6750
+ await this._sendPreparedEvent("alias", {
6751
+ distinctId: data.distinctId,
6752
+ event: "$create_alias",
6753
+ properties: {
6754
+ distinct_id: data.distinctId,
6755
+ alias: data.alias
6756
+ },
4809
6757
  disableGeoip: data.disableGeoip
6758
+ }, true, {
6759
+ includeContextProperties: false
4810
6760
  });
4811
6761
  }
4812
6762
  isLocalEvaluationReady() {
@@ -4861,7 +6811,7 @@ var init_client = __esm(() => {
4861
6811
  const adjustedProperties = this.addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties);
4862
6812
  personProperties = adjustedProperties.allPersonProperties;
4863
6813
  groupProperties = adjustedProperties.allGroupProperties;
4864
- const evaluationContext = this.createFeatureFlagEvaluationContext(distinctId, groups, personProperties, groupProperties);
6814
+ const evaluationContext = this.createFeatureFlagEvaluationContext(distinctId, groups, this.personPropertiesForLocalEvaluation(distinctId, personProperties), groupProperties);
4865
6815
  if (onlyEvaluateLocally == undefined)
4866
6816
  onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;
4867
6817
  let result;
@@ -4872,6 +6822,7 @@ var init_client = __esm(() => {
4872
6822
  let flagId;
4873
6823
  let flagVersion;
4874
6824
  let flagReason;
6825
+ let flagHasExperiment;
4875
6826
  const localEvaluationEnabled = this.featureFlagsPoller !== undefined;
4876
6827
  if (localEvaluationEnabled) {
4877
6828
  await this.featureFlagsPoller?.loadFeatureFlags();
@@ -4886,6 +6837,7 @@ var init_client = __esm(() => {
4886
6837
  const value = localResult.value;
4887
6838
  flagId = flag.id;
4888
6839
  flagReason = "Evaluated locally";
6840
+ flagHasExperiment = flag.has_experiment;
4889
6841
  result = {
4890
6842
  key,
4891
6843
  enabled: value !== false,
@@ -4901,12 +6853,13 @@ var init_client = __esm(() => {
4901
6853
  }
4902
6854
  }
4903
6855
  if (!flagWasLocallyEvaluated && !onlyEvaluateLocally) {
4904
- const flagsResponse = await super.getFeatureFlagDetailsStateless(evaluationContext.distinctId, evaluationContext.groups, evaluationContext.personProperties, evaluationContext.groupProperties, disableGeoip, [
6856
+ const flagsResponse = await super.getFeatureFlagDetailsStateless(evaluationContext.distinctId, evaluationContext.groups, personProperties, groupProperties, disableGeoip, [
4905
6857
  key
4906
6858
  ]);
4907
6859
  if (flagsResponse === undefined)
4908
6860
  featureFlagError = FeatureFlagError2.UNKNOWN_ERROR;
4909
6861
  else {
6862
+ this._minimalFlagCalledEvents = flagsResponse.minimalFlagCalledEvents === true;
4910
6863
  requestId = flagsResponse.requestId;
4911
6864
  evaluatedAt = flagsResponse.evaluatedAt;
4912
6865
  const errors = [];
@@ -4921,6 +6874,7 @@ var init_client = __esm(() => {
4921
6874
  flagId = flagDetail.metadata?.id;
4922
6875
  flagVersion = flagDetail.metadata?.version;
4923
6876
  flagReason = flagDetail.reason?.description ?? flagDetail.reason?.code;
6877
+ flagHasExperiment = flagDetail.metadata?.has_experiment;
4924
6878
  let parsedPayload;
4925
6879
  if (flagDetail.metadata?.payload !== undefined)
4926
6880
  try {
@@ -4931,7 +6885,7 @@ var init_client = __esm(() => {
4931
6885
  result = {
4932
6886
  key,
4933
6887
  enabled: flagDetail.enabled,
4934
- variant: flagDetail.variant,
6888
+ variant: flagDetail.variant ?? undefined,
4935
6889
  payload: parsedPayload
4936
6890
  };
4937
6891
  }
@@ -4952,6 +6906,8 @@ var init_client = __esm(() => {
4952
6906
  $feature_flag_request_id: requestId,
4953
6907
  $feature_flag_evaluated_at: flagWasLocallyEvaluated ? Date.now() : evaluatedAt
4954
6908
  };
6909
+ if (flagHasExperiment !== undefined)
6910
+ properties.$feature_flag_has_experiment = flagHasExperiment;
4955
6911
  if (flagWasLocallyEvaluated && this.featureFlagsPoller) {
4956
6912
  const flagDefinitionsLoadedAt = this.featureFlagsPoller.getFlagDefinitionsLoadedAt();
4957
6913
  if (flagDefinitionsLoadedAt !== undefined)
@@ -5066,7 +7022,7 @@ var init_client = __esm(() => {
5066
7022
  const adjustedProperties = this.addLocalPersonAndGroupProperties(resolvedDistinctId, groups, personProperties, groupProperties);
5067
7023
  personProperties = adjustedProperties.allPersonProperties;
5068
7024
  groupProperties = adjustedProperties.allGroupProperties;
5069
- const evaluationContext = this.createFeatureFlagEvaluationContext(resolvedDistinctId, groups, personProperties, groupProperties);
7025
+ const evaluationContext = this.createFeatureFlagEvaluationContext(resolvedDistinctId, groups, this.personPropertiesForLocalEvaluation(resolvedDistinctId, personProperties), groupProperties);
5070
7026
  if (onlyEvaluateLocally == undefined)
5071
7027
  onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;
5072
7028
  const localEvaluationResult = await this.featureFlagsPoller?.getAllFlagsAndPayloads(evaluationContext, flagKeys);
@@ -5079,7 +7035,7 @@ var init_client = __esm(() => {
5079
7035
  fallbackToFlags = localEvaluationResult.fallbackToFlags;
5080
7036
  }
5081
7037
  if (fallbackToFlags && !onlyEvaluateLocally) {
5082
- const remoteEvaluationResult = await super.getFeatureFlagsAndPayloadsStateless(evaluationContext.distinctId, evaluationContext.groups, evaluationContext.personProperties, evaluationContext.groupProperties, disableGeoip, flagKeys);
7038
+ const remoteEvaluationResult = await super.getFeatureFlagsAndPayloadsStateless(evaluationContext.distinctId, evaluationContext.groups, personProperties, groupProperties, disableGeoip, flagKeys);
5083
7039
  featureFlags = {
5084
7040
  ...featureFlags,
5085
7041
  ...remoteEvaluationResult.flags || {}
@@ -5127,9 +7083,10 @@ var init_client = __esm(() => {
5127
7083
  const adjustedProperties = this.addLocalPersonAndGroupProperties(resolvedDistinctId, groups, personProperties, groupProperties);
5128
7084
  personProperties = adjustedProperties.allPersonProperties;
5129
7085
  groupProperties = adjustedProperties.allGroupProperties;
5130
- const evaluationContext = this.createFeatureFlagEvaluationContext(resolvedDistinctId, groups, personProperties, groupProperties);
7086
+ const evaluationContext = this.createFeatureFlagEvaluationContext(resolvedDistinctId, groups, this.personPropertiesForLocalEvaluation(resolvedDistinctId, personProperties), groupProperties);
5131
7087
  if (onlyEvaluateLocally == undefined)
5132
7088
  onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;
7089
+ const requestedFlagKeys = flagKeys ? new Set(flagKeys) : undefined;
5133
7090
  const records = {};
5134
7091
  let requestId;
5135
7092
  let evaluatedAt;
@@ -5148,14 +7105,17 @@ var init_client = __esm(() => {
5148
7105
  id: flagDef?.id,
5149
7106
  version: undefined,
5150
7107
  reason: "Evaluated locally",
5151
- locallyEvaluated: true
7108
+ locallyEvaluated: true,
7109
+ hasExperiment: flagDef?.has_experiment
5152
7110
  };
5153
7111
  locallyEvaluatedKeys.add(key);
5154
7112
  }
5155
- const fallbackToFlags = localResult ? localResult.fallbackToFlags : true;
7113
+ const requestedFlagMissingLocally = requestedFlagKeys !== undefined && Array.from(requestedFlagKeys).some((key) => this.featureFlagsPoller?.featureFlagsByKey[key] === undefined);
7114
+ const fallbackToFlags = localResult ? localResult.fallbackToFlags || requestedFlagMissingLocally : true;
5156
7115
  if (fallbackToFlags && !onlyEvaluateLocally) {
5157
- const details = await super.getFeatureFlagDetailsStateless(evaluationContext.distinctId, evaluationContext.groups, evaluationContext.personProperties, evaluationContext.groupProperties, disableGeoip, flagKeys);
7116
+ const details = await super.getFeatureFlagDetailsStateless(evaluationContext.distinctId, evaluationContext.groups, personProperties, groupProperties, disableGeoip, flagKeys);
5158
7117
  if (details) {
7118
+ this._minimalFlagCalledEvents = details.minimalFlagCalledEvents === true;
5159
7119
  requestId = details.requestId;
5160
7120
  evaluatedAt = details.evaluatedAt;
5161
7121
  errorsWhileComputing = Boolean(details.errorsWhileComputingFlags);
@@ -5178,7 +7138,8 @@ var init_client = __esm(() => {
5178
7138
  id: detail.metadata?.id,
5179
7139
  version: detail.metadata?.version,
5180
7140
  reason: detail.reason?.description ?? detail.reason?.code,
5181
- locallyEvaluated: false
7141
+ locallyEvaluated: false,
7142
+ hasExperiment: detail.metadata?.has_experiment
5182
7143
  };
5183
7144
  }
5184
7145
  }
@@ -5198,7 +7159,8 @@ var init_client = __esm(() => {
5198
7159
  id: existing?.id,
5199
7160
  version: existing?.version,
5200
7161
  reason: existing?.reason,
5201
- locallyEvaluated: existing?.locallyEvaluated ?? false
7162
+ locallyEvaluated: existing?.locallyEvaluated ?? false,
7163
+ hasExperiment: existing?.hasExperiment
5202
7164
  };
5203
7165
  }
5204
7166
  if (this._payloadOverrides !== undefined)
@@ -5210,6 +7172,11 @@ var init_client = __esm(() => {
5210
7172
  payload
5211
7173
  };
5212
7174
  }
7175
+ if (requestedFlagKeys !== undefined) {
7176
+ for (const key of Object.keys(records))
7177
+ if (!requestedFlagKeys.has(key))
7178
+ delete records[key];
7179
+ }
5213
7180
  return new FeatureFlagEvaluations({
5214
7181
  host: this._getFeatureFlagEvaluationsHost(),
5215
7182
  distinctId: resolvedDistinctId,
@@ -5223,6 +7190,9 @@ var init_client = __esm(() => {
5223
7190
  quotaLimited
5224
7191
  });
5225
7192
  }
7193
+ _shouldSendMinimalFlagCalledEvent(event, properties) {
7194
+ return event === "$feature_flag_called" && this._minimalFlagCalledEvents && properties.$feature_flag_has_experiment === false;
7195
+ }
5226
7196
  _captureFlagCalledEventIfNeeded(params) {
5227
7197
  const { distinctId, key, response, groups, disableGeoip, properties } = params;
5228
7198
  const groupSuffix = groups && Object.keys(groups).length > 0 ? `_${JSON.stringify(Object.entries(groups).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0))}` : "";
@@ -5257,9 +7227,32 @@ var init_client = __esm(() => {
5257
7227
  return this._featureFlagEvaluationsHost;
5258
7228
  }
5259
7229
  groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip }) {
5260
- super.groupIdentifyStateless(groupType, groupKey, properties, {
7230
+ this._sendPreparedEvent("capture", {
7231
+ distinctId: distinctId || `$${groupType}_${groupKey}`,
7232
+ event: "$groupidentify",
7233
+ properties: {
7234
+ $group_type: groupType,
7235
+ $group_key: groupKey,
7236
+ $group_set: properties || {}
7237
+ },
7238
+ disableGeoip
7239
+ }, false, {
7240
+ includeContextProperties: false
7241
+ });
7242
+ }
7243
+ async groupIdentifyImmediate({ groupType, groupKey, properties, distinctId, disableGeoip }) {
7244
+ await this._sendPreparedEvent("capture", {
7245
+ distinctId: distinctId || `$${groupType}_${groupKey}`,
7246
+ event: "$groupidentify",
7247
+ properties: {
7248
+ $group_type: groupType,
7249
+ $group_key: groupKey,
7250
+ $group_set: properties || {}
7251
+ },
5261
7252
  disableGeoip
5262
- }, distinctId);
7253
+ }, true, {
7254
+ includeContextProperties: false
7255
+ });
5263
7256
  }
5264
7257
  async reloadFeatureFlags() {
5265
7258
  await this.featureFlagsPoller?.loadFeatureFlags(true);
@@ -5331,12 +7324,18 @@ var init_client = __esm(() => {
5331
7324
  this.context?.enter(data, options);
5332
7325
  }
5333
7326
  async _shutdown(shutdownTimeoutMs) {
7327
+ const shutdownDeadlineMs = Date.now() + (shutdownTimeoutMs ?? 30000);
5334
7328
  const resolve9 = this._consumeWaitUntilCycle();
5335
7329
  await this.featureFlagsPoller?.stopPoller(shutdownTimeoutMs);
5336
7330
  this.errorTracking.shutdown();
7331
+ if (this._metrics) {
7332
+ await raceWithTimeout(this._metrics.flush().catch(() => {}), Math.max(0, shutdownDeadlineMs - Date.now()));
7333
+ this._metrics.reset();
7334
+ }
5337
7335
  try {
5338
- return await super._shutdown(shutdownTimeoutMs);
7336
+ return await super._shutdown(Math.max(0, shutdownDeadlineMs - Date.now()));
5339
7337
  } finally {
7338
+ this.distinctIdHasSentFlagCalls = {};
5340
7339
  resolve9?.();
5341
7340
  }
5342
7341
  }
@@ -5431,7 +7430,6 @@ var init_client = __esm(() => {
5431
7430
  }
5432
7431
  addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties) {
5433
7432
  const allPersonProperties = {
5434
- distinct_id: distinctId,
5435
7433
  ...personProperties || {}
5436
7434
  };
5437
7435
  const allGroupProperties = {};
@@ -5446,6 +7444,12 @@ var init_client = __esm(() => {
5446
7444
  allGroupProperties
5447
7445
  };
5448
7446
  }
7447
+ personPropertiesForLocalEvaluation(distinctId, personProperties) {
7448
+ return {
7449
+ distinct_id: distinctId,
7450
+ ...personProperties || {}
7451
+ };
7452
+ }
5449
7453
  createFeatureFlagEvaluationContext(distinctId, groups, personProperties, groupProperties) {
5450
7454
  return {
5451
7455
  distinctId,
@@ -5456,21 +7460,21 @@ var init_client = __esm(() => {
5456
7460
  };
5457
7461
  }
5458
7462
  captureException(error, distinctId, additionalProperties, uuid, flags) {
5459
- if (!ErrorTracking.isPreviouslyCapturedError(error)) {
7463
+ if (!error_tracking_ErrorTracking.isPreviouslyCapturedError(error)) {
5460
7464
  const syntheticException = new Error("PostHog syntheticException");
5461
- this.addPendingPromise(ErrorTracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
7465
+ this.addPendingPromise(error_tracking_ErrorTracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
5462
7466
  syntheticException
5463
- }, distinctId, additionalProperties).then((msg) => this.capture({
7467
+ }, distinctId, additionalProperties).then((msg) => this._capturePreparedEvent({
5464
7468
  ...msg,
5465
7469
  uuid,
5466
7470
  flags
5467
- })));
7471
+ }, false)));
5468
7472
  }
5469
7473
  }
5470
7474
  async captureExceptionImmediate(error, distinctId, additionalProperties, flags) {
5471
- if (!ErrorTracking.isPreviouslyCapturedError(error)) {
7475
+ if (!error_tracking_ErrorTracking.isPreviouslyCapturedError(error)) {
5472
7476
  const syntheticException = new Error("PostHog syntheticException");
5473
- return this.addPendingPromise(ErrorTracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
7477
+ return this.addPendingPromise(error_tracking_ErrorTracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
5474
7478
  syntheticException
5475
7479
  }, distinctId, additionalProperties).then((msg) => this.captureImmediate({
5476
7480
  ...msg,
@@ -5479,24 +7483,31 @@ var init_client = __esm(() => {
5479
7483
  }
5480
7484
  }
5481
7485
  async prepareEventMessage(props) {
7486
+ return this._prepareEventMessage(props);
7487
+ }
7488
+ async _prepareEventMessage(props, options = {}) {
5482
7489
  const { distinctId, event, properties, groups, flags, sendFeatureFlags, timestamp, disableGeoip, uuid } = props;
5483
7490
  const contextData = this.context?.get();
7491
+ const includeContextProperties = options.includeContextProperties ?? true;
5484
7492
  let mergedDistinctId = distinctId || contextData?.distinctId;
5485
- const mergedProperties = {
7493
+ const mergedProperties = includeContextProperties ? {
5486
7494
  ...this.props,
5487
7495
  ...contextData?.properties || {},
5488
7496
  ...properties || {}
7497
+ } : {
7498
+ ...properties || {}
5489
7499
  };
5490
7500
  if (!mergedDistinctId) {
5491
7501
  mergedDistinctId = uuidv7();
5492
7502
  mergedProperties.$process_person_profile = false;
5493
7503
  }
5494
- if (contextData?.sessionId && !mergedProperties.$session_id)
7504
+ if (includeContextProperties && contextData?.sessionId && !mergedProperties.$session_id)
5495
7505
  mergedProperties.$session_id = contextData.sessionId;
7506
+ const finalProperties = this._shouldSendMinimalFlagCalledEvent(event, mergedProperties) ? minimizeFlagCalledEventProperties(mergedProperties) : mergedProperties;
5496
7507
  const eventMessage = this._runBeforeSend({
5497
7508
  distinctId: mergedDistinctId,
5498
7509
  event,
5499
- properties: mergedProperties,
7510
+ properties: finalProperties,
5500
7511
  groups,
5501
7512
  flags,
5502
7513
  sendFeatureFlags,
@@ -5520,12 +7531,14 @@ var init_client = __esm(() => {
5520
7531
  }
5521
7532
  return {};
5522
7533
  }).catch(() => ({})).then((additionalProperties) => {
5523
- const props2 = {
7534
+ const resolvedGroups = eventMessage.groups || groups;
7535
+ return {
5524
7536
  ...additionalProperties,
5525
7537
  ...eventMessage.properties || {},
5526
- $groups: eventMessage.groups || groups
7538
+ ...resolvedGroups !== undefined && Object.keys(resolvedGroups).length > 0 ? {
7539
+ $groups: resolvedGroups
7540
+ } : {}
5527
7541
  };
5528
- return props2;
5529
7542
  });
5530
7543
  if (eventMessage.event === "$pageview" && this.options.__preview_capture_bot_pageviews && typeof eventProperties.$raw_user_agent == "string") {
5531
7544
  if (isBlockedUA(eventProperties.$raw_user_agent, this.options.custom_blocked_useragents || [])) {
@@ -5552,23 +7565,27 @@ var init_client = __esm(() => {
5552
7565
  beforeSend
5553
7566
  ];
5554
7567
  let result = eventMessage;
5555
- for (const fn of fns) {
5556
- result = fn(result);
5557
- if (!result) {
5558
- this._logger.info(`Event '${eventMessage.event}' was rejected in beforeSend function`);
7568
+ for (const fn of fns)
7569
+ try {
7570
+ result = fn(result);
7571
+ if (!result) {
7572
+ this._logger.info(`Event '${eventMessage.event}' was rejected in beforeSend function`);
7573
+ return null;
7574
+ }
7575
+ if (!result.properties || Object.keys(result.properties).length === 0) {
7576
+ const message = `Event '${result.event}' has no properties after beforeSend function, this is likely an error.`;
7577
+ this._logger.warn(message);
7578
+ }
7579
+ } catch (error) {
7580
+ this._logger.error(`Error in before_send function for event '${eventMessage.event}':`, error);
5559
7581
  return null;
5560
7582
  }
5561
- if (!result.properties || Object.keys(result.properties).length === 0) {
5562
- const message = `Event '${result.event}' has no properties after beforeSend function, this is likely an error.`;
5563
- this._logger.warn(message);
5564
- }
5565
- }
5566
7583
  return result;
5567
7584
  }
5568
7585
  };
5569
7586
  });
5570
7587
 
5571
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/context/context.mjs
7588
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/context/context.mjs
5572
7589
  import { AsyncLocalStorage } from "node:async_hooks";
5573
7590
 
5574
7591
  class PostHogContext {
@@ -5600,7 +7617,25 @@ class PostHogContext {
5600
7617
  }
5601
7618
  var init_context = () => {};
5602
7619
 
5603
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/sentry-integration.mjs
7620
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/gzip.node.mjs
7621
+ import { gzip } from "node:zlib";
7622
+ import { promisify } from "node:util";
7623
+ async function gzipCompress2(input, isDebug = true) {
7624
+ try {
7625
+ const compressed = await gzipAsync(input);
7626
+ return new Uint8Array(compressed);
7627
+ } catch (error) {
7628
+ if (isDebug)
7629
+ console.error("Failed to gzip compress data", error);
7630
+ return null;
7631
+ }
7632
+ }
7633
+ var gzipAsync;
7634
+ var init_gzip_node = __esm(() => {
7635
+ gzipAsync = promisify(gzip);
7636
+ });
7637
+
7638
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/sentry-integration.mjs
5604
7639
  function createEventProcessor(_posthog, { organization, projectId, prefix, severityAllowList = [
5605
7640
  "error"
5606
7641
  ], sendExceptionsToPostHog = true } = {}) {
@@ -5639,6 +7674,9 @@ function createEventProcessor(_posthog, { organization, projectId, prefix, sever
5639
7674
  $sentry_exception_type: exceptions[0]?.type,
5640
7675
  $sentry_tags: event.tags
5641
7676
  };
7677
+ const injectedReleaseId = exports_error_tracking.getInjectedReleaseId();
7678
+ if (injectedReleaseId)
7679
+ properties.$release_id = injectedReleaseId;
5642
7680
  if (organization && projectId)
5643
7681
  properties["$sentry_url"] = (prefix || "https://sentry.io/organizations/") + organization + "/issues/?project=" + projectId + "&query=" + event.event_id;
5644
7682
  if (sendExceptionsToPostHog)
@@ -5652,6 +7690,7 @@ function createEventProcessor(_posthog, { organization, projectId, prefix, sever
5652
7690
  }
5653
7691
  var NAME = "posthog-node", PostHogSentryIntegration;
5654
7692
  var init_sentry_integration = __esm(() => {
7693
+ init_dist();
5655
7694
  PostHogSentryIntegration = class PostHogSentryIntegration {
5656
7695
  static #_ = this.POSTHOG_ID_TAG = "posthog_distinct_id";
5657
7696
  constructor(_posthog, organization, prefix, severityAllowList, sendExceptionsToPostHog) {
@@ -5671,16 +7710,22 @@ var init_sentry_integration = __esm(() => {
5671
7710
  };
5672
7711
  });
5673
7712
 
5674
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/tracing-headers.mjs
7713
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/tracing-headers.mjs
5675
7714
  var init_tracing_headers2 = () => {};
5676
7715
 
5677
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/express.mjs
7716
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/url-utils.mjs
7717
+ var init_url_utils = __esm(() => {
7718
+ init_dist();
7719
+ });
7720
+
7721
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/express.mjs
5678
7722
  var init_express = __esm(() => {
5679
7723
  init_error_tracking2();
5680
7724
  init_tracing_headers2();
7725
+ init_url_utils();
5681
7726
  });
5682
7727
 
5683
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/exports.mjs
7728
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/exports.mjs
5684
7729
  var init_exports = __esm(() => {
5685
7730
  init_feature_flag_evaluations();
5686
7731
  init_dist();
@@ -5689,7 +7734,7 @@ var init_exports = __esm(() => {
5689
7734
  init_types3();
5690
7735
  });
5691
7736
 
5692
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/entrypoints/index.node.mjs
7737
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/entrypoints/index.node.mjs
5693
7738
  var PostHog;
5694
7739
  var init_index_node = __esm(() => {
5695
7740
  init_module_node();
@@ -5698,11 +7743,15 @@ var init_index_node = __esm(() => {
5698
7743
  init_client();
5699
7744
  init_dist();
5700
7745
  init_context();
7746
+ init_gzip_node();
5701
7747
  init_exports();
5702
7748
  PostHog = class PostHog extends PostHogBackendClient {
5703
7749
  getLibraryId() {
5704
7750
  return "posthog-node";
5705
7751
  }
7752
+ compressPayload(payload) {
7753
+ return gzipCompress2(payload, this.isDebug);
7754
+ }
5706
7755
  initializeContext() {
5707
7756
  return new PostHogContext;
5708
7757
  }
@@ -5715,13 +7764,24 @@ var init_index_node = __esm(() => {
5715
7764
  new exports_error_tracking.PrimitiveCoercer
5716
7765
  ], exports_error_tracking.createStackParser("node:javascript", exports_error_tracking.nodeStackLineParser), [
5717
7766
  createModulerModifier(),
5718
- addSourceContext,
7767
+ (frames) => addSourceContext(frames, undefined, this._logger),
5719
7768
  createRelativePathModifier()
5720
7769
  ]);
5721
7770
  }
5722
7771
  };
5723
7772
  });
5724
7773
 
7774
+ // packages/telemetry-core/src/machine-id.ts
7775
+ import { createHash as createHash3 } from "node:crypto";
7776
+ import os2 from "node:os";
7777
+ function getDefaultTelemetryOsProvider() {
7778
+ return os2;
7779
+ }
7780
+ function getTelemetryDistinctId(machineIdPrefix, osProvider = getDefaultTelemetryOsProvider()) {
7781
+ return createHash3("sha256").update(`${machineIdPrefix}${osProvider.hostname()}`).digest("hex");
7782
+ }
7783
+ var init_machine_id = () => {};
7784
+
5725
7785
  // packages/telemetry-core/src/posthog-client.ts
5726
7786
  class PostHogTelemetryTransport {
5727
7787
  #client;
@@ -5743,7 +7803,7 @@ function createDefaultPostHogTransport(apiKey, options) {
5743
7803
  }
5744
7804
  function isTelemetryClientEnabled(input) {
5745
7805
  const env = input.env ?? process.env;
5746
- return !shouldDisableTelemetry({ env, productEnvPrefix: input.product.productEnvPrefix }) && getTelemetryApiKey(env, input.product.defaultApiKey).length > 0;
7806
+ return !shouldDisableTelemetry({ env, productEnvPrefix: input.product.productEnvPrefix }) && hasTelemetryApiKey(env, input.product.defaultApiKey);
5747
7807
  }
5748
7808
  function createTelemetryClient(input) {
5749
7809
  if (!isTelemetryClientEnabled(input)) {
@@ -5809,7 +7869,8 @@ function createTransport(input) {
5809
7869
  flushAt: 1,
5810
7870
  flushInterval: 0,
5811
7871
  host: getTelemetryHost(env, input.product.defaultHost),
5812
- disableGeoip: false
7872
+ disableGeoip: input.product.disableGeoip ?? false,
7873
+ ...input.product.transportOptions
5813
7874
  });
5814
7875
  } catch (error) {
5815
7876
  input.diagnostics?.({
@@ -5886,6 +7947,17 @@ var init_posthog_client = __esm(() => {
5886
7947
  };
5887
7948
  });
5888
7949
 
7950
+ // packages/telemetry-core/src/events.ts
7951
+ var ALLOWED_DOLLAR_KEYS;
7952
+ var init_events = __esm(() => {
7953
+ ALLOWED_DOLLAR_KEYS = new Set([
7954
+ "$os",
7955
+ "$os_version",
7956
+ "$process_person_profile",
7957
+ "$session_id"
7958
+ ]);
7959
+ });
7960
+
5889
7961
  // packages/telemetry-core/src/record-daily-active.ts
5890
7962
  var init_record_daily_active = () => {};
5891
7963
 
@@ -5894,6 +7966,7 @@ var init_src = __esm(() => {
5894
7966
  init_activity_state();
5895
7967
  init_diagnostics();
5896
7968
  init_env();
7969
+ init_events();
5897
7970
  init_machine_id();
5898
7971
  init_posthog_client();
5899
7972
  init_record_daily_active();
@@ -5904,7 +7977,7 @@ var package_default;
5904
7977
  var init_package = __esm(() => {
5905
7978
  package_default = {
5906
7979
  name: "@oh-my-opencode/omo-codex",
5907
- version: "5.0.0-beta.3",
7980
+ version: "5.0.0-beta.30",
5908
7981
  type: "module",
5909
7982
  private: true,
5910
7983
  description: "Codex harness adapter for oh-my-openagent. Vendored Codex plugin namespace (omo) + TypeScript installer + telemetry.",
@@ -5938,7 +8011,7 @@ var init_package = __esm(() => {
5938
8011
  "@oh-my-opencode/utils": "workspace:*"
5939
8012
  },
5940
8013
  devDependencies: {
5941
- "bun-types": "1.3.14"
8014
+ "bun-types": "1.4.0"
5942
8015
  }
5943
8016
  };
5944
8017
  });
@@ -6109,14 +8182,14 @@ var init_posthog = __esm(() => {
6109
8182
  // packages/omo-codex/src/telemetry/index.ts
6110
8183
  var exports_telemetry = {};
6111
8184
  __export(exports_telemetry, {
6112
- getPostHogDistinctId: () => getPostHogDistinctId,
6113
- createPluginPostHog: () => createPluginPostHog,
6114
- createInstallPostHog: () => createInstallPostHog,
6115
- createCliPostHog: () => createCliPostHog,
6116
- __setOsProviderForTesting: () => __setOsProviderForTesting,
6117
- __setActivityStateProviderForTesting: () => __setActivityStateProviderForTesting,
8185
+ __resetActivityStateProviderForTesting: () => __resetActivityStateProviderForTesting,
6118
8186
  __resetOsProviderForTesting: () => __resetOsProviderForTesting,
6119
- __resetActivityStateProviderForTesting: () => __resetActivityStateProviderForTesting
8187
+ __setActivityStateProviderForTesting: () => __setActivityStateProviderForTesting,
8188
+ __setOsProviderForTesting: () => __setOsProviderForTesting,
8189
+ createCliPostHog: () => createCliPostHog,
8190
+ createInstallPostHog: () => createInstallPostHog,
8191
+ createPluginPostHog: () => createPluginPostHog,
8192
+ getPostHogDistinctId: () => getPostHogDistinctId
6120
8193
  });
6121
8194
  var init_telemetry = __esm(() => {
6122
8195
  init_posthog();
@@ -6124,7 +8197,7 @@ var init_telemetry = __esm(() => {
6124
8197
 
6125
8198
  // packages/omo-codex/src/install/install-local-cli.ts
6126
8199
  import { readFile as readFile23 } from "node:fs/promises";
6127
- import { dirname as dirname12, join as join40, resolve as resolve10 } from "node:path";
8200
+ import { dirname as dirname13, join as join40, resolve as resolve10 } from "node:path";
6128
8201
  import { fileURLToPath as fileURLToPath2 } from "node:url";
6129
8202
 
6130
8203
  // packages/utils/src/runtime/spawn.ts
@@ -6624,9 +8697,9 @@ var LEGACY_CODEX_COMPONENT_BINS = [
6624
8697
  { name: "codex-comment-checker", component: "comment-checker" },
6625
8698
  { name: "codex-lsp", component: "lsp" },
6626
8699
  { name: "codex-rules", component: "rules" },
6627
- { name: "codex-start-work-continuation", component: "start-work-continuation" },
6628
8700
  { name: "codex-telemetry", component: "telemetry" },
6629
- { name: "codex-ultrawork", component: "ultrawork" }
8701
+ { name: "codex-ultrawork", component: "ultrawork" },
8702
+ { name: "codex-ulw-execute-continuation", component: "ulw-execute-continuation" }
6630
8703
  ];
6631
8704
  var LEGACY_CODEX_COMPONENT_BIN_NAMES = LEGACY_CODEX_COMPONENT_BINS.map((entry) => entry.name);
6632
8705
  async function removeLegacyCodexComponentBins(binDir, platform) {
@@ -8971,14 +11044,14 @@ import { join as join17 } from "node:path";
8971
11044
  var FALLBACK_CODEX_MODEL_CATALOG = {
8972
11045
  current: {
8973
11046
  model: "gpt-5.6-sol",
8974
- modelContextWindow: 372000,
11047
+ modelContextWindow: 650000,
8975
11048
  modelReasoningEffort: "high",
8976
11049
  planModeReasoningEffort: "xhigh"
8977
11050
  },
8978
11051
  managedProfiles: [
8979
11052
  {
8980
11053
  model: "gpt-5.5",
8981
- modelContextWindow: 400000,
11054
+ modelContextWindow: 650000,
8982
11055
  modelReasoningEffort: "high",
8983
11056
  planModeReasoningEffort: "xhigh"
8984
11057
  },
@@ -10796,6 +12869,7 @@ function runtimeSlug(platform = process.platform, arch = process.arch) {
10796
12869
 
10797
12870
  // packages/utils/src/ast-grep/install-script.ts
10798
12871
  var AST_GREP_BIN_DIR_ENV_KEY = "OMO_AST_GREP_BIN_DIR";
12872
+ var KILL_GRACE_MS = 1000;
10799
12873
  var AST_GREP_INSTALL_TIMEOUT_MS = 30000;
10800
12874
  function astGrepRuntimeDir(baseDir, platform = process.platform, arch = process.arch) {
10801
12875
  return join32(baseDir, "runtime", "ast-grep", runtimeSlug(platform, arch));
@@ -10847,16 +12921,30 @@ function invocationsForPlatform(scriptPath, platform) {
10847
12921
  async function runInvocation(input) {
10848
12922
  const child = input.spawnProcess(input.invocation.command, input.invocation.args, { cwd: input.skillDir, env: input.env });
10849
12923
  let timedOut = false;
12924
+ let terminateDeadline;
12925
+ let terminateDeadlineGrace;
12926
+ const killIgnored = new Promise((_, reject) => {
12927
+ terminateDeadline = () => reject(new Error("ast-grep install child ignored termination"));
12928
+ });
10850
12929
  const timeout = setTimeout(() => {
10851
12930
  timedOut = true;
10852
12931
  child.kill();
12932
+ terminateDeadlineGrace = setTimeout(() => terminateDeadline?.(), KILL_GRACE_MS);
10853
12933
  }, input.timeoutMs);
10854
- timeout.unref?.();
10855
12934
  try {
10856
- const outcome = await child.outcome;
10857
- return timedOut ? { kind: "timed-out" } : outcome;
12935
+ const outcome = await Promise.race([child.outcome, killIgnored]);
12936
+ if (timedOut)
12937
+ return { kind: "timed-out" };
12938
+ return outcome;
12939
+ } catch (error) {
12940
+ if (error instanceof Error && error.message.includes("ignored termination")) {
12941
+ return { kind: "spawn-error", error, missingExecutable: false };
12942
+ }
12943
+ throw error;
10858
12944
  } finally {
10859
12945
  clearTimeout(timeout);
12946
+ if (terminateDeadlineGrace !== undefined)
12947
+ clearTimeout(terminateDeadlineGrace);
10860
12948
  }
10861
12949
  }
10862
12950
  function failedReason(outcome) {
@@ -11467,7 +13555,7 @@ function shellQuote(value) {
11467
13555
  // packages/omo-codex/src/install/lazycodex-manual-update.ts
11468
13556
  import { spawn as spawn3, spawnSync as spawnSync3 } from "node:child_process";
11469
13557
  import { readFileSync as readFileSync4 } from "node:fs";
11470
- import { dirname as dirname11, join as join38 } from "node:path";
13558
+ import { dirname as dirname12, join as join38 } from "node:path";
11471
13559
  import { createInterface as createInterface2 } from "node:readline/promises";
11472
13560
  import { fileURLToPath } from "node:url";
11473
13561
 
@@ -11576,7 +13664,7 @@ function resolveArgs(env2) {
11576
13664
  function resolveCurrentVersion(env2) {
11577
13665
  if (env2.LAZYCODEX_CURRENT_VERSION?.trim())
11578
13666
  return env2.LAZYCODEX_CURRENT_VERSION.trim();
11579
- const pluginRoot = dirname11(dirname11(fileURLToPath(import.meta.url)));
13667
+ const pluginRoot = dirname12(dirname12(fileURLToPath(import.meta.url)));
11580
13668
  return readVersionManifest(resolveInstalledVersionPath(env2, pluginRoot)) ?? readVersionManifest(join38(pluginRoot, "..", "..", "..", "package.json")) ?? readVersionManifest(join38(pluginRoot, ".codex-plugin", "plugin.json"));
11581
13669
  }
11582
13670
  function resolveLatestVersion(env2) {
@@ -11756,7 +13844,7 @@ async function installMarketplaceLocally(options = {}) {
11756
13844
  return runCodexInstaller(options);
11757
13845
  }
11758
13846
  function resolveDefaultRepoRootForEntrypoint(entrypointPath) {
11759
- return resolve10(dirname12(entrypointPath), "..", "..", "..");
13847
+ return resolve10(dirname13(entrypointPath), "..", "..", "..");
11760
13848
  }
11761
13849
  function resolveDefaultRepoRoot() {
11762
13850
  return resolveDefaultRepoRootForEntrypoint(fileURLToPath2(import.meta.url));
@@ -11809,23 +13897,23 @@ async function runLazyCodexInstallLocalCli(input) {
11809
13897
  return 0;
11810
13898
  }
11811
13899
  export {
11812
- updateCodexConfig,
11813
- stampGitBashMcpEnv,
11814
- runLazyCodexInstallLocalCli,
11815
- runDelegatedOmoCommand,
11816
- resolveDefaultRepoRootForEntrypoint,
11817
- resolveDefaultRepoRoot,
11818
- resolveCodexInstallerBinDir,
11819
- repairNearestProjectLocalCodexArtifacts,
11820
- readCodexModelCatalog,
11821
- parseLazyCodexInstallCliArgs,
11822
- linkRootRuntimeBin,
11823
- linkCachedPluginBins,
11824
- installMarketplaceLocally,
11825
- installCachedPlugin,
11826
- formatLazyCodexInstallHelp,
11827
- findMissingHookCommandTargets,
11828
- buildDelegatedOmoInvocation,
13900
+ PASSTHROUGH_COMMANDS,
11829
13901
  assertHookCommandTargets,
11830
- PASSTHROUGH_COMMANDS
13902
+ buildDelegatedOmoInvocation,
13903
+ findMissingHookCommandTargets,
13904
+ formatLazyCodexInstallHelp,
13905
+ installCachedPlugin,
13906
+ installMarketplaceLocally,
13907
+ linkCachedPluginBins,
13908
+ linkRootRuntimeBin,
13909
+ parseLazyCodexInstallCliArgs,
13910
+ readCodexModelCatalog,
13911
+ repairNearestProjectLocalCodexArtifacts,
13912
+ resolveCodexInstallerBinDir,
13913
+ resolveDefaultRepoRoot,
13914
+ resolveDefaultRepoRootForEntrypoint,
13915
+ runDelegatedOmoCommand,
13916
+ runLazyCodexInstallLocalCli,
13917
+ stampGitBashMcpEnv,
13918
+ updateCodexConfig
11831
13919
  };