@shware/analytics 16.2.1 → 16.2.3

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 (58) hide show
  1. package/README.md +1 -1
  2. package/dist/react/posthog-error-boundary.cjs.map +1 -1
  3. package/dist/react/posthog-error-boundary.d.cts +1 -1
  4. package/dist/react/posthog-error-boundary.d.mts +1 -1
  5. package/dist/react/posthog-error-boundary.mjs.map +1 -1
  6. package/dist/react/posthog.cjs.map +1 -1
  7. package/dist/react/posthog.d.cts +1 -1
  8. package/dist/react/posthog.d.cts.map +1 -1
  9. package/dist/react/posthog.d.mts +1 -1
  10. package/dist/react/posthog.d.mts.map +1 -1
  11. package/dist/react/posthog.mjs.map +1 -1
  12. package/dist/schema/index.cjs +9 -7
  13. package/dist/schema/index.cjs.map +1 -1
  14. package/dist/schema/index.d.cts.map +1 -1
  15. package/dist/schema/index.d.mts.map +1 -1
  16. package/dist/schema/index.mjs +9 -7
  17. package/dist/schema/index.mjs.map +1 -1
  18. package/dist/server/event-time.cjs +14 -0
  19. package/dist/server/event-time.cjs.map +1 -0
  20. package/dist/server/event-time.d.cts +8 -0
  21. package/dist/server/event-time.d.cts.map +1 -0
  22. package/dist/server/event-time.d.mts +8 -0
  23. package/dist/server/event-time.d.mts.map +1 -0
  24. package/dist/server/event-time.mjs +13 -0
  25. package/dist/server/event-time.mjs.map +1 -0
  26. package/dist/server/meta-capi.cjs +4 -3
  27. package/dist/server/meta-capi.cjs.map +1 -1
  28. package/dist/server/meta-capi.d.cts.map +1 -1
  29. package/dist/server/meta-capi.d.mts.map +1 -1
  30. package/dist/server/meta-capi.mjs +4 -3
  31. package/dist/server/meta-capi.mjs.map +1 -1
  32. package/dist/server/microsoft-conversions-api.cjs +2 -1
  33. package/dist/server/microsoft-conversions-api.cjs.map +1 -1
  34. package/dist/server/microsoft-conversions-api.d.cts.map +1 -1
  35. package/dist/server/microsoft-conversions-api.d.mts.map +1 -1
  36. package/dist/server/microsoft-conversions-api.mjs +2 -1
  37. package/dist/server/microsoft-conversions-api.mjs.map +1 -1
  38. package/dist/server/reddit-conversions-api.cjs +2 -1
  39. package/dist/server/reddit-conversions-api.cjs.map +1 -1
  40. package/dist/server/reddit-conversions-api.d.cts.map +1 -1
  41. package/dist/server/reddit-conversions-api.d.mts.map +1 -1
  42. package/dist/server/reddit-conversions-api.mjs +2 -1
  43. package/dist/server/reddit-conversions-api.mjs.map +1 -1
  44. package/dist/third-parties/posthog.cjs +2 -2
  45. package/dist/third-parties/posthog.cjs.map +1 -1
  46. package/dist/third-parties/posthog.d.cts +3 -3
  47. package/dist/third-parties/posthog.d.mts +3 -3
  48. package/dist/third-parties/posthog.mjs +2 -2
  49. package/dist/third-parties/posthog.mjs.map +1 -1
  50. package/dist/visitor/id.cjs +5 -2
  51. package/dist/visitor/id.cjs.map +1 -1
  52. package/dist/visitor/id.d.cts +4 -1
  53. package/dist/visitor/id.d.cts.map +1 -1
  54. package/dist/visitor/id.d.mts +4 -1
  55. package/dist/visitor/id.d.mts.map +1 -1
  56. package/dist/visitor/id.mjs +6 -3
  57. package/dist/visitor/id.mjs.map +1 -1
  58. package/package.json +2 -5
package/README.md CHANGED
@@ -130,7 +130,7 @@ With server-evaluated flags, skip the wait: pass them in `config.bootstrap` and
130
130
 
131
131
  For error tracking, `<PosthogErrorBoundary fallback={…}>` (with `posthog-js/react`'s props) sends a render error to PostHog with its component stack, tied to the session's replay, and renders `fallback` instead; an error before the library loads is queued on the stub. Errors outside render (event handlers, unhandled rejections) are the library's own exception autocapture: `capture_exceptions: true` in `config`. What no boundary of yours sees — an uncaught error, one a framework's boundary caught (TanStack Router's `errorComponent`), a hydration mismatch React recovered from — `setupReactErrorHandler()` reports from React 19's root options, in the client entry: `hydrateRoot(document, <StartClient />, { onUncaughtError: setupReactErrorHandler(), onCaughtError: setupReactErrorHandler(), onRecoverableError: setupReactErrorHandler() })`.
132
132
 
133
- Under `posthogFlagsReady()` with `config.bootstrap` the wait ends as soon as the library loads. On Next.js its snippet uses `next/script`'s `beforeInteractive`, so the stub exists before hydration tracks anything; render `<Analytics>` in the root layout for that. `<Analytics>` also preconnects to PostHog's assets host (`Integration.preconnect`, through `react-dom`'s `preconnect`), so `array.js` starts sooner. The `PostHog` and `PostHogConfig` types come from `posthog-js`: install it as a dev dependency for them. In an app, `firebaseAnalytics()` (every event) and `metaAppEvents({ customEvents })` (the conversions Meta maps, like `metaAds`) are the `integrations`. A platform the SDK does not cover is an object implementing `Integration` (`type`, `track`, and optionally `setUser` and `script`).
133
+ Under `posthogFlagsReady()` with `config.bootstrap` the wait ends as soon as the library loads. On Next.js its snippet uses `next/script`'s `beforeInteractive`, so the stub exists before hydration tracks anything; render `<Analytics>` in the root layout for that. `<Analytics>` also preconnects to PostHog's assets host (`Integration.preconnect`, through `react-dom`'s `preconnect`), so `array.js` starts sooner. The `PostHog` and `PostHogConfig` types come from `@posthog/types`, PostHog's types-only package for the snippet, a dependency of this one: the host does not install `posthog-js` for them. In an app, `firebaseAnalytics()` (every event) and `metaAppEvents({ customEvents })` (the conversions Meta maps, like `metaAds`) are the `integrations`. A platform the SDK does not cover is an object implementing `Integration` (`type`, `track`, and optionally `setUser` and `script`).
134
134
 
135
135
  `getHeaders` is also accepted, for a backend that wants extra headers on the analytics requests.
136
136
 
@@ -1 +1 @@
1
- {"version":3,"file":"posthog-error-boundary.cjs","names":["Component","getPosthog","isValidElement"],"sources":["../../src/react/posthog-error-boundary.tsx"],"sourcesContent":["import type { CaptureResult, Properties } from 'posthog-js';\nimport {\n Component,\n type ErrorInfo,\n type FunctionComponent,\n type ReactNode,\n isValidElement,\n} from 'react';\nimport { getPosthog } from '../third-parties/posthog';\n\nexport interface PosthogErrorBoundaryFallbackProps {\n error: unknown;\n /** The `$exception` event sent; `undefined` while only the stub is there, which queues it. */\n exceptionEvent: CaptureResult | undefined;\n componentStack: string;\n resetError: () => void;\n}\n\nexport interface PosthogErrorBoundaryProps {\n children?: ReactNode | (() => ReactNode);\n fallback?: ReactNode | FunctionComponent<PosthogErrorBoundaryFallbackProps>;\n additionalProperties?: Properties | ((error: unknown, errorInfo: ErrorInfo) => Properties);\n}\n\ninterface State {\n error: unknown;\n componentStack: string | null;\n exceptionEvent: CaptureResult | undefined;\n}\n\nconst INITIAL_STATE: State = { error: null, componentStack: null, exceptionEvent: undefined };\n\n/**\n * The error as PostHog's own boundary reports it: the React component stack added as a cause, so\n * the issue shows which components it was thrown in.\n */\nfunction withComponentStack(error: unknown, componentStack: string | null | undefined): unknown {\n if (!componentStack) return error;\n const isError = error instanceof Error;\n const stackError = new Error(\n isError ? error.message : `Primitive value captured as exception: ${String(error)}`\n );\n stackError.name = `React ErrorBoundary ${isError ? error.name : 'Error'}`;\n stackError.stack = componentStack;\n if (!isError) return stackError;\n // At the end of the error's cause chain, keeping a last cause that is not an error under it.\n const seen = new WeakSet<Error>();\n let current = error;\n while (!seen.has(current)) {\n seen.add(current);\n if (!(current.cause instanceof Error)) {\n if (current.cause !== undefined) stackError.cause = current.cause;\n current.cause = stackError;\n break;\n }\n current = current.cause;\n }\n return error;\n}\n\n/**\n * `posthog-js/react`'s `PostHogErrorBoundary`, with its props, for the snippet-loaded library: a\n * render error in `children` is sent to PostHog's error tracking (`captureException`, as an\n * `$exception` event tied to the session's replay) and `fallback` renders instead — a\n * component gets the error and `resetError`. An error thrown before the library has loaded is\n * queued on the stub and sent once it has.\n *\n * The boundary itself never throws: a failure to report (no PostHog, an ad blocker that stopped the\n * library, a throwing `additionalProperties`) is logged and the fallback still renders. It\n * catches render errors only, as any error boundary; errors outside React's render (event\n * handlers, unhandled rejections) are the library's exception autocapture's, enabled in the\n * snippet's `config` (`capture_exceptions`).\n */\nexport class PosthogErrorBoundary extends Component<PosthogErrorBoundaryProps, State> {\n override state = INITIAL_STATE;\n\n override componentDidCatch(error: unknown, errorInfo: ErrorInfo) {\n const componentStack = errorInfo.componentStack ?? '';\n let exceptionEvent: CaptureResult | undefined;\n // Reporting must never fail the boundary: an error thrown here would go to the boundary\n // above it, if any — `additionalProperties` throwing, or an error that cannot take a cause.\n try {\n const { additionalProperties } = this.props;\n const properties =\n typeof additionalProperties === 'function'\n ? additionalProperties(error, errorInfo)\n : additionalProperties;\n exceptionEvent = getPosthog()?.captureException(\n withComponentStack(error, componentStack),\n properties\n );\n } catch (e: unknown) {\n console.error('PosthogErrorBoundary: the error was not reported', e);\n }\n this.setState({ error, componentStack, exceptionEvent });\n }\n\n resetError = () => {\n this.setState(INITIAL_STATE);\n };\n\n override render() {\n const { children, fallback } = this.props;\n const { error, componentStack, exceptionEvent } = this.state;\n if (componentStack === null) return typeof children === 'function' ? children() : children;\n\n const element =\n typeof fallback === 'function'\n ? fallback({ error, componentStack, exceptionEvent, resetError: this.resetError })\n : fallback;\n if (isValidElement(element)) return element;\n console.warn('PosthogErrorBoundary: fallback is not a React element; rendering nothing');\n return null;\n }\n}\n\n/**\n * `posthog-js/react`'s `setupReactErrorHandler`, for the snippet-loaded library, so without its\n * `client`: a handler for React 19's root options, which report what no `PosthogErrorBoundary`\n * sees — `onUncaughtError` (no boundary caught it), `onCaughtError` (a framework's boundary did,\n * e.g. TanStack Router's `errorComponent`) and `onRecoverableError` (a hydration mismatch React\n * recovered from). The error goes to PostHog with its component stack; `callback` gets the event\n * (`undefined` while only the stub is there), as React's own logging does not run once a handler\n * is set.\n *\n * ```tsx\n * hydrateRoot(document, <StartClient />, {\n * onUncaughtError: setupReactErrorHandler(),\n * onCaughtError: setupReactErrorHandler(),\n * onRecoverableError: setupReactErrorHandler(),\n * });\n * ```\n *\n * Never throws, as `PosthogErrorBoundary`: a failure to report is logged.\n */\nexport function setupReactErrorHandler(\n callback?: (event: CaptureResult | undefined, error: unknown, errorInfo: ErrorInfo) => void\n): (error: unknown, errorInfo: ErrorInfo) => void {\n return (error, errorInfo) => {\n let event: CaptureResult | undefined;\n try {\n event = getPosthog()?.captureException(withComponentStack(error, errorInfo.componentStack));\n } catch (e: unknown) {\n console.error('setupReactErrorHandler: the error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U,aAAa,KAAK;EACpC,MAAM,EAAE,OAAO,gBAAgB,mBAAmB,KAAK;EACvD,IAAI,mBAAmB,MAAM,OAAO,OAAO,aAAa,aAAa,SAAS,IAAI;EAElF,MAAM,UACJ,OAAO,aAAa,aAChB,SAAS;GAAE;GAAO;GAAgB;GAAgB,YAAY,KAAK;EAAW,CAAC,IAC/E;EACN,KAAA,GAAIC,MAAAA,eAAAA,CAAe,OAAO,GAAG,OAAO;EACpC,QAAQ,KAAK,0EAA0E;EACvF,OAAO;CACT;AACF;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,uBACd,UACgD;CAChD,QAAQ,OAAO,cAAc;EAC3B,IAAI;EACJ,IAAI;GACF,QAAQD,8BAAAA,WAAW,CAAC,EAAE,iBAAiB,mBAAmB,OAAO,UAAU,cAAc,CAAC;EAC5F,SAAS,GAAY;GACnB,QAAQ,MAAM,sDAAsD,CAAC;EACvE;EACA,WAAW,OAAO,OAAO,SAAS;CACpC;AACF"}
1
+ {"version":3,"file":"posthog-error-boundary.cjs","names":["Component","getPosthog","isValidElement"],"sources":["../../src/react/posthog-error-boundary.tsx"],"sourcesContent":["import type { CaptureResult, Properties } from '@posthog/types';\nimport {\n Component,\n type ErrorInfo,\n type FunctionComponent,\n type ReactNode,\n isValidElement,\n} from 'react';\nimport { getPosthog } from '../third-parties/posthog';\n\nexport interface PosthogErrorBoundaryFallbackProps {\n error: unknown;\n /** The `$exception` event sent; `undefined` while only the stub is there, which queues it. */\n exceptionEvent: CaptureResult | undefined;\n componentStack: string;\n resetError: () => void;\n}\n\nexport interface PosthogErrorBoundaryProps {\n children?: ReactNode | (() => ReactNode);\n fallback?: ReactNode | FunctionComponent<PosthogErrorBoundaryFallbackProps>;\n additionalProperties?: Properties | ((error: unknown, errorInfo: ErrorInfo) => Properties);\n}\n\ninterface State {\n error: unknown;\n componentStack: string | null;\n exceptionEvent: CaptureResult | undefined;\n}\n\nconst INITIAL_STATE: State = { error: null, componentStack: null, exceptionEvent: undefined };\n\n/**\n * The error as PostHog's own boundary reports it: the React component stack added as a cause, so\n * the issue shows which components it was thrown in.\n */\nfunction withComponentStack(error: unknown, componentStack: string | null | undefined): unknown {\n if (!componentStack) return error;\n const isError = error instanceof Error;\n const stackError = new Error(\n isError ? error.message : `Primitive value captured as exception: ${String(error)}`\n );\n stackError.name = `React ErrorBoundary ${isError ? error.name : 'Error'}`;\n stackError.stack = componentStack;\n if (!isError) return stackError;\n // At the end of the error's cause chain, keeping a last cause that is not an error under it.\n const seen = new WeakSet<Error>();\n let current = error;\n while (!seen.has(current)) {\n seen.add(current);\n if (!(current.cause instanceof Error)) {\n if (current.cause !== undefined) stackError.cause = current.cause;\n current.cause = stackError;\n break;\n }\n current = current.cause;\n }\n return error;\n}\n\n/**\n * `posthog-js/react`'s `PostHogErrorBoundary`, with its props, for the snippet-loaded library: a\n * render error in `children` is sent to PostHog's error tracking (`captureException`, as an\n * `$exception` event tied to the session's replay) and `fallback` renders instead — a\n * component gets the error and `resetError`. An error thrown before the library has loaded is\n * queued on the stub and sent once it has.\n *\n * The boundary itself never throws: a failure to report (no PostHog, an ad blocker that stopped the\n * library, a throwing `additionalProperties`) is logged and the fallback still renders. It\n * catches render errors only, as any error boundary; errors outside React's render (event\n * handlers, unhandled rejections) are the library's exception autocapture's, enabled in the\n * snippet's `config` (`capture_exceptions`).\n */\nexport class PosthogErrorBoundary extends Component<PosthogErrorBoundaryProps, State> {\n override state = INITIAL_STATE;\n\n override componentDidCatch(error: unknown, errorInfo: ErrorInfo) {\n const componentStack = errorInfo.componentStack ?? '';\n let exceptionEvent: CaptureResult | undefined;\n // Reporting must never fail the boundary: an error thrown here would go to the boundary\n // above it, if any — `additionalProperties` throwing, or an error that cannot take a cause.\n try {\n const { additionalProperties } = this.props;\n const properties =\n typeof additionalProperties === 'function'\n ? additionalProperties(error, errorInfo)\n : additionalProperties;\n exceptionEvent = getPosthog()?.captureException(\n withComponentStack(error, componentStack),\n properties\n );\n } catch (e: unknown) {\n console.error('PosthogErrorBoundary: the error was not reported', e);\n }\n this.setState({ error, componentStack, exceptionEvent });\n }\n\n resetError = () => {\n this.setState(INITIAL_STATE);\n };\n\n override render() {\n const { children, fallback } = this.props;\n const { error, componentStack, exceptionEvent } = this.state;\n if (componentStack === null) return typeof children === 'function' ? children() : children;\n\n const element =\n typeof fallback === 'function'\n ? fallback({ error, componentStack, exceptionEvent, resetError: this.resetError })\n : fallback;\n if (isValidElement(element)) return element;\n console.warn('PosthogErrorBoundary: fallback is not a React element; rendering nothing');\n return null;\n }\n}\n\n/**\n * `posthog-js/react`'s `setupReactErrorHandler`, for the snippet-loaded library, so without its\n * `client`: a handler for React 19's root options, which report what no `PosthogErrorBoundary`\n * sees — `onUncaughtError` (no boundary caught it), `onCaughtError` (a framework's boundary did,\n * e.g. TanStack Router's `errorComponent`) and `onRecoverableError` (a hydration mismatch React\n * recovered from). The error goes to PostHog with its component stack; `callback` gets the event\n * (`undefined` while only the stub is there), as React's own logging does not run once a handler\n * is set.\n *\n * ```tsx\n * hydrateRoot(document, <StartClient />, {\n * onUncaughtError: setupReactErrorHandler(),\n * onCaughtError: setupReactErrorHandler(),\n * onRecoverableError: setupReactErrorHandler(),\n * });\n * ```\n *\n * Never throws, as `PosthogErrorBoundary`: a failure to report is logged.\n */\nexport function setupReactErrorHandler(\n callback?: (event: CaptureResult | undefined, error: unknown, errorInfo: ErrorInfo) => void\n): (error: unknown, errorInfo: ErrorInfo) => void {\n return (error, errorInfo) => {\n let event: CaptureResult | undefined;\n try {\n event = getPosthog()?.captureException(withComponentStack(error, errorInfo.componentStack));\n } catch (e: unknown) {\n console.error('setupReactErrorHandler: the error was not reported', e);\n }\n callback?.(event, error, errorInfo);\n };\n}\n"],"mappings":";;;;AA8BA,MAAM,gBAAuB;CAAE,OAAO;CAAM,gBAAgB;CAAM,gBAAgB,KAAA;AAAU;;;;;AAM5F,SAAS,mBAAmB,OAAgB,gBAAoD;CAC9F,IAAI,CAAC,gBAAgB,OAAO;CAC5B,M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C,IAC/E;EACN,KAAA,GAAIC,MAAAA,eAAAA,CAAe,OAAO,GAAG,OAAO;EACpC,QAAQ,KAAK,0EAA0E;EACvF,OAAO;CACT;AACF;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,uBACd,UACgD;CAChD,QAAQ,OAAO,cAAc;EAC3B,IAAI;EACJ,IAAI;GACF,QAAQD,8BAAAA,WAAW,CAAC,EAAE,iBAAiB,mBAAmB,OAAO,UAAU,cAAc,CAAC;EAC5F,SAAS,GAAY;GACnB,QAAQ,MAAM,sDAAsD,CAAC;EACvE;EACA,WAAW,OAAO,OAAO,SAAS;CACpC;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { Component, ErrorInfo, FunctionComponent, ReactNode } from "react";
2
- import { CaptureResult, Properties } from "posthog-js";
2
+ import { CaptureResult, Properties } from "@posthog/types";
3
3
  export interface PosthogErrorBoundaryFallbackProps {
4
4
  error: unknown;
5
5
  /** The `$exception` event sent; `undefined` while only the stub is there, which queues it. */
@@ -1,5 +1,5 @@
1
1
  import { Component, ErrorInfo, FunctionComponent, ReactNode } from "react";
2
- import { CaptureResult, Properties } from "posthog-js";
2
+ import { CaptureResult, Properties } from "@posthog/types";
3
3
  export interface PosthogErrorBoundaryFallbackProps {
4
4
  error: unknown;
5
5
  /** The `$exception` event sent; `undefined` while only the stub is there, which queues it. */
@@ -1 +1 @@
1
- {"version":3,"file":"posthog-error-boundary.mjs","names":[],"sources":["../../src/react/posthog-error-boundary.tsx"],"sourcesContent":["import type { CaptureResult, Properties } from 'posthog-js';\nimport {\n Component,\n type ErrorInfo,\n type FunctionComponent,\n type ReactNode,\n isValidElement,\n} from 'react';\nimport { getPosthog } from '../third-parties/posthog';\n\nexport interface PosthogErrorBoundaryFallbackProps {\n error: unknown;\n /** The `$exception` event sent; `undefined` while only the stub is there, which queues it. */\n exceptionEvent: CaptureResult | undefined;\n componentStack: string;\n resetError: () => void;\n}\n\nexport interface PosthogErrorBoundaryProps {\n children?: ReactNode | (() => ReactNode);\n fallback?: ReactNode | FunctionComponent<PosthogErrorBoundaryFallbackProps>;\n additionalProperties?: Properties | ((error: unknown, errorInfo: ErrorInfo) => Properties);\n}\n\ninterface State {\n error: unknown;\n componentStack: string | null;\n exceptionEvent: CaptureResult | undefined;\n}\n\nconst INITIAL_STATE: State = { error: null, componentStack: null, exceptionEvent: undefined };\n\n/**\n * The error as PostHog's own boundary reports it: the React component stack added as a cause, so\n * the issue shows which components it was thrown in.\n */\nfunction withComponentStack(error: unknown, componentStack: string | null | undefined): unknown {\n if (!componentStack) return error;\n const isError = error instanceof Error;\n const stackError = new Error(\n isError ? error.message : `Primitive value captured as exception: ${String(error)}`\n );\n stackError.name = `React ErrorBoundary ${isError ? error.name : 'Error'}`;\n stackError.stack = componentStack;\n if (!isError) return stackError;\n // At the end of the error's cause chain, keeping a last cause that is not an error under it.\n const seen = new WeakSet<Error>();\n let current = error;\n while (!seen.has(current)) {\n seen.add(current);\n if (!(current.cause instanceof Error)) {\n if (current.cause !== undefined) stackError.cause = current.cause;\n current.cause = stackError;\n break;\n }\n current = current.cause;\n }\n return error;\n}\n\n/**\n * `posthog-js/react`'s `PostHogErrorBoundary`, with its props, for the snippet-loaded library: a\n * render error in `children` is sent to PostHog's error tracking (`captureException`, as an\n * `$exception` event tied to the session's replay) and `fallback` renders instead — a\n * component gets the error and `resetError`. An error thrown before the library has loaded is\n * queued on the stub and sent once it has.\n *\n * The boundary itself never throws: a failure to report (no PostHog, an ad blocker that stopped the\n * library, a throwing `additionalProperties`) is logged and the fallback still renders. It\n * catches render errors only, as any error boundary; errors outside React's render (event\n * handlers, unhandled rejections) are the library's exception autocapture's, enabled in the\n * snippet's `config` (`capture_exceptions`).\n */\nexport class PosthogErrorBoundary extends Component<PosthogErrorBoundaryProps, State> {\n override state = INITIAL_STATE;\n\n override componentDidCatch(error: unknown, errorInfo: ErrorInfo) {\n const componentStack = errorInfo.componentStack ?? '';\n let exceptionEvent: CaptureResult | undefined;\n // Reporting must never fail the boundary: an error thrown here would go to the boundary\n // above it, if any — `additionalProperties` throwing, or an error that cannot take a cause.\n try {\n const { additionalProperties } = this.props;\n const properties =\n typeof additionalProperties === 'function'\n ? additionalProperties(error, errorInfo)\n : additionalProperties;\n exceptionEvent = getPosthog()?.captureException(\n withComponentStack(error, componentStack),\n properties\n );\n } catch (e: unknown) {\n console.error('PosthogErrorBoundary: the error was not reported', e);\n }\n this.setState({ error, componentStack, exceptionEvent });\n }\n\n resetError = () => {\n this.setState(INITIAL_STATE);\n };\n\n override render() {\n const { children, fallback } = this.props;\n const { error, componentStack, exceptionEvent } = this.state;\n if (componentStack === null) return typeof children === 'function' ? children() : children;\n\n const element =\n typeof fallback === 'function'\n ? fallback({ error, componentStack, exceptionEvent, resetError: this.resetError })\n : fallback;\n if (isValidElement(element)) return element;\n console.warn('PosthogErrorBoundary: fallback is not a React element; rendering nothing');\n return null;\n }\n}\n\n/**\n * `posthog-js/react`'s `setupReactErrorHandler`, for the snippet-loaded library, so without its\n * `client`: a handler for React 19's root options, which report what no `PosthogErrorBoundary`\n * sees — `onUncaughtError` (no boundary caught it), `onCaughtError` (a framework's boundary did,\n * e.g. TanStack Router's `errorComponent`) and `onRecoverableError` (a hydration mismatch React\n * recovered from). The error goes to PostHog with its component stack; `callback` gets the event\n * (`undefined` while only the stub is there), as React's own logging does not run once a handler\n * is set.\n *\n * ```tsx\n * hydrateRoot(document, <StartClient />, {\n * onUncaughtError: setupReactErrorHandler(),\n * onCaughtError: setupReactErrorHandler(),\n * onRecoverableError: setupReactErrorHandler(),\n * });\n * ```\n *\n * Never throws, as `PosthogErrorBoundary`: a failure to report is logged.\n */\nexport function setupReactErrorHandler(\n callback?: (event: CaptureResult | undefined, error: unknown, errorInfo: ErrorInfo) => void\n): (error: unknown, errorInfo: ErrorInfo) => void {\n return (error, errorInfo) => {\n let event: CaptureResult | undefined;\n try {\n event = getPosthog()?.captureException(withComponentStack(error, errorInfo.componentStack));\n } catch (e: unknown) {\n console.error('setupReactErrorHand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EACpC,MAAM,EAAE,OAAO,gBAAgB,mBAAmB,KAAK;EACvD,IAAI,mBAAmB,MAAM,OAAO,OAAO,aAAa,aAAa,SAAS,IAAI;EAElF,MAAM,UACJ,OAAO,aAAa,aAChB,SAAS;GAAE;GAAO;GAAgB;GAAgB,YAAY,KAAK;EAAW,CAAC,IAC/E;EACN,IAAI,eAAe,OAAO,GAAG,OAAO;EACpC,QAAQ,KAAK,0EAA0E;EACvF,OAAO;CACT;AACF;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,uBACd,UACgD;CAChD,QAAQ,OAAO,cAAc;EAC3B,IAAI;EACJ,IAAI;GACF,QAAQ,WAAW,CAAC,EAAE,iBAAiB,mBAAmB,OAAO,UAAU,cAAc,CAAC;EAC5F,SAAS,GAAY;GACnB,QAAQ,MAAM,sDAAsD,CAAC;EACvE;EACA,WAAW,OAAO,OAAO,SAAS;CACpC;AACF"}
1
+ {"version":3,"file":"posthog-error-boundary.mjs","names":[],"sources":["../../src/react/posthog-error-boundary.tsx"],"sourcesContent":["import type { CaptureResult, Properties } from '@posthog/types';\nimport {\n Component,\n type ErrorInfo,\n type FunctionComponent,\n type ReactNode,\n isValidElement,\n} from 'react';\nimport { getPosthog } from '../third-parties/posthog';\n\nexport interface PosthogErrorBoundaryFallbackProps {\n error: unknown;\n /** The `$exception` event sent; `undefined` while only the stub is there, which queues it. */\n exceptionEvent: CaptureResult | undefined;\n componentStack: string;\n resetError: () => void;\n}\n\nexport interface PosthogErrorBoundaryProps {\n children?: ReactNode | (() => ReactNode);\n fallback?: ReactNode | FunctionComponent<PosthogErrorBoundaryFallbackProps>;\n additionalProperties?: Properties | ((error: unknown, errorInfo: ErrorInfo) => Properties);\n}\n\ninterface State {\n error: unknown;\n componentStack: string | null;\n exceptionEvent: CaptureResult | undefined;\n}\n\nconst INITIAL_STATE: State = { error: null, componentStack: null, exceptionEvent: undefined };\n\n/**\n * The error as PostHog's own boundary reports it: the React component stack added as a cause, so\n * the issue shows which components it was thrown in.\n */\nfunction withComponentStack(error: unknown, componentStack: string | null | undefined): unknown {\n if (!componentStack) return error;\n const isError = error instanceof Error;\n const stackError = new Error(\n isError ? error.message : `Primitive value captured as exception: ${String(error)}`\n );\n stackError.name = `React ErrorBoundary ${isError ? error.name : 'Error'}`;\n stackError.stack = componentStack;\n if (!isError) return stackError;\n // At the end of the error's cause chain, keeping a last cause that is not an error under it.\n const seen = new WeakSet<Error>();\n let current = error;\n while (!seen.has(current)) {\n seen.add(current);\n if (!(current.cause instanceof Error)) {\n if (current.cause !== undefined) stackError.cause = current.cause;\n current.cause = stackError;\n break;\n }\n current = current.cause;\n }\n return error;\n}\n\n/**\n * `posthog-js/react`'s `PostHogErrorBoundary`, with its props, for the snippet-loaded library: a\n * render error in `children` is sent to PostHog's error tracking (`captureException`, as an\n * `$exception` event tied to the session's replay) and `fallback` renders instead — a\n * component gets the error and `resetError`. An error thrown before the library has loaded is\n * queued on the stub and sent once it has.\n *\n * The boundary itself never throws: a failure to report (no PostHog, an ad blocker that stopped the\n * library, a throwing `additionalProperties`) is logged and the fallback still renders. It\n * catches render errors only, as any error boundary; errors outside React's render (event\n * handlers, unhandled rejections) are the library's exception autocapture's, enabled in the\n * snippet's `config` (`capture_exceptions`).\n */\nexport class PosthogErrorBoundary extends Component<PosthogErrorBoundaryProps, State> {\n override state = INITIAL_STATE;\n\n override componentDidCatch(error: unknown, errorInfo: ErrorInfo) {\n const componentStack = errorInfo.componentStack ?? '';\n let exceptionEvent: CaptureResult | undefined;\n // Reporting must never fail the boundary: an error thrown here would go to the boundary\n // above it, if any — `additionalProperties` throwing, or an error that cannot take a cause.\n try {\n const { additionalProperties } = this.props;\n const properties =\n typeof additionalProperties === 'function'\n ? additionalProperties(error, errorInfo)\n : additionalProperties;\n exceptionEvent = getPosthog()?.captureException(\n withComponentStack(error, componentStack),\n properties\n );\n } catch (e: unknown) {\n console.error('PosthogErrorBoundary: the error was not reported', e);\n }\n this.setState({ error, componentStack, exceptionEvent });\n }\n\n resetError = () => {\n this.setState(INITIAL_STATE);\n };\n\n override render() {\n const { children, fallback } = this.props;\n const { error, componentStack, exceptionEvent } = this.state;\n if (componentStack === null) return typeof children === 'function' ? children() : children;\n\n const element =\n typeof fallback === 'function'\n ? fallback({ error, componentStack, exceptionEvent, resetError: this.resetError })\n : fallback;\n if (isValidElement(element)) return element;\n console.warn('PosthogErrorBoundary: fallback is not a React element; rendering nothing');\n return null;\n }\n}\n\n/**\n * `posthog-js/react`'s `setupReactErrorHandler`, for the snippet-loaded library, so without its\n * `client`: a handler for React 19's root options, which report what no `PosthogErrorBoundary`\n * sees — `onUncaughtError` (no boundary caught it), `onCaughtError` (a framework's boundary did,\n * e.g. TanStack Router's `errorComponent`) and `onRecoverableError` (a hydration mismatch React\n * recovered from). The error goes to PostHog with its component stack; `callback` gets the event\n * (`undefined` while only the stub is there), as React's own logging does not run once a handler\n * is set.\n *\n * ```tsx\n * hydrateRoot(document, <StartClient />, {\n * onUncaughtError: setupReactErrorHandler(),\n * onCaughtError: setupReactErrorHandler(),\n * onRecoverableError: setupReactErrorHandler(),\n * });\n * ```\n *\n * Never throws, as `PosthogErrorBoundary`: a failure to report is logged.\n */\nexport function setupReactErrorHandler(\n callback?: (event: CaptureResult | undefined, error: unknown, errorInfo: ErrorInfo) => void\n): (error: unknown, errorInfo: ErrorInfo) => void {\n return (error, errorInfo) => {\n let event: CaptureResult | undefined;\n try {\n event = getPosthog()?.captureException(withComponentStack(error, errorInfo.componentStack));\n } catch (e: unknown) {\n console.error('setupReactErrorHandler: the error was not reported', e);\n }\n callback?.(event, error, errorInfo);\n };\n}\n"],"mappings":";;;AA8BA,MAAM,gBAAuB;CAAE,OAAO;CAAM,gBAAgB;CAAM,gBAAgB,KAAA;AAAU;;;;;AAM5F,SAAS,mBAAmB,OAAgB,gBAAoD;CAC9F,IAAI,CAAC,gBAAgB,OAAO;CAC5B,MAAM,UAAU,iBAAiB;CACjC,MAAM,aAAa,IAAI,MACrB,UAAU,MAAM,UA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O;CACT;AACF;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,uBACd,UACgD;CAChD,QAAQ,OAAO,cAAc;EAC3B,IAAI;EACJ,IAAI;GACF,QAAQ,WAAW,CAAC,EAAE,iBAAiB,mBAAmB,OAAO,UAAU,cAAc,CAAC;EAC5F,SAAS,GAAY;GACnB,QAAQ,MAAM,sDAAsD,CAAC;EACvE;EACA,WAAW,OAAO,OAAO,SAAS;CACpC;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.cjs","names":["createContext","createElement","getPosthog","useRef","useSyncExternalStore","getLoadedPosthog","use"],"sources":["../../src/react/posthog.ts"],"sourcesContent":["import type { BootstrapConfig, FeatureFlagResult, JsonType, PostHog } from 'posthog-js';\nimport {\n type ReactNode,\n createContext,\n createElement,\n use,\n useRef,\n useSyncExternalStore,\n} from 'react';\nimport { getLoadedPosthog, getPosthog } from '../third-parties/posthog';\n\nconst noop = () => {};\n\nconst Bootstrap = createContext<BootstrapConfig | undefined>(undefined);\n\n/**\n * The counterpart of `posthog-js/react`'s `PostHogProvider`, for the snippet-loaded library. It\n * does not initialize PostHog — `posthogAnalytics` does — only carries what the hooks need from\n * the server: the request's server-evaluated flags, the same object as the snippet's\n * `config.bootstrap`, for the flag hooks to render with on the server, through hydration and until\n * the library has loaded its flags — an experiment's variant renders at once, with no flicker and\n * no hydration mismatch. Wrap the app in it, e.g. in the root route.\n */\nexport function PosthogProvider({\n bootstrap,\n children,\n}: {\n bootstrap: BootstrapConfig | undefined;\n children: ReactNode;\n}) {\n return createElement(Bootstrap.Provider, { value: bootstrap }, children);\n}\n\n/** Subscribes to flag (re)loads; on the stub the subscription is queued and has no unsubscribe. */\nfunction subscribe(onChange: () => void): () => void {\n const unsubscribe: (() => void) | undefined = getPosthog()?.onFeatureFlags(onChange);\n return unsubscribe ?? noop;\n}\n\n/**\n * What `read` returns once the library has loaded its flags, and `bootstrapped` until then and on\n * the server, re-read when flags reload. The value is kept while its JSON is unchanged, as\n * `useSyncExternalStore` needs: PostHog builds a new result or payload object on every read.\n */\nfunction useFlags<T>(read: (posthog: PostHog) => T, bootstrapped: T): T {\n const cache = useRef<{ json: string | undefined; value: T }>(undefined);\n const stable = (value: T) => {\n // Typed wider: `JSON.stringify(undefined)` is `undefined`, whatever its type says.\n const json: string | undefined = JSON.stringify(value);\n if (!cache.current || cache.current.json !== json) cache.current = { json, value };\n return cache.current.value;\n };\n return useSyncExternalStore(\n subscribe,\n () => {\n const posthog = getLoadedPosthog();\n // As `posthog-js/react`: the bootstrap until the flags request has answered, not only until\n // the library has loaded, so no flag is read (and no exposure recorded) before then.\n return stable(posthog?.featureFlags.hasLoadedFlags ? read(posthog) : bootstrapped);\n },\n () => stable(bootstrapped)\n );\n}\n\n/*\n * The hooks of `posthog-js/react`, with its names and signatures, for the snippet-loaded library.\n *\n * Under a `<PosthogProvider>` each is the server's value until the library has loaded its\n * flags, on the server too. Without one it is `undefined` on the server and through hydration, so\n * the default renders first and the variant once flags arrive; to wait for them instead, call\n * `use(browser())` and `use(posthogFlagsReady())` above it, under a `<Suspense>`.\n *\n * Reading a flag records the exposure (`$feature_flag_called`) once the flags have loaded, as\n * PostHog's do — except the payload's — not while only a bootstrapped value is shown.\n */\n\n/** A flag's value: `true`/`false`, a multivariate flag's variant, or `undefined` until loaded. */\nexport function useFeatureFlagVariantKey(flag: string): string | boolean | undefined {\n const bootstrapped = use(Bootstrap)?.featureFlags?.[flag];\n return useFlags((posthog) => posthog.getFeatureFlag(flag), bootstrapped);\n}\n\n/** Whether a flag is on (a variant counts as on); `defaultValue` while it is unknown. */\nexport function useFeatureFlagEnabled(flag: string): boolean | undefined;\nexport function useFeatureFlagEnabled(flag: string, defaultValue: boolean): boolean;\nexport function useFeatureFlagEnabled(flag: string, defaultValue?: boolean) {\n const value = use(Bootstrap)?.featureFlags?.[flag];\n const bootstrapped = value === undefined ? undefined : !!value;\n return useFlags((posthog) => posthog.isFeatureEnabled(flag), bootstrapped) ?? defaultValue;\n}\n\n/** A flag's payload, read without recording an exposure. */\nexport function useFeatureFlagPayload(flag: string): JsonType {\n const bootstrapped = use(Bootstrap)?.featureFlagPayloads?.[flag];\n return useFlags(\n (posthog) => posthog.getFeatureFlagResult(flag, { send_event: false })?.payload,\n bootstrapped\n );\n}\n\n/** A flag's value, variant and payload together; `undefined` while it is unknown. */\nexport function useFeatureFlagResult(flag: string): FeatureFlagResult | undefined {\n const bootstrap = use(Bootstrap);\n const value = bootstrap?.featureFlags?.[flag];\n const bootstrapped: FeatureFlagResult | undefined =\n value === undefined\n ? undefined\n : {\n key: flag,\n enabled: typeof value === 'string' ? true : value,\n variant: typeof value === 'string' ? value : undefined,\n payload: bootstrap?.featureFlagPayloads?.[flag],\n };\n return useFlags((posthog) => posthog.getFeatureFlagResult(flag), bootstrapped);\n}\n\n/**\n * The keys of the flags: only those that are on while bootstrapped, every flag the library has\n * once loaded — as `posthog-js/react`'s does.\n */\nexport function useActiveFeatureFlags(): string[] {\n const flags = use(Bootstrap)?.featureFlags ?? {};\n const bootstrapped = Object.keys(flags).filter((key) => flags[key]);\n return useFlags((posthog) => posthog.featureFlags.getFlags(), bootstrapped);\n}\n\n/**\n * `window.posthog`, as `posthog-js/react`'s `usePostHog`: the snippet's stub until the library\n * loads — which queues the calls returning nothing (`capture`, `identify`, …) — then the library,\n * re-rendering when it replaces the stub; `undefined` on the server. Use the value of the latest\n * render rather than one kept from before (e.g. in a ref): calls on a stub kept past the load are\n * lost. A method that returns a value returns `undefined` on the stub; read flags with the hooks.\n *\n * The re-render comes from the flags loading, as the library answers the stub's queued\n * `onFeatureFlags`: with feature flags disabled it stays on the stub until something else\n * re-renders.\n */\nexport function usePostHog(): PostHog | undefined {\n return useSyncExternalStore(subscribe, getPosthog, () => undefined);\n}\n"],"mappings":";;;;AAWA,MAAM,aAAa,CAAC;AAEpB,MAAM,aAAA,GAAYA,MAAAA,cAAAA,CAA2C,KAAA,CAAS;;;;;;;;;AAUtE,SAAgB,gBAAgB,EAC9B,WACA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AAGA,SAAgB,qBAAqB,MAA6C;CAChF,MAAM,aAAA,GAAYA,MAAAA,IAAAA,CAAI,SAAS;CAC/B,MAAM,QAAQ,WAAW,eAAe;CAUxC,OAAO,UAAU,YAAY,QAAQ,qBAAqB,IAAI,GAR5D,UAAU,KAAA,IACN,KAAA,IACA;EACE,KAAK;EACL,SAAS,OAAO,UAAU,WAAW,OAAO;EAC5C,SAAS,OAAO,UAAU,WAAW,QAAQ,KAAA;EAC7C,SAAS,WAAW,sBAAsB;CAC5C,CACuE;AAC/E;;;;;AAMA,SAAgB,wBAAkC;CAChD,MAAM,SAAA,GAAQA,MAAAA,IAAAA,CAAI,SAAS,CAAC,EAAE,gBAAgB,CAAC;CAE/C,OAAO,UAAU,YAAY,QAAQ,aAAa,SAAS,GADtC,OAAO,KAAK,KAAK,CAAC,CAAC,QAAQ,QAAQ,MAAM,IACW,CAAC;AAC5E;;;;;;;;;;;;AAaA,SAAgB,aAAkC;CAChD,QAAA,GAAOF,MAAAA,qBAAAA,CAAqB,WAAWF,8BAAAA,kBAAkB,KAAA,CAAS;AACpE"}
1
+ {"version":3,"file":"posthog.cjs","names":["createContext","createElement","getPosthog","useRef","useSyncExternalStore","getLoadedPosthog","use"],"sources":["../../src/react/posthog.ts"],"sourcesContent":["import type { BootstrapConfig, FeatureFlagResult, JsonType, PostHog } from '@posthog/types';\nimport {\n type ReactNode,\n createContext,\n createElement,\n use,\n useRef,\n useSyncExternalStore,\n} from 'react';\nimport { getLoadedPosthog, getPosthog } from '../third-parties/posthog';\n\nconst noop = () => {};\n\nconst Bootstrap = createContext<BootstrapConfig | undefined>(undefined);\n\n/**\n * The counterpart of `posthog-js/react`'s `PostHogProvider`, for the snippet-loaded library. It\n * does not initialize PostHog — `posthogAnalytics` does — only carries what the hooks need from\n * the server: the request's server-evaluated flags, the same object as the snippet's\n * `config.bootstrap`, for the flag hooks to render with on the server, through hydration and until\n * the library has loaded its flags — an experiment's variant renders at once, with no flicker and\n * no hydration mismatch. Wrap the app in it, e.g. in the root route.\n */\nexport function PosthogProvider({\n bootstrap,\n children,\n}: {\n bootstrap: BootstrapConfig | undefined;\n children: ReactNode;\n}) {\n return createElement(Bootstrap.Provider, { value: bootstrap }, children);\n}\n\n/** Subscribes to flag (re)loads; on the stub the subscription is queued and has no unsubscribe. */\nfunction subscribe(onChange: () => void): () => void {\n const unsubscribe: (() => void) | undefined = getPosthog()?.onFeatureFlags(onChange);\n return unsubscribe ?? noop;\n}\n\n/**\n * The loaded library's flag state, which `posthog-js/react` reads too: on the instance, but left\n * out of `@posthog/types`, whose `featureFlags` declares only the override methods.\n */\ntype LoadedPostHog = PostHog & {\n featureFlags: { hasLoadedFlags: boolean; getFlags(): string[] };\n};\n\n/**\n * What `read` returns once the library has loaded its flags, and `bootstrapped` until then and on\n * the server, re-read when flags reload. The value is kept while its JSON is unchanged, as\n * `useSyncExternalStore` needs: PostHog builds a new result or payload object on every read.\n */\nfunction useFlags<T>(read: (posthog: LoadedPostHog) => T, bootstrapped: T): T {\n const cache = useRef<{ json: string | undefined; value: T }>(undefined);\n const stable = (value: T) => {\n // Typed wider: `JSON.stringify(undefined)` is `undefined`, whatever its type says.\n const json: string | undefined = JSON.stringify(value);\n if (!cache.current || cache.current.json !== json) cache.current = { json, value };\n return cache.current.value;\n };\n return useSyncExternalStore(\n subscribe,\n () => {\n const posthog = getLoadedPosthog() as LoadedPostHog | undefined;\n // As `posthog-js/react`: the bootstrap until the flags request has answered, not only until\n // the library has loaded, so no flag is read (and no exposure recorded) before then.\n return stable(posthog?.featureFlags.hasLoadedFlags ? read(posthog) : bootstrapped);\n },\n () => stable(bootstrapped)\n );\n}\n\n/*\n * The hooks of `posthog-js/react`, with its names and signatures, for the snippet-loaded library.\n *\n * Under a `<PosthogProvider>` each is the server's value until the library has loaded its\n * flags, on the server too. Without one it is `undefined` on the server and through hydration, so\n * the default renders first and the variant once flags arrive; to wait for them instead, call\n * `use(browser())` and `use(posthogFlagsReady())` above it, under a `<Suspense>`.\n *\n * Reading a flag records the exposure (`$feature_flag_called`) once the flags have loaded, as\n * PostHog's do — except the payload's — not while only a bootstrapped value is shown.\n */\n\n/** A flag's value: `true`/`false`, a multivariate flag's variant, or `undefined` until loaded. */\nexport function useFeatureFlagVariantKey(flag: string): string | boolean | undefined {\n const bootstrapped = use(Bootstrap)?.featureFlags?.[flag];\n return useFlags((posthog) => posthog.getFeatureFlag(flag), bootstrapped);\n}\n\n/** Whether a flag is on (a variant counts as on); `defaultValue` while it is unknown. */\nexport function useFeatureFlagEnabled(flag: string): boolean | undefined;\nexport function useFeatureFlagEnabled(flag: string, defaultValue: boolean): boolean;\nexport function useFeatureFlagEnabled(flag: string, defaultValue?: boolean) {\n const value = use(Bootstrap)?.featureFlags?.[flag];\n const bootstrapped = value === undefined ? undefined : !!value;\n return useFlags((posthog) => posthog.isFeatureEnabled(flag), bootstrapped) ?? defaultValue;\n}\n\n/** A flag's payload, read without recording an exposure. */\nexport function useFeatureFlagPayload(flag: string): JsonType {\n const bootstrapped = use(Bootstrap)?.featureFlagPayloads?.[flag];\n return useFlags(\n (posthog) => posthog.getFeatureFlagResult(flag, { send_event: false })?.payload,\n bootstrapped\n );\n}\n\n/** A flag's value, variant and payload together; `undefined` while it is unknown. */\nexport function useFeatureFlagResult(flag: string): FeatureFlagResult | undefined {\n const bootstrap = use(Bootstrap);\n const value = bootstrap?.featureFlags?.[flag];\n const bootstrapped: FeatureFlagResult | undefined =\n value === undefined\n ? undefined\n : {\n key: flag,\n enabled: typeof value === 'string' ? true : value,\n variant: typeof value === 'string' ? value : undefined,\n payload: bootstrap?.featureFlagPayloads?.[flag],\n };\n return useFlags((posthog) => posthog.getFeatureFlagResult(flag), bootstrapped);\n}\n\n/**\n * The keys of the flags: only those that are on while bootstrapped, every flag the library has\n * once loaded — as `posthog-js/react`'s does.\n */\nexport function useActiveFeatureFlags(): string[] {\n const flags = use(Bootstrap)?.featureFlags ?? {};\n const bootstrapped = Object.keys(flags).filter((key) => flags[key]);\n return useFlags((posthog) => posthog.featureFlags.getFlags(), bootstrapped);\n}\n\n/**\n * `window.posthog`, as `posthog-js/react`'s `usePostHog`: the snippet's stub until the library\n * loads — which queues the calls returning nothing (`capture`, `identify`, …) — then the library,\n * re-rendering when it replaces the stub; `undefined` on the server. Use the value of the latest\n * render rather than one kept from before (e.g. in a ref): calls on a stub kept past the load are\n * lost. A method that returns a value returns `undefined` on the stub; read flags with the hooks.\n *\n * The re-render comes from the flags loading, as the library answers the stub's queued\n * `onFeatureFlags`: with feature flags disabled it stays on the stub until something else\n * re-renders.\n */\nexport function usePostHog(): PostHog | undefined {\n return useSyncExternalStore(subscribe, getPosthog, () => undefined);\n}\n"],"mappings":";;;;AAWA,MAAM,aAAa,CAAC;AAEpB,MAAM,aAAA,GAAYA,MAAAA,cAAAA,CAA2C,KAAA,CAAS;;;;;;;;;AAUtE,SAAgB,gBAAgB,EAC9B,WACA,YAIC;CACD,QAAA,GAAOC,MAAAA,cAAAA,CAAc,UAAU,UAAU,EAAE,OAAO,UAAU,GAAG,QAAQ;AACzE;;AAGA,SAAS,UAAU,UAAkC;CAEnD,OAD8CC,8BAAAA,WAAW,CAAC,EAAE,eAAe,QAAQ,KAC7D;AACxB;;;;;;AAeA,SAAS,SAAY,MAAqC,cAAoB;CAC5E,MAAM,SAAA,GAAQC,MAAAA,OAAAA,CAA+C,KAAA,CAAS;CACtE,MAAM,UAAU,UAAa;EAE3B,MAAM,OAA2B,KAAK,UAAU,KAAK;EACrD,IAAI,CAAC,MAAM,WAAW,MAAM,QAAQ,SAAS,MAAM,MAAM,UAAU;GAAE;GAAM;EAAM;EACjF,OAAO,MAAM,QAAQ;CACvB;CACA,QAAA,GAAOC,MAAAA,qBAAAA,CACL,iBACM;EACJ,MAAM,UAAUC,8BAAAA,iBAAiB;EAGjC,OAAO,OAAO,SAAS,aAAa,iBAAiB,KAAK,OAAO,IAAI,YAAY;CACnF,SACM,OAAO,YAAY,CAC3B;AACF;;AAeA,SAAgB,yBAAyB,MAA4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"}
@@ -1,5 +1,5 @@
1
1
  import { ReactNode } from "react";
2
- import { BootstrapConfig, FeatureFlagResult, JsonType, PostHog } from "posthog-js";
2
+ import { BootstrapConfig, FeatureFlagResult, JsonType, PostHog } from "@posthog/types";
3
3
  /**
4
4
  * The counterpart of `posthog-js/react`'s `PostHogProvider`, for the snippet-loaded library. It
5
5
  * does not initialize PostHog — `posthogAnalytics` does — only carries what the hooks need from
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.d.cts","names":[],"sources":["../../src/react/posthog.ts"],"mappings":";;;;;;;;;;wBAuBgB,kBACd,WACA;EAEA,WAAW;EACX,UAAU;oBACX,yCAAA,cAAA;;wBAgDe,yBAAyB;;wBAMzB,sBAAsB;wBACtB,sBAAsB,cAAc;;wBAQpC,sBAAsB,eAAe;;wBASrC,qBAAqB,eAAe;;;;;wBAmBpC;;;;;;;;;;;;wBAiBA,cAAc"}
1
+ {"version":3,"file":"posthog.d.cts","names":[],"sources":["../../src/react/posthog.ts"],"mappings":";;;;;;;;;;wBAuBgB,kBACd,WACA;EAEA,WAAW;EACX,UAAU;oBACX,yCAAA,cAAA;;wBAwDe,yBAAyB;;wBAMzB,sBAAsB;wBACtB,sBAAsB,cAAc;;wBAQpC,sBAAsB,eAAe;;wBASrC,qBAAqB,eAAe;;;;;wBAmBpC;;;;;;;;;;;;wBAiBA,cAAc"}
@@ -1,5 +1,5 @@
1
1
  import { ReactNode } from "react";
2
- import { BootstrapConfig, FeatureFlagResult, JsonType, PostHog } from "posthog-js";
2
+ import { BootstrapConfig, FeatureFlagResult, JsonType, PostHog } from "@posthog/types";
3
3
  /**
4
4
  * The counterpart of `posthog-js/react`'s `PostHogProvider`, for the snippet-loaded library. It
5
5
  * does not initialize PostHog — `posthogAnalytics` does — only carries what the hooks need from
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.d.mts","names":[],"sources":["../../src/react/posthog.ts"],"mappings":";;;;;;;;;;wBAuBgB,kBACd,WACA;EAEA,WAAW;EACX,UAAU;oBACX,yCAAA,cAAA;;wBAgDe,yBAAyB;;wBAMzB,sBAAsB;wBACtB,sBAAsB,cAAc;;wBAQpC,sBAAsB,eAAe;;wBASrC,qBAAqB,eAAe;;;;;wBAmBpC;;;;;;;;;;;;wBAiBA,cAAc"}
1
+ {"version":3,"file":"posthog.d.mts","names":[],"sources":["../../src/react/posthog.ts"],"mappings":";;;;;;;;;;wBAuBgB,kBACd,WACA;EAEA,WAAW;EACX,UAAU;oBACX,yCAAA,cAAA;;wBAwDe,yBAAyB;;wBAMzB,sBAAsB;wBACtB,sBAAsB,cAAc;;wBAQpC,sBAAsB,eAAe;;wBASrC,qBAAqB,eAAe;;;;;wBAmBpC;;;;;;;;;;;;wBAiBA,cAAc"}
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.mjs","names":[],"sources":["../../src/react/posthog.ts"],"sourcesContent":["import type { BootstrapConfig, FeatureFlagResult, JsonType, PostHog } from 'posthog-js';\nimport {\n type ReactNode,\n createContext,\n createElement,\n use,\n useRef,\n useSyncExternalStore,\n} from 'react';\nimport { getLoadedPosthog, getPosthog } from '../third-parties/posthog';\n\nconst noop = () => {};\n\nconst Bootstrap = createContext<BootstrapConfig | undefined>(undefined);\n\n/**\n * The counterpart of `posthog-js/react`'s `PostHogProvider`, for the snippet-loaded library. It\n * does not initialize PostHog — `posthogAnalytics` does — only carries what the hooks need from\n * the server: the request's server-evaluated flags, the same object as the snippet's\n * `config.bootstrap`, for the flag hooks to render with on the server, through hydration and until\n * the library has loaded its flags — an experiment's variant renders at once, with no flicker and\n * no hydration mismatch. Wrap the app in it, e.g. in the root route.\n */\nexport function PosthogProvider({\n bootstrap,\n children,\n}: {\n bootstrap: BootstrapConfig | undefined;\n children: ReactNode;\n}) {\n return createElement(Bootstrap.Provider, { value: bootstrap }, children);\n}\n\n/** Subscribes to flag (re)loads; on the stub the subscription is queued and has no unsubscribe. */\nfunction subscribe(onChange: () => void): () => void {\n const unsubscribe: (() => void) | undefined = getPosthog()?.onFeatureFlags(onChange);\n return unsubscribe ?? noop;\n}\n\n/**\n * What `read` returns once the library has loaded its flags, and `bootstrapped` until then and on\n * the server, re-read when flags reload. The value is kept while its JSON is unchanged, as\n * `useSyncExternalStore` needs: PostHog builds a new result or payload object on every read.\n */\nfunction useFlags<T>(read: (posthog: PostHog) => T, bootstrapped: T): T {\n const cache = useRef<{ json: string | undefined; value: T }>(undefined);\n const stable = (value: T) => {\n // Typed wider: `JSON.stringify(undefined)` is `undefined`, whatever its type says.\n const json: string | undefined = JSON.stringify(value);\n if (!cache.current || cache.current.json !== json) cache.current = { json, value };\n return cache.current.value;\n };\n return useSyncExternalStore(\n subscribe,\n () => {\n const posthog = getLoadedPosthog();\n // As `posthog-js/react`: the bootstrap until the flags request has answered, not only until\n // the library has loaded, so no flag is read (and no exposure recorded) before then.\n return stable(posthog?.featureFlags.hasLoadedFlags ? read(posthog) : bootstrapped);\n },\n () => stable(bootstrapped)\n );\n}\n\n/*\n * The hooks of `posthog-js/react`, with its names and signatures, for the snippet-loaded library.\n *\n * Under a `<PosthogProvider>` each is the server's value until the library has loaded its\n * flags, on the server too. Without one it is `undefined` on the server and through hydration, so\n * the default renders first and the variant once flags arrive; to wait for them instead, call\n * `use(browser())` and `use(posthogFlagsReady())` above it, under a `<Suspense>`.\n *\n * Reading a flag records the exposure (`$feature_flag_called`) once the flags have loaded, as\n * PostHog's do — except the payload's — not while only a bootstrapped value is shown.\n */\n\n/** A flag's value: `true`/`false`, a multivariate flag's variant, or `undefined` until loaded. */\nexport function useFeatureFlagVariantKey(flag: string): string | boolean | undefined {\n const bootstrapped = use(Bootstrap)?.featureFlags?.[flag];\n return useFlags((posthog) => posthog.getFeatureFlag(flag), bootstrapped);\n}\n\n/** Whether a flag is on (a variant counts as on); `defaultValue` while it is unknown. */\nexport function useFeatureFlagEnabled(flag: string): boolean | undefined;\nexport function useFeatureFlagEnabled(flag: string, defaultValue: boolean): boolean;\nexport function useFeatureFlagEnabled(flag: string, defaultValue?: boolean) {\n const value = use(Bootstrap)?.featureFlags?.[flag];\n const bootstrapped = value === undefined ? undefined : !!value;\n return useFlags((posthog) => posthog.isFeatureEnabled(flag), bootstrapped) ?? defaultValue;\n}\n\n/** A flag's payload, read without recording an exposure. */\nexport function useFeatureFlagPayload(flag: string): JsonType {\n const bootstrapped = use(Bootstrap)?.featureFlagPayloads?.[flag];\n return useFlags(\n (posthog) => posthog.getFeatureFlagResult(flag, { send_event: false })?.payload,\n bootstrapped\n );\n}\n\n/** A flag's value, variant and payload together; `undefined` while it is unknown. */\nexport function useFeatureFlagResult(flag: string): FeatureFlagResult | undefined {\n const bootstrap = use(Bootstrap);\n const value = bootstrap?.featureFlags?.[flag];\n const bootstrapped: FeatureFlagResult | undefined =\n value === undefined\n ? undefined\n : {\n key: flag,\n enabled: typeof value === 'string' ? true : value,\n variant: typeof value === 'string' ? value : undefined,\n payload: bootstrap?.featureFlagPayloads?.[flag],\n };\n return useFlags((posthog) => posthog.getFeatureFlagResult(flag), bootstrapped);\n}\n\n/**\n * The keys of the flags: only those that are on while bootstrapped, every flag the library has\n * once loaded — as `posthog-js/react`'s does.\n */\nexport function useActiveFeatureFlags(): string[] {\n const flags = use(Bootstrap)?.featureFlags ?? {};\n const bootstrapped = Object.keys(flags).filter((key) => flags[key]);\n return useFlags((posthog) => posthog.featureFlags.getFlags(), bootstrapped);\n}\n\n/**\n * `window.posthog`, as `posthog-js/react`'s `usePostHog`: the snippet's stub until the library\n * loads — which queues the calls returning nothing (`capture`, `identify`, …) — then the library,\n * re-rendering when it replaces the stub; `undefined` on the server. Use the value of the latest\n * render rather than one kept from before (e.g. in a ref): calls on a stub kept past the load are\n * lost. A method that returns a value returns `undefined` on the stub; read flags with the hooks.\n *\n * The re-render comes from the flags loading, as the library answers the stub's queued\n * `onFeatureFlags`: with feature flags disabled it stays on the stub until something else\n * re-renders.\n */\nexport function usePostHog(): PostHog | undefined {\n return useSyncExternalStore(subscribe, getPosthog, () => undefined);\n}\n"],"mappings":";;;AAWA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AAI,SAAS;CAC/B,MAAM,QAAQ,WAAW,eAAe;CAUxC,OAAO,UAAU,YAAY,QAAQ,qBAAqB,IAAI,GAR5D,UAAU,KAAA,IACN,KAAA,IACA;EACE,KAAK;EACL,SAAS,OAAO,UAAU,WAAW,OAAO;EAC5C,SAAS,OAAO,UAAU,WAAW,QAAQ,KAAA;EAC7C,SAAS,WAAW,sBAAsB;CAC5C,CACuE;AAC/E;;;;;AAMA,SAAgB,wBAAkC;CAChD,MAAM,QAAQ,IAAI,SAAS,CAAC,EAAE,gBAAgB,CAAC;CAE/C,OAAO,UAAU,YAAY,QAAQ,aAAa,SAAS,GADtC,OAAO,KAAK,KAAK,CAAC,CAAC,QAAQ,QAAQ,MAAM,IACW,CAAC;AAC5E;;;;;;;;;;;;AAaA,SAAgB,aAAkC;CAChD,OAAO,qBAAqB,WAAW,kBAAkB,KAAA,CAAS;AACpE"}
1
+ {"version":3,"file":"posthog.mjs","names":[],"sources":["../../src/react/posthog.ts"],"sourcesContent":["import type { BootstrapConfig, FeatureFlagResult, JsonType, PostHog } from '@posthog/types';\nimport {\n type ReactNode,\n createContext,\n createElement,\n use,\n useRef,\n useSyncExternalStore,\n} from 'react';\nimport { getLoadedPosthog, getPosthog } from '../third-parties/posthog';\n\nconst noop = () => {};\n\nconst Bootstrap = createContext<BootstrapConfig | undefined>(undefined);\n\n/**\n * The counterpart of `posthog-js/react`'s `PostHogProvider`, for the snippet-loaded library. It\n * does not initialize PostHog — `posthogAnalytics` does — only carries what the hooks need from\n * the server: the request's server-evaluated flags, the same object as the snippet's\n * `config.bootstrap`, for the flag hooks to render with on the server, through hydration and until\n * the library has loaded its flags — an experiment's variant renders at once, with no flicker and\n * no hydration mismatch. Wrap the app in it, e.g. in the root route.\n */\nexport function PosthogProvider({\n bootstrap,\n children,\n}: {\n bootstrap: BootstrapConfig | undefined;\n children: ReactNode;\n}) {\n return createElement(Bootstrap.Provider, { value: bootstrap }, children);\n}\n\n/** Subscribes to flag (re)loads; on the stub the subscription is queued and has no unsubscribe. */\nfunction subscribe(onChange: () => void): () => void {\n const unsubscribe: (() => void) | undefined = getPosthog()?.onFeatureFlags(onChange);\n return unsubscribe ?? noop;\n}\n\n/**\n * The loaded library's flag state, which `posthog-js/react` reads too: on the instance, but left\n * out of `@posthog/types`, whose `featureFlags` declares only the override methods.\n */\ntype LoadedPostHog = PostHog & {\n featureFlags: { hasLoadedFlags: boolean; getFlags(): string[] };\n};\n\n/**\n * What `read` returns once the library has loaded its flags, and `bootstrapped` until then and on\n * the server, re-read when flags reload. The value is kept while its JSON is unchanged, as\n * `useSyncExternalStore` needs: PostHog builds a new result or payload object on every read.\n */\nfunction useFlags<T>(read: (posthog: LoadedPostHog) => T, bootstrapped: T): T {\n const cache = useRef<{ json: string | undefined; value: T }>(undefined);\n const stable = (value: T) => {\n // Typed wider: `JSON.stringify(undefined)` is `undefined`, whatever its type says.\n const json: string | undefined = JSON.stringify(value);\n if (!cache.current || cache.current.json !== json) cache.current = { json, value };\n return cache.current.value;\n };\n return useSyncExternalStore(\n subscribe,\n () => {\n const posthog = getLoadedPosthog() as LoadedPostHog | undefined;\n // As `posthog-js/react`: the bootstrap until the flags request has answered, not only until\n // the library has loaded, so no flag is read (and no exposure recorded) before then.\n return stable(posthog?.featureFlags.hasLoadedFlags ? read(posthog) : bootstrapped);\n },\n () => stable(bootstrapped)\n );\n}\n\n/*\n * The hooks of `posthog-js/react`, with its names and signatures, for the snippet-loaded library.\n *\n * Under a `<PosthogProvider>` each is the server's value until the library has loaded its\n * flags, on the server too. Without one it is `undefined` on the server and through hydration, so\n * the default renders first and the variant once flags arrive; to wait for them instead, call\n * `use(browser())` and `use(posthogFlagsReady())` above it, under a `<Suspense>`.\n *\n * Reading a flag records the exposure (`$feature_flag_called`) once the flags have loaded, as\n * PostHog's do — except the payload's — not while only a bootstrapped value is shown.\n */\n\n/** A flag's value: `true`/`false`, a multivariate flag's variant, or `undefined` until loaded. */\nexport function useFeatureFlagVariantKey(flag: string): string | boolean | undefined {\n const bootstrapped = use(Bootstrap)?.featureFlags?.[flag];\n return useFlags((posthog) => posthog.getFeatureFlag(flag), bootstrapped);\n}\n\n/** Whether a flag is on (a variant counts as on); `defaultValue` while it is unknown. */\nexport function useFeatureFlagEnabled(flag: string): boolean | undefined;\nexport function useFeatureFlagEnabled(flag: string, defaultValue: boolean): boolean;\nexport function useFeatureFlagEnabled(flag: string, defaultValue?: boolean) {\n const value = use(Bootstrap)?.featureFlags?.[flag];\n const bootstrapped = value === undefined ? undefined : !!value;\n return useFlags((posthog) => posthog.isFeatureEnabled(flag), bootstrapped) ?? defaultValue;\n}\n\n/** A flag's payload, read without recording an exposure. */\nexport function useFeatureFlagPayload(flag: string): JsonType {\n const bootstrapped = use(Bootstrap)?.featureFlagPayloads?.[flag];\n return useFlags(\n (posthog) => posthog.getFeatureFlagResult(flag, { send_event: false })?.payload,\n bootstrapped\n );\n}\n\n/** A flag's value, variant and payload together; `undefined` while it is unknown. */\nexport function useFeatureFlagResult(flag: string): FeatureFlagResult | undefined {\n const bootstrap = use(Bootstrap);\n const value = bootstrap?.featureFlags?.[flag];\n const bootstrapped: FeatureFlagResult | undefined =\n value === undefined\n ? undefined\n : {\n key: flag,\n enabled: typeof value === 'string' ? true : value,\n variant: typeof value === 'string' ? value : undefined,\n payload: bootstrap?.featureFlagPayloads?.[flag],\n };\n return useFlags((posthog) => posthog.getFeatureFlagResult(flag), bootstrapped);\n}\n\n/**\n * The keys of the flags: only those that are on while bootstrapped, every flag the library has\n * once loaded — as `posthog-js/react`'s does.\n */\nexport function useActiveFeatureFlags(): string[] {\n const flags = use(Bootstrap)?.featureFlags ?? {};\n const bootstrapped = Object.keys(flags).filter((key) => flags[key]);\n return useFlags((posthog) => posthog.featureFlags.getFlags(), bootstrapped);\n}\n\n/**\n * `window.posthog`, as `posthog-js/react`'s `usePostHog`: the snippet's stub until the library\n * loads — which queues the calls returning nothing (`capture`, `identify`, …) — then the library,\n * re-rendering when it replaces the stub; `undefined` on the server. Use the value of the latest\n * render rather than one kept from before (e.g. in a ref): calls on a stub kept past the load are\n * lost. A method that returns a value returns `undefined` on the stub; read flags with the hooks.\n *\n * The re-render comes from the flags loading, as the library answers the stub's queued\n * `onFeatureFlags`: with feature flags disabled it stays on the stub until something else\n * re-renders.\n */\nexport function usePostHog(): PostHog | undefined {\n return useSyncExternalStore(subscribe, getPosthog, () => undefined);\n}\n"],"mappings":";;;AAWA,MAAM,aAAa,CAAC;AAEpB,MAAM,YAAY,cAA2C,KAAA,CAAS;;;;;;;;;AAUtE,SAAgB,gBAAgB,EAC9B,WACA,YAIC;CACD,OAAO,cAAc,UAAU,UAAU,EAAE,OAAO,UAAU,GAAG,QAAQ;AACzE;;AAGA,SAAS,UAAU,UAAkC;CAEnD,OAD8C,WAAW,CAAC,EAAE,eAAe,QAAQ,KAC7D;AACxB;;;;;;AAeA,SAAS,SAAY,MAAqC,cAAoB;CAC5E,MAAM,QAAQ,OAA+C,KAAA,CAAS;CACtE,MAAM,UAAU,UAAa;EAE3B,MAAM,OAA2B,KAAK,UAAU,KAAK;EACrD,IAAI,CAAC,MAAM,WAAW,MAAM,QAAQ,SAAS,MAAM,MAAM,UAAU;GAAE;GAAM;EAAM;EACjF,OAAO,MAAM,QAAQ;CACvB;CACA,OAAO,qBACL,iBACM;EACJ,MAAM,UAAU,iBAAiB;EAGjC,OAAO,OAAO,SAAS,aAAa,iBAAiB,KAAK,OAAO,IAAI,YAAY;CACnF,SACM,OAAO,YAAY,CAC3B;AACF;;AAeA,SAAgB,yBAAyB,MAA4C;CACnF,MAAM,eAAe,IAAI,SAAS,CAAC,EAAE,eAAe;CACpD,OAAO,UAAU,YAAY,QAAQ,eAAe,IAAI,GAAG,YAAY;AACzE;AAKA,SAAgB,sBAAsB,MAAc,cAAwB;CAC1E,MAAM,QAAQ,IAAI,SAAS,CAAC,EAAE,eAAe;CAE7C,OAAO,UAAU,YAAY,QAAQ,iBAAiB,IAAI,GADrC,UAAU,KAAA,IAAY,KAAA,IAAY,CAAC,CAAC,KACgB,KAAK;AAChF;;AAGA,SAAgB,sBAAsB,MAAwB;CAC5D,MAAM,eAAe,IAAI,SAAS,CAAC,EAAE,sBAAsB;CAC3D,OAAO,UACJ,YAAY,QAAQ,qBAAqB,MAAM,EAAE,YAAY,MAAM,CAAC,CAAC,EAAE,SACxE,YACF;AACF;;AAGA,SAAgB,qBAAqB,MAA6C;CAChF,MAAM,YAAY,IAAI,SAAS;CAC/B,MAAM,QAAQ,WAAW,eAAe;CAUxC,OAAO,UAAU,YAAY,QAAQ,qBAAqB,IAAI,GAR5D,UAAU,KAAA,IACN,KAAA,IACA;EACE,KAAK;EACL,SAAS,OAAO,UAAU,WAAW,OAAO;EAC5C,SAAS,OAAO,UAAU,WAAW,QAAQ,KAAA;EAC7C,SAAS,WAAW,sBAAsB;CAC5C,CACuE;AAC/E;;;;;AAMA,SAAgB,wBAAkC;CAChD,MAAM,QAAQ,IAAI,SAAS,CAAC,EAAE,gBAAgB,CAAC;CAE/C,OAAO,UAAU,YAAY,QAAQ,aAAa,SAAS,GADtC,OAAO,KAAK,KAAK,CAAC,CAAC,QAAQ,QAAQ,MAAM,IACW,CAAC;AAC5E;;;;;;;;;;;;AAaA,SAAgB,aAAkC;CAChD,OAAO,qBAAqB,WAAW,kBAAkB,KAAA,CAAS;AACpE"}
@@ -161,22 +161,24 @@ const propertiesSchema = (0, zod_mini.optional)((0, zod_mini.pipe)((0, zod_mini.
161
161
  items
162
162
  ])), (0, zod_mini.transform)(takeProperties)));
163
163
  /**
164
- * How far an event's time may be from the server's before the client clock it was stamped with is
165
- * taken as wrong. A batch legitimately arrives late — a tab frozen in the background, a
164
+ * How far behind the server's an event's time may be before the client clock it was stamped with
165
+ * is taken as wrong. A batch legitimately arrives late — a tab frozen in the background, a
166
166
  * session_start held back after a failed batch — by hours, not days; a phone set to another year
167
- * writes its sessions into that year.
167
+ * writes its sessions into that year. Ahead of the server's is wrong by any amount: an event
168
+ * cannot have happened after it arrived, and a clock a few minutes fast is common enough that the
169
+ * conversions APIs, which reject a future event, turned its events away by the hundred.
168
170
  */
169
171
  const MAX_CLOCK_SKEW = 864e5;
170
172
  /**
171
173
  * Puts the events stamped by a wrong client clock onto the server's, where they are parsed. Only
172
- * the events outside `MAX_CLOCK_SKEW` move, so one bad event cannot drag the rest of its batch
173
- * along: they move together by their own latest one — the wrong clock at sending — keeping their
174
- * order and spacing, and one still out after that (a batch mixing two wrong clocks) is on no clock
174
+ * the events ahead of the server, or further behind it than `MAX_CLOCK_SKEW`, move, so one bad
175
+ * event cannot drag the rest of its batch along: they move together by their own latest one — the
176
+ * wrong clock at sending — keeping their order and spacing, and one still out after that (a batch mixing two wrong clocks) is on no clock
175
177
  * at all and takes the server's time. Corrected rather than rejected, for the same reason values
176
178
  * are truncated: a wrong clock should cost the event its time, not the batch its events.
177
179
  */
178
180
  function alignClock(events, now = Date.now()) {
179
- const within = (time) => Math.abs(now - time) <= MAX_CLOCK_SKEW;
181
+ const within = (time) => time <= now && now - time <= MAX_CLOCK_SKEW;
180
182
  const times = events.map((event) => Date.parse(event.timestamp));
181
183
  const wrong = times.filter((time) => !within(time));
182
184
  if (wrong.length === 0) return events;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["pipe","string","transform","array","record","union","number","boolean","_null","object","optional","trim","minLength","maxLength","regex","uuid","_enum","iso","toLowerCase","email","e164","toUpperCase","url"],"sources":["../../src/schema/index.ts"],"sourcesContent":["import {\n enum as _enum,\n null as _null,\n array,\n boolean,\n e164,\n email,\n iso,\n maxLength,\n minLength,\n number,\n object,\n optional,\n pipe,\n record,\n regex,\n string,\n toLowerCase,\n toUpperCase,\n transform,\n trim,\n union,\n url,\n uuid,\n type z,\n} from 'zod/mini';\nimport type { Environment, Platform } from '../track/types';\n\nconst MAX_KEY_LENGTH = 128;\nconst MAX_VALUE_LENGTH = 512;\nconst MAX_PROPERTIES = 64;\n\n/**\n * Truncated rather than rejected. These schemas validate a whole batch at once, so refusing one\n * oversized value costs every event that traveled with it — and the values that overrun are the\n * ones derived from the page (a link's text, a URL carrying a long query), which no client can\n * bound in advance. A shortened value is worth more than a lost batch.\n */\nconst propertyText = pipe(\n string(),\n transform((value) => value.slice(0, MAX_VALUE_LENGTH))\n);\n\n/**\n * Tags are truncated for the same reason property values are, and they are stored more than once\n * (on the event, the session and the visitor), so an unbounded one costs several times over.\n * 1024 sits just above what GA4 itself keeps (1000 characters of page_location, 420 of\n * page_referrer, 300 of page_title). Real tags stay under ~500 characters; the rare longer ones\n * are page_referrer values from search and ad redirect URLs, where the kept prefix — host and\n * path — is the part that matters.\n */\nconst MAX_TAG_LENGTH = 1024;\n\nconst tagText = pipe(\n string(),\n transform((value) => value.slice(0, MAX_TAG_LENGTH))\n);\n\n/**\n * Keys are written by hand in instrumentation code, so an unusable one is a mistake in the host\n * rather than something the visitor typed. It is still dropped rather than rejected, for the same\n * reason: the mistake should cost that property, not the batch it happens to be in. Truncating a\n * key is not an option — two long keys would silently become one field.\n *\n * The key schema below is deliberately permissive so that this transform is reached at all; the\n * trimming it used to do happens here instead. `MAX_PROPERTIES` keeps the first N in insertion\n * order.\n */\nfunction takeProperties<T>(data: Record<string, T>): Record<string, T> {\n const result: Record<string, T> = {};\n let count = 0;\n for (const [rawKey, value] of Object.entries(data)) {\n if (count >= MAX_PROPERTIES) break;\n const key = rawKey.trim();\n if (!key || key.length > MAX_KEY_LENGTH) continue;\n result[key] = value;\n count++;\n }\n return result;\n}\n\n/**\n * Capped at GA4's own item-list limit, and truncated rather than rejected like every other\n * property limit here: an unbounded array is the one field a caller could still blow a batch\n * up with after the value and key limits.\n */\nconst MAX_ITEMS = 200;\n\nconst items = pipe(\n array(\n pipe(\n record(string(), union([propertyText, number(), boolean(), _null()])),\n transform(takeProperties)\n )\n ),\n transform((list) => list.slice(0, MAX_ITEMS))\n);\n\nexport const ALL_PLATFORMS = [\n 'ios',\n 'android',\n 'web',\n 'macos',\n 'windows',\n 'linux',\n 'unknown',\n] as const satisfies Platform[];\n\nexport const ALL_ENVIRONMENTS = ['development', 'production'] as const satisfies Environment[];\n\nexport const tagsSchema = object({\n os: optional(tagText),\n os_name: optional(tagText),\n os_version: optional(tagText),\n browser: optional(tagText),\n browser_name: optional(tagText),\n browser_version: optional(tagText),\n device: optional(tagText),\n device_id: optional(string().check(trim(), minLength(1), maxLength(36))),\n device_type: optional(tagText),\n device_vendor: optional(tagText),\n device_pixel_ratio: optional(number()),\n screen_width: optional(number()),\n screen_height: optional(number()),\n screen_resolution: optional(\n pipe(\n string().check(regex(/^\\d+x\\d+$/)),\n transform((v) => v as `${number}x${number}`)\n )\n ),\n webdriver: optional(boolean()),\n release: optional(tagText),\n language: optional(tagText),\n time_zone: optional(tagText),\n page_location: optional(tagText),\n page_referrer: optional(tagText),\n page_title: optional(tagText),\n page_load_id: optional(tagText),\n /**\n * @deprecated Renamed to `page_location` in 7.0.0. Accepted so that events from clients\n * still on an older SDK are not stripped of their page URL at this boundary — a browser\n * bundle stays cached long after a backend deploys. Remove once those clients are gone;\n * `pageLocation` in `server/page-location.ts` is the only reader.\n */\n // oxlint-disable-next-line typescript/no-deprecated -- Legacy input from pre-7.0 clients must survive validation.\n source_url: optional(tagText),\n // app info\n advertising_id: optional(tagText),\n install_referrer: optional(tagText),\n // Ad click ids (URL parameters) and ad platform cookies (underscore names); see AdvertisingInfo.\n // Meta Ads\n fbclid: optional(tagText),\n ad_id: optional(tagText),\n ad_name: optional(tagText),\n adset_id: optional(tagText),\n adset_name: optional(tagText),\n campaign_id: optional(tagText),\n campaign_name: optional(tagText),\n placement: optional(tagText),\n _fbc: optional(tagText),\n _fbp: optional(tagText),\n /**\n * @deprecated `fbc` / `fbp` / `rdt_uuid` were renamed to `_fbc` / `_fbp` / `_rdt_uuid` in 9.0.0.\n * Accepted so that conversions from clients still on an older SDK keep their match keys; the\n * senders read them only as a fallback (`server/click-ids.ts`). Remove once those clients are\n * gone.\n */\n // oxlint-disable-next-line typescript/no-deprecated -- Legacy pre-9.0 click-id fields must survive validation.\n fbc: optional(tagText),\n fbp: optional(tagText),\n rdt_uuid: optional(tagText),\n // Google Ads\n gclid: optional(tagText),\n gclsrc: optional(tagText),\n gad_source: optional(tagText),\n gad_campaignid: optional(tagText),\n network: optional(tagText),\n match_type: optional(tagText),\n wbraid: optional(tagText),\n gbraid: optional(tagText),\n dclid: optional(tagText),\n _gcl_aw: optional(tagText),\n _gcl_gb: optional(tagText),\n // Microsoft Ads\n msclkid: optional(tagText),\n _uetmsclkid: optional(tagText),\n // Reddit Ads\n rdt_cid: optional(tagText),\n _rdt_cid: optional(tagText),\n _rdt_uuid: optional(tagText),\n // LinkedIn Ads\n li_fat_id: optional(tagText),\n _li_fat_id: optional(tagText),\n // OpenAI Ads\n oppref: optional(tagText),\n __oppref: optional(tagText),\n __obref: optional(tagText),\n // other click ids\n ko_click_id: optional(tagText),\n ScCid: optional(tagText),\n ttclid: optional(tagText),\n twclid: optional(tagText),\n yclid: optional(tagText),\n epik: optional(tagText),\n // utm params\n utm_source: optional(tagText),\n utm_medium: optional(tagText),\n utm_campaign: optional(tagText),\n utm_term: optional(tagText),\n utm_content: optional(tagText),\n utm_id: optional(tagText),\n utm_source_platform: optional(tagText),\n utm_creative_format: optional(tagText),\n utm_marketing_tactic: optional(tagText),\n});\n\nexport const propertiesSchema = optional(\n pipe(\n record(string(), union([propertyText, number(), boolean(), _null(), items])),\n transform(takeProperties)\n )\n);\n\n/**\n * How far an event's time may be from the server's before the client clock it was stamped with is\n * taken as wrong. A batch legitimately arrives late — a tab frozen in the background, a\n * session_start held back after a failed batch — by hours, not days; a phone set to another year\n * writes its sessions into that year.\n */\nconst MAX_CLOCK_SKEW = 24 * 60 * 60 * 1000;\n\n/**\n * Puts the events stamped by a wrong client clock onto the server's, where they are parsed. Only\n * the events outside `MAX_CLOCK_SKEW` move, so one bad event cannot drag the rest of its batch\n * along: they move together by their own latest one — the wrong clock at sending — keeping their\n * order and spacing, and one still out after that (a batch mixing two wrong clocks) is on no clock\n * at all and takes the server's time. Corrected rather than rejected, for the same reason values\n * are truncated: a wrong clock should cost the event its time, not the batch its events.\n */\nfunction alignClock<T extends { timestamp: string }>(events: T[], now = Date.now()): T[] {\n const within = (time: number) => Math.abs(now - time) <= MAX_CLOCK_SKEW;\n const times = events.map((event) => Date.parse(event.timestamp));\n const wrong = times.filter((time) => !within(time));\n if (wrong.length === 0) return events;\n const offset = now - Math.max(...wrong);\n return events.map((event, i) => {\n if (within(times[i])) return event;\n const shifted = times[i] + offset;\n return { ...event, timestamp: new Date(within(shifted) ? shifted : now).toISOString() };\n });\n}\n\nexport const createTrackEventSchema = pipe(\n array(\n object({\n /**\n * The event's id, generated by the client when the event was tracked (12.1) and given to\n * the browser pixels as their deduplication id. Store the event under it with\n * `on conflict (id) do nothing`: a batch retried after the server committed it then\n * stores nothing twice. Optional for clients before 12.1, which send none — generate one\n * on the server for those.\n */\n id: optional(uuid({ version: 'v7' })),\n name: string().check(trim(), minLength(1), maxLength(64)),\n // Generated by the SDK, like `id` (`visitorId()`, `Session`): uuidv7 as well, so the\n // constraint is checked here once and the server need not check it again.\n visitor_id: uuid({ version: 'v7' }),\n session_id: uuid({ version: 'v7' }),\n platform: _enum(ALL_PLATFORMS),\n environment: _enum(ALL_ENVIRONMENTS),\n timestamp: iso.datetime(),\n tags: tagsSchema,\n properties: propertiesSchema,\n })\n ).check(minLength(1), maxLength(100)),\n transform((events) => alignClock(events))\n);\n\n/**\n * `POST /visitors`, what clients before 11.0 create their visitor with; 11.0 generates the id\n * itself and the server creates the visitor from its first events (README, \"Visitors\").\n * Kept for servers that still serve older clients.\n */\nexport const createVisitorSchema = object({\n device_id: string().check(trim(), minLength(1), maxLength(36)),\n platform: _enum(ALL_PLATFORMS),\n environment: _enum(ALL_ENVIRONMENTS),\n tags: tagsSchema,\n});\n\nconst emailValue = pipe(string().check(trim(), toLowerCase(), maxLength(320)), email());\n\n/** E.164: a plus sign (+) prefix, country code, then digits only, no dashes/parens/spaces. */\nconst phoneValue = pipe(string().check(trim()), e164());\n\nconst addressValue = object({\n first_name: optional(string().check(trim(), maxLength(128))),\n last_name: optional(string().check(trim(), maxLength(128))),\n street: optional(string().check(trim(), maxLength(256))),\n city: optional(string().check(trim(), maxLength(128))),\n /** User province, state, or region. Example: `Hampshire` */\n region: optional(string().check(trim(), maxLength(128))),\n postal_code: optional(string().check(trim(), maxLength(32))),\n /** 2-letter country code, per the ISO 3166-1 alpha-2 standard. Example: `UK` */\n country: optional(string().check(trim(), toUpperCase(), regex(/^[A-Z]{2}$/))),\n});\n\n/**\n * User-provided data (UPD) used for enhanced conversions, Customer Match, and demographics.\n * Values are sent unhashed; Google normalizes and hashes them before they reach its servers.\n *\n * Multiple values may be sent to increase the match rate: up to 3 emails, 3 phone numbers, and\n * 2 addresses.\n *\n * @see https://support.google.com/analytics/answer/14078702\n * @see https://support.google.com/google-ads/answer/13258081\n */\nexport const userProvidedDataSchema = object({\n email: optional(union([emailValue, array(emailValue).check(minLength(1), maxLength(3))])),\n phone_number: optional(union([phoneValue, array(phoneValue).check(minLength(1), maxLength(3))])),\n address: optional(union([addressValue, array(addressValue).check(minLength(1), maxLength(2))])),\n});\n\nexport const updateVisitorSchema = object({\n user_id: optional(uuid()),\n user_data: optional(userProvidedDataSchema),\n /**\n * Sent by clients before 11.1, which PATCHed their tags on every page load. From 11.1 the\n * server refreshes `visitor.tags` from each `session_start` — the moment the visit arrives —\n * and `identify` sends none: at sign-in the page is no longer where the visit came in.\n */\n tags: optional(tagsSchema),\n});\n\nexport const createFeedbackSchema = object({\n name: string().check(minLength(1), maxLength(256)),\n // Trimmed and lower-cased like every other email the SDK accepts, so a host stores the\n // normalized form without wrapping the schema.\n email: emailValue,\n message: string().check(minLength(1), maxLength(65536)),\n /**\n * The Cloudflare Turnstile token the host verifies before storing the feedback (the same field\n * `@shware/security`'s email-code request carries). Required: without it `POST /feedback` is an\n * open free-text write that only a rate limit protects. Single-use: Turnstile spends the token\n * at verification, so the caller resets the widget after every submit, success or failure.\n */\n turnstileToken: string().check(minLength(1), maxLength(2048)),\n});\n\nconst noEmptyString = pipe(\n string().check(maxLength(256)),\n transform((v) => (v ? v : undefined))\n);\n\n/**\n * The schema for creating a link.\n * @see https://support.google.com/analytics/answer/10917952\n * */\nexport const createLinkSchema = object({\n /** The URL that the user is redirected to. */\n url: url().check(minLength(1), maxLength(1024)), // required\n\n /**\n * Campaign ID. Used to identify a specific campaign or promotion. This is a required key for GA4\n * data import. Use the same IDs that you use when uploading campaign cost data.\n */\n utm_id: optional(noEmptyString),\n\n /** Referrer, for example: google, newsletter4, billboard */\n utm_source: string().check(minLength(1), maxLength(256)), // required\n\n /** Marketing medium, for example: cpc, banner, email */\n utm_medium: string().check(minLength(1), maxLength(256)), // required\n\n /** Product, slogan, promo code, for example, spring_sale */\n utm_campaign: string().check(minLength(1), maxLength(256)), // required\n\n /** Paid keyword */\n utm_term: optional(noEmptyString),\n\n /**\n * Use to differentiate creatives. For example, if you have two call-to-action links within the\n * same email message, you can use utm_content and set different values for each so you can tell\n * which version is more effective.\n */\n utm_content: optional(noEmptyString),\n\n /**\n * The platform responsible for directing traffic to a given Analytics property (such as a buying\n * platform that sets budgets and targeting criteria or a platform that manages organic traffic\n * data). For example, Search Ads 360 or Display & Video 360.\n */\n utm_source_platform: optional(noEmptyString),\n\n /**\n * Type of creative, for example, display, native, video, search, utm_creative_format is not\n * currently reported in Google Analytics 4 properties.\n */\n utm_creative_format: optional(noEmptyString),\n\n /**\n * Targeting criteria applied to a campaign, for example, remarketing, prospecting,\n * utm_marketing_tactic is not currently reported in Google Analytics 4 properties.\n * */\n utm_marketing_tactic: optional(noEmptyString),\n});\n\nexport type CreateTrackEventDTO = z.output<typeof createTrackEventSchema>;\nexport type CreateFeedbackDTO = z.output<typeof createFeedbackSchema>;\nexport type CreateLinkDTO = z.output<typeof createLinkSchema>;\nexport type CreateVisitorDTO = z.output<typeof createVisitorSchema>;\nexport type UserProvidedDataDTO = z.output<typeof userProvidedDataSchema>;\nexport type UpdateVisitorD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AC,IAAA,GAAGC,SAAAA,UAAAA,CAAU,GAAG,CAAC;;CAGvD,aAAA,GAAYZ,SAAAA,OAAAA,CAAO,CAAC,CAAC,OAAA,GAAMW,SAAAA,UAAAA,CAAU,CAAC,IAAA,GAAGC,SAAAA,UAAAA,CAAU,GAAG,CAAC;;CAGvD,eAAA,GAAcZ,SAAAA,OAAAA,CAAO,CAAC,CAAC,OAAA,GAAMW,SAAAA,UAAAA,CAAU,CAAC,IAAA,GAAGC,SAAAA,UAAAA,CAAU,GAAG,CAAC;;CAGzD,WAAA,GAAUH,SAAAA,SAAAA,CAAS,aAAa;;;;;;CAOhC,cAAA,GAAaA,SAAAA,SAAAA,CAAS,aAAa;;;;;;CAOnC,sBAAA,GAAqBA,SAAAA,SAAAA,CAAS,aAAa;;;;;CAM3C,sBAAA,GAAqBA,SAAAA,SAAAA,CAAS,aAAa;;;;;CAM3C,uBAAA,GAAsBA,SAAAA,SAAAA,CAAS,aAAa;AAC9C,CAAC"}
1
+ {"version":3,"file":"index.cjs","names":["pipe","string","transform","array","record","union","number","boolean","_null","object","optional","trim","minLength","maxLength","regex","uuid","_enum","iso","toLowerCase","email","e164","toUpperCase","url"],"sources":["../../src/schema/index.ts"],"sourcesContent":["import {\n enum as _enum,\n null as _null,\n array,\n boolean,\n e164,\n email,\n iso,\n maxLength,\n minLength,\n number,\n object,\n optional,\n pipe,\n record,\n regex,\n string,\n toLowerCase,\n toUpperCase,\n transform,\n trim,\n union,\n url,\n uuid,\n type z,\n} from 'zod/mini';\nimport type { Environment, Platform } from '../track/types';\n\nconst MAX_KEY_LENGTH = 128;\nconst MAX_VALUE_LENGTH = 512;\nconst MAX_PROPERTIES = 64;\n\n/**\n * Truncated rather than rejected. These schemas validate a whole batch at once, so refusing one\n * oversized value costs every event that traveled with it — and the values that overrun are the\n * ones derived from the page (a link's text, a URL carrying a long query), which no client can\n * bound in advance. A shortened value is worth more than a lost batch.\n */\nconst propertyText = pipe(\n string(),\n transform((value) => value.slice(0, MAX_VALUE_LENGTH))\n);\n\n/**\n * Tags are truncated for the same reason property values are, and they are stored more than once\n * (on the event, the session and the visitor), so an unbounded one costs several times over.\n * 1024 sits just above what GA4 itself keeps (1000 characters of page_location, 420 of\n * page_referrer, 300 of page_title). Real tags stay under ~500 characters; the rare longer ones\n * are page_referrer values from search and ad redirect URLs, where the kept prefix — host and\n * path — is the part that matters.\n */\nconst MAX_TAG_LENGTH = 1024;\n\nconst tagText = pipe(\n string(),\n transform((value) => value.slice(0, MAX_TAG_LENGTH))\n);\n\n/**\n * Keys are written by hand in instrumentation code, so an unusable one is a mistake in the host\n * rather than something the visitor typed. It is still dropped rather than rejected, for the same\n * reason: the mistake should cost that property, not the batch it happens to be in. Truncating a\n * key is not an option — two long keys would silently become one field.\n *\n * The key schema below is deliberately permissive so that this transform is reached at all; the\n * trimming it used to do happens here instead. `MAX_PROPERTIES` keeps the first N in insertion\n * order.\n */\nfunction takeProperties<T>(data: Record<string, T>): Record<string, T> {\n const result: Record<string, T> = {};\n let count = 0;\n for (const [rawKey, value] of Object.entries(data)) {\n if (count >= MAX_PROPERTIES) break;\n const key = rawKey.trim();\n if (!key || key.length > MAX_KEY_LENGTH) continue;\n result[key] = value;\n count++;\n }\n return result;\n}\n\n/**\n * Capped at GA4's own item-list limit, and truncated rather than rejected like every other\n * property limit here: an unbounded array is the one field a caller could still blow a batch\n * up with after the value and key limits.\n */\nconst MAX_ITEMS = 200;\n\nconst items = pipe(\n array(\n pipe(\n record(string(), union([propertyText, number(), boolean(), _null()])),\n transform(takeProperties)\n )\n ),\n transform((list) => list.slice(0, MAX_ITEMS))\n);\n\nexport const ALL_PLATFORMS = [\n 'ios',\n 'android',\n 'web',\n 'macos',\n 'windows',\n 'linux',\n 'unknown',\n] as const satisfies Platform[];\n\nexport const ALL_ENVIRONMENTS = ['development', 'production'] as const satisfies Environment[];\n\nexport const tagsSchema = object({\n os: optional(tagText),\n os_name: optional(tagText),\n os_version: optional(tagText),\n browser: optional(tagText),\n browser_name: optional(tagText),\n browser_version: optional(tagText),\n device: optional(tagText),\n device_id: optional(string().check(trim(), minLength(1), maxLength(36))),\n device_type: optional(tagText),\n device_vendor: optional(tagText),\n device_pixel_ratio: optional(number()),\n screen_width: optional(number()),\n screen_height: optional(number()),\n screen_resolution: optional(\n pipe(\n string().check(regex(/^\\d+x\\d+$/)),\n transform((v) => v as `${number}x${number}`)\n )\n ),\n webdriver: optional(boolean()),\n release: optional(tagText),\n language: optional(tagText),\n time_zone: optional(tagText),\n page_location: optional(tagText),\n page_referrer: optional(tagText),\n page_title: optional(tagText),\n page_load_id: optional(tagText),\n /**\n * @deprecated Renamed to `page_location` in 7.0.0. Accepted so that events from clients\n * still on an older SDK are not stripped of their page URL at this boundary — a browser\n * bundle stays cached long after a backend deploys. Remove once those clients are gone;\n * `pageLocation` in `server/page-location.ts` is the only reader.\n */\n // oxlint-disable-next-line typescript/no-deprecated -- Legacy input from pre-7.0 clients must survive validation.\n source_url: optional(tagText),\n // app info\n advertising_id: optional(tagText),\n install_referrer: optional(tagText),\n // Ad click ids (URL parameters) and ad platform cookies (underscore names); see AdvertisingInfo.\n // Meta Ads\n fbclid: optional(tagText),\n ad_id: optional(tagText),\n ad_name: optional(tagText),\n adset_id: optional(tagText),\n adset_name: optional(tagText),\n campaign_id: optional(tagText),\n campaign_name: optional(tagText),\n placement: optional(tagText),\n _fbc: optional(tagText),\n _fbp: optional(tagText),\n /**\n * @deprecated `fbc` / `fbp` / `rdt_uuid` were renamed to `_fbc` / `_fbp` / `_rdt_uuid` in 9.0.0.\n * Accepted so that conversions from clients still on an older SDK keep their match keys; the\n * senders read them only as a fallback (`server/click-ids.ts`). Remove once those clients are\n * gone.\n */\n // oxlint-disable-next-line typescript/no-deprecated -- Legacy pre-9.0 click-id fields must survive validation.\n fbc: optional(tagText),\n fbp: optional(tagText),\n rdt_uuid: optional(tagText),\n // Google Ads\n gclid: optional(tagText),\n gclsrc: optional(tagText),\n gad_source: optional(tagText),\n gad_campaignid: optional(tagText),\n network: optional(tagText),\n match_type: optional(tagText),\n wbraid: optional(tagText),\n gbraid: optional(tagText),\n dclid: optional(tagText),\n _gcl_aw: optional(tagText),\n _gcl_gb: optional(tagText),\n // Microsoft Ads\n msclkid: optional(tagText),\n _uetmsclkid: optional(tagText),\n // Reddit Ads\n rdt_cid: optional(tagText),\n _rdt_cid: optional(tagText),\n _rdt_uuid: optional(tagText),\n // LinkedIn Ads\n li_fat_id: optional(tagText),\n _li_fat_id: optional(tagText),\n // OpenAI Ads\n oppref: optional(tagText),\n __oppref: optional(tagText),\n __obref: optional(tagText),\n // other click ids\n ko_click_id: optional(tagText),\n ScCid: optional(tagText),\n ttclid: optional(tagText),\n twclid: optional(tagText),\n yclid: optional(tagText),\n epik: optional(tagText),\n // utm params\n utm_source: optional(tagText),\n utm_medium: optional(tagText),\n utm_campaign: optional(tagText),\n utm_term: optional(tagText),\n utm_content: optional(tagText),\n utm_id: optional(tagText),\n utm_source_platform: optional(tagText),\n utm_creative_format: optional(tagText),\n utm_marketing_tactic: optional(tagText),\n});\n\nexport const propertiesSchema = optional(\n pipe(\n record(string(), union([propertyText, number(), boolean(), _null(), items])),\n transform(takeProperties)\n )\n);\n\n/**\n * How far behind the server's an event's time may be before the client clock it was stamped with\n * is taken as wrong. A batch legitimately arrives late — a tab frozen in the background, a\n * session_start held back after a failed batch — by hours, not days; a phone set to another year\n * writes its sessions into that year. Ahead of the server's is wrong by any amount: an event\n * cannot have happened after it arrived, and a clock a few minutes fast is common enough that the\n * conversions APIs, which reject a future event, turned its events away by the hundred.\n */\nconst MAX_CLOCK_SKEW = 24 * 60 * 60 * 1000;\n\n/**\n * Puts the events stamped by a wrong client clock onto the server's, where they are parsed. Only\n * the events ahead of the server, or further behind it than `MAX_CLOCK_SKEW`, move, so one bad\n * event cannot drag the rest of its batch along: they move together by their own latest one — the\n * wrong clock at sending — keeping their order and spacing, and one still out after that (a batch mixing two wrong clocks) is on no clock\n * at all and takes the server's time. Corrected rather than rejected, for the same reason values\n * are truncated: a wrong clock should cost the event its time, not the batch its events.\n */\nfunction alignClock<T extends { timestamp: string }>(events: T[], now = Date.now()): T[] {\n const within = (time: number) => time <= now && now - time <= MAX_CLOCK_SKEW;\n const times = events.map((event) => Date.parse(event.timestamp));\n const wrong = times.filter((time) => !within(time));\n if (wrong.length === 0) return events;\n const offset = now - Math.max(...wrong);\n return events.map((event, i) => {\n if (within(times[i])) return event;\n const shifted = times[i] + offset;\n return { ...event, timestamp: new Date(within(shifted) ? shifted : now).toISOString() };\n });\n}\n\nexport const createTrackEventSchema = pipe(\n array(\n object({\n /**\n * The event's id, generated by the client when the event was tracked (12.1) and given to\n * the browser pixels as their deduplication id. Store the event under it with\n * `on conflict (id) do nothing`: a batch retried after the server committed it then\n * stores nothing twice. Optional for clients before 12.1, which send none — generate one\n * on the server for those.\n */\n id: optional(uuid({ version: 'v7' })),\n name: string().check(trim(), minLength(1), maxLength(64)),\n // Generated by the SDK, like `id` (`visitorId()`, `Session`): uuidv7 as well, so the\n // constraint is checked here once and the server need not check it again.\n visitor_id: uuid({ version: 'v7' }),\n session_id: uuid({ version: 'v7' }),\n platform: _enum(ALL_PLATFORMS),\n environment: _enum(ALL_ENVIRONMENTS),\n timestamp: iso.datetime(),\n tags: tagsSchema,\n properties: propertiesSchema,\n })\n ).check(minLength(1), maxLength(100)),\n transform((events) => alignClock(events))\n);\n\n/**\n * `POST /visitors`, what clients before 11.0 create their visitor with; 11.0 generates the id\n * itself and the server creates the visitor from its first events (README, \"Visitors\").\n * Kept for servers that still serve older clients.\n */\nexport const createVisitorSchema = object({\n device_id: string().check(trim(), minLength(1), maxLength(36)),\n platform: _enum(ALL_PLATFORMS),\n environment: _enum(ALL_ENVIRONMENTS),\n tags: tagsSchema,\n});\n\nconst emailValue = pipe(string().check(trim(), toLowerCase(), maxLength(320)), email());\n\n/** E.164: a plus sign (+) prefix, country code, then digits only, no dashes/parens/spaces. */\nconst phoneValue = pipe(string().check(trim()), e164());\n\nconst addressValue = object({\n first_name: optional(string().check(trim(), maxLength(128))),\n last_name: optional(string().check(trim(), maxLength(128))),\n street: optional(string().check(trim(), maxLength(256))),\n city: optional(string().check(trim(), maxLength(128))),\n /** User province, state, or region. Example: `Hampshire` */\n region: optional(string().check(trim(), maxLength(128))),\n postal_code: optional(string().check(trim(), maxLength(32))),\n /** 2-letter country code, per the ISO 3166-1 alpha-2 standard. Example: `UK` */\n country: optional(string().check(trim(), toUpperCase(), regex(/^[A-Z]{2}$/))),\n});\n\n/**\n * User-provided data (UPD) used for enhanced conversions, Customer Match, and demographics.\n * Values are sent unhashed; Google normalizes and hashes them before they reach its servers.\n *\n * Multiple values may be sent to increase the match rate: up to 3 emails, 3 phone numbers, and\n * 2 addresses.\n *\n * @see https://support.google.com/analytics/answer/14078702\n * @see https://support.google.com/google-ads/answer/13258081\n */\nexport const userProvidedDataSchema = object({\n email: optional(union([emailValue, array(emailValue).check(minLength(1), maxLength(3))])),\n phone_number: optional(union([phoneValue, array(phoneValue).check(minLength(1), maxLength(3))])),\n address: optional(union([addressValue, array(addressValue).check(minLength(1), maxLength(2))])),\n});\n\nexport const updateVisitorSchema = object({\n user_id: optional(uuid()),\n user_data: optional(userProvidedDataSchema),\n /**\n * Sent by clients before 11.1, which PATCHed their tags on every page load. From 11.1 the\n * server refreshes `visitor.tags` from each `session_start` — the moment the visit arrives —\n * and `identify` sends none: at sign-in the page is no longer where the visit came in.\n */\n tags: optional(tagsSchema),\n});\n\nexport const createFeedbackSchema = object({\n name: string().check(minLength(1), maxLength(256)),\n // Trimmed and lower-cased like every other email the SDK accepts, so a host stores the\n // normalized form without wrapping the schema.\n email: emailValue,\n message: string().check(minLength(1), maxLength(65536)),\n /**\n * The Cloudflare Turnstile token the host verifies before storing the feedback (the same field\n * `@shware/security`'s email-code request carries). Required: without it `POST /feedback` is an\n * open free-text write that only a rate limit protects. Single-use: Turnstile spends the token\n * at verification, so the caller resets the widget after every submit, success or failure.\n */\n turnstileToken: string().check(minLength(1), maxLength(2048)),\n});\n\nconst noEmptyString = pipe(\n string().check(maxLength(256)),\n transform((v) => (v ? v : undefined))\n);\n\n/**\n * The schema for creating a link.\n * @see https://support.google.com/analytics/answer/10917952\n * */\nexport const createLinkSchema = object({\n /** The URL that the user is redirected to. */\n url: url().check(minLength(1), maxLength(1024)), // required\n\n /**\n * Campaign ID. Used to identify a specific campaign or promotion. This is a required key for GA4\n * data import. Use the same IDs that you use when uploading campaign cost data.\n */\n utm_id: optional(noEmptyString),\n\n /** Referrer, for example: google, newsletter4, billboard */\n utm_source: string().check(minLength(1), maxLength(256)), // required\n\n /** Marketing medium, for example: cpc, banner, email */\n utm_medium: string().check(minLength(1), maxLength(256)), // required\n\n /** Product, slogan, promo code, for example, spring_sale */\n utm_campaign: string().check(minLength(1), maxLength(256)), // required\n\n /** Paid keyword */\n utm_term: optional(noEmptyString),\n\n /**\n * Use to differentiate creatives. For example, if you have two call-to-action links within the\n * same email message, you can use utm_content and set different values for each so you can tell\n * which version is more effective.\n */\n utm_content: optional(noEmptyString),\n\n /**\n * The platform responsible for directing traffic to a given Analytics property (such as a buying\n * platform that sets budgets and targeting criteria or a platform that manages organic traffic\n * data). For example, Search Ads 360 or Display & Video 360.\n */\n utm_source_platform: optional(noEmptyString),\n\n /**\n * Type of creative, for example, display, native, video, search, utm_creative_format is not\n * currently reported in Google Analytics 4 properties.\n */\n utm_creative_format: optional(noEmptyString),\n\n /**\n * Targeting criteria applied to a campaign, for example, remarketing, prospecting,\n * utm_marketing_tactic is not currently reported in Google Analytics 4 properties.\n * */\n utm_marketing_tactic: optional(noEmptyString),\n});\n\nexport type CreateTrackEventDTO = z.output<typeof createTrackEventSchema>;\nexport type CreateFeedbackDTO = z.output<typeof createFeedbackSchema>;\nexport type CreateLinkDTO = z.output<typeof createLinkSchema>;\nexport type CreateVisitorDTO = z.output<typeof createVisitorSchema>;\nexport type UserProvidedDataDTO = z.output<typeof userProvidedDataSchema>;\nexport type UpdateVisitorDTO = z.output<typeof updateVisitorSchema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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBA+BtB,qBAAmB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAK9B,EAAA,KAAA;;;;;;;;;;;qBA6BW,wBAAsB,EAAA;;;;;;;;;;;;;;;;;;;;GAIjC,EAAA,KAAA;qBAEW,qBAAmB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAS9B,EAAA,KAAA;qBAEW,sBAAoB,EAAA;;;;;GAa/B,EAAA,KAAA;;;;;qBAWW,kBAAgB,EAAA;;;;;;;;;;;GA+C3B,EAAA,KAAA;YAEU,sBAAsB,EAAE,cAAc;YACtC,oBAAoB,EAAE,cAAc;YACpC,gBAAgB,EAAE,cAAc;YAChC,mBAAmB,EAAE,cAAc;YACnC,sBAAsB,EAAE,cAAc;YACtC,mBAAmB,EAAE,cAAc"}
@@ -160,22 +160,24 @@ const propertiesSchema = optional(pipe(record(string(), union([
160
160
  items
161
161
  ])), transform(takeProperties)));
162
162
  /**
163
- * How far an event's time may be from the server's before the client clock it was stamped with is
164
- * taken as wrong. A batch legitimately arrives late — a tab frozen in the background, a
163
+ * How far behind the server's an event's time may be before the client clock it was stamped with
164
+ * is taken as wrong. A batch legitimately arrives late — a tab frozen in the background, a
165
165
  * session_start held back after a failed batch — by hours, not days; a phone set to another year
166
- * writes its sessions into that year.
166
+ * writes its sessions into that year. Ahead of the server's is wrong by any amount: an event
167
+ * cannot have happened after it arrived, and a clock a few minutes fast is common enough that the
168
+ * conversions APIs, which reject a future event, turned its events away by the hundred.
167
169
  */
168
170
  const MAX_CLOCK_SKEW = 864e5;
169
171
  /**
170
172
  * Puts the events stamped by a wrong client clock onto the server's, where they are parsed. Only
171
- * the events outside `MAX_CLOCK_SKEW` move, so one bad event cannot drag the rest of its batch
172
- * along: they move together by their own latest one — the wrong clock at sending — keeping their
173
- * order and spacing, and one still out after that (a batch mixing two wrong clocks) is on no clock
173
+ * the events ahead of the server, or further behind it than `MAX_CLOCK_SKEW`, move, so one bad
174
+ * event cannot drag the rest of its batch along: they move together by their own latest one — the
175
+ * wrong clock at sending — keeping their order and spacing, and one still out after that (a batch mixing two wrong clocks) is on no clock
174
176
  * at all and takes the server's time. Corrected rather than rejected, for the same reason values
175
177
  * are truncated: a wrong clock should cost the event its time, not the batch its events.
176
178
  */
177
179
  function alignClock(events, now = Date.now()) {
178
- const within = (time) => Math.abs(now - time) <= MAX_CLOCK_SKEW;
180
+ const within = (time) => time <= now && now - time <= MAX_CLOCK_SKEW;
179
181
  const times = events.map((event) => Date.parse(event.timestamp));
180
182
  const wrong = times.filter((time) => !within(time));
181
183
  if (wrong.length === 0) return events;
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["_null","_enum"],"sources":["../../src/schema/index.ts"],"sourcesContent":["import {\n enum as _enum,\n null as _null,\n array,\n boolean,\n e164,\n email,\n iso,\n maxLength,\n minLength,\n number,\n object,\n optional,\n pipe,\n record,\n regex,\n string,\n toLowerCase,\n toUpperCase,\n transform,\n trim,\n union,\n url,\n uuid,\n type z,\n} from 'zod/mini';\nimport type { Environment, Platform } from '../track/types';\n\nconst MAX_KEY_LENGTH = 128;\nconst MAX_VALUE_LENGTH = 512;\nconst MAX_PROPERTIES = 64;\n\n/**\n * Truncated rather than rejected. These schemas validate a whole batch at once, so refusing one\n * oversized value costs every event that traveled with it — and the values that overrun are the\n * ones derived from the page (a link's text, a URL carrying a long query), which no client can\n * bound in advance. A shortened value is worth more than a lost batch.\n */\nconst propertyText = pipe(\n string(),\n transform((value) => value.slice(0, MAX_VALUE_LENGTH))\n);\n\n/**\n * Tags are truncated for the same reason property values are, and they are stored more than once\n * (on the event, the session and the visitor), so an unbounded one costs several times over.\n * 1024 sits just above what GA4 itself keeps (1000 characters of page_location, 420 of\n * page_referrer, 300 of page_title). Real tags stay under ~500 characters; the rare longer ones\n * are page_referrer values from search and ad redirect URLs, where the kept prefix — host and\n * path — is the part that matters.\n */\nconst MAX_TAG_LENGTH = 1024;\n\nconst tagText = pipe(\n string(),\n transform((value) => value.slice(0, MAX_TAG_LENGTH))\n);\n\n/**\n * Keys are written by hand in instrumentation code, so an unusable one is a mistake in the host\n * rather than something the visitor typed. It is still dropped rather than rejected, for the same\n * reason: the mistake should cost that property, not the batch it happens to be in. Truncating a\n * key is not an option — two long keys would silently become one field.\n *\n * The key schema below is deliberately permissive so that this transform is reached at all; the\n * trimming it used to do happens here instead. `MAX_PROPERTIES` keeps the first N in insertion\n * order.\n */\nfunction takeProperties<T>(data: Record<string, T>): Record<string, T> {\n const result: Record<string, T> = {};\n let count = 0;\n for (const [rawKey, value] of Object.entries(data)) {\n if (count >= MAX_PROPERTIES) break;\n const key = rawKey.trim();\n if (!key || key.length > MAX_KEY_LENGTH) continue;\n result[key] = value;\n count++;\n }\n return result;\n}\n\n/**\n * Capped at GA4's own item-list limit, and truncated rather than rejected like every other\n * property limit here: an unbounded array is the one field a caller could still blow a batch\n * up with after the value and key limits.\n */\nconst MAX_ITEMS = 200;\n\nconst items = pipe(\n array(\n pipe(\n record(string(), union([propertyText, number(), boolean(), _null()])),\n transform(takeProperties)\n )\n ),\n transform((list) => list.slice(0, MAX_ITEMS))\n);\n\nexport const ALL_PLATFORMS = [\n 'ios',\n 'android',\n 'web',\n 'macos',\n 'windows',\n 'linux',\n 'unknown',\n] as const satisfies Platform[];\n\nexport const ALL_ENVIRONMENTS = ['development', 'production'] as const satisfies Environment[];\n\nexport const tagsSchema = object({\n os: optional(tagText),\n os_name: optional(tagText),\n os_version: optional(tagText),\n browser: optional(tagText),\n browser_name: optional(tagText),\n browser_version: optional(tagText),\n device: optional(tagText),\n device_id: optional(string().check(trim(), minLength(1), maxLength(36))),\n device_type: optional(tagText),\n device_vendor: optional(tagText),\n device_pixel_ratio: optional(number()),\n screen_width: optional(number()),\n screen_height: optional(number()),\n screen_resolution: optional(\n pipe(\n string().check(regex(/^\\d+x\\d+$/)),\n transform((v) => v as `${number}x${number}`)\n )\n ),\n webdriver: optional(boolean()),\n release: optional(tagText),\n language: optional(tagText),\n time_zone: optional(tagText),\n page_location: optional(tagText),\n page_referrer: optional(tagText),\n page_title: optional(tagText),\n page_load_id: optional(tagText),\n /**\n * @deprecated Renamed to `page_location` in 7.0.0. Accepted so that events from clients\n * still on an older SDK are not stripped of their page URL at this boundary — a browser\n * bundle stays cached long after a backend deploys. Remove once those clients are gone;\n * `pageLocation` in `server/page-location.ts` is the only reader.\n */\n // oxlint-disable-next-line typescript/no-deprecated -- Legacy input from pre-7.0 clients must survive validation.\n source_url: optional(tagText),\n // app info\n advertising_id: optional(tagText),\n install_referrer: optional(tagText),\n // Ad click ids (URL parameters) and ad platform cookies (underscore names); see AdvertisingInfo.\n // Meta Ads\n fbclid: optional(tagText),\n ad_id: optional(tagText),\n ad_name: optional(tagText),\n adset_id: optional(tagText),\n adset_name: optional(tagText),\n campaign_id: optional(tagText),\n campaign_name: optional(tagText),\n placement: optional(tagText),\n _fbc: optional(tagText),\n _fbp: optional(tagText),\n /**\n * @deprecated `fbc` / `fbp` / `rdt_uuid` were renamed to `_fbc` / `_fbp` / `_rdt_uuid` in 9.0.0.\n * Accepted so that conversions from clients still on an older SDK keep their match keys; the\n * senders read them only as a fallback (`server/click-ids.ts`). Remove once those clients are\n * gone.\n */\n // oxlint-disable-next-line typescript/no-deprecated -- Legacy pre-9.0 click-id fields must survive validation.\n fbc: optional(tagText),\n fbp: optional(tagText),\n rdt_uuid: optional(tagText),\n // Google Ads\n gclid: optional(tagText),\n gclsrc: optional(tagText),\n gad_source: optional(tagText),\n gad_campaignid: optional(tagText),\n network: optional(tagText),\n match_type: optional(tagText),\n wbraid: optional(tagText),\n gbraid: optional(tagText),\n dclid: optional(tagText),\n _gcl_aw: optional(tagText),\n _gcl_gb: optional(tagText),\n // Microsoft Ads\n msclkid: optional(tagText),\n _uetmsclkid: optional(tagText),\n // Reddit Ads\n rdt_cid: optional(tagText),\n _rdt_cid: optional(tagText),\n _rdt_uuid: optional(tagText),\n // LinkedIn Ads\n li_fat_id: optional(tagText),\n _li_fat_id: optional(tagText),\n // OpenAI Ads\n oppref: optional(tagText),\n __oppref: optional(tagText),\n __obref: optional(tagText),\n // other click ids\n ko_click_id: optional(tagText),\n ScCid: optional(tagText),\n ttclid: optional(tagText),\n twclid: optional(tagText),\n yclid: optional(tagText),\n epik: optional(tagText),\n // utm params\n utm_source: optional(tagText),\n utm_medium: optional(tagText),\n utm_campaign: optional(tagText),\n utm_term: optional(tagText),\n utm_content: optional(tagText),\n utm_id: optional(tagText),\n utm_source_platform: optional(tagText),\n utm_creative_format: optional(tagText),\n utm_marketing_tactic: optional(tagText),\n});\n\nexport const propertiesSchema = optional(\n pipe(\n record(string(), union([propertyText, number(), boolean(), _null(), items])),\n transform(takeProperties)\n )\n);\n\n/**\n * How far an event's time may be from the server's before the client clock it was stamped with is\n * taken as wrong. A batch legitimately arrives late — a tab frozen in the background, a\n * session_start held back after a failed batch — by hours, not days; a phone set to another year\n * writes its sessions into that year.\n */\nconst MAX_CLOCK_SKEW = 24 * 60 * 60 * 1000;\n\n/**\n * Puts the events stamped by a wrong client clock onto the server's, where they are parsed. Only\n * the events outside `MAX_CLOCK_SKEW` move, so one bad event cannot drag the rest of its batch\n * along: they move together by their own latest one — the wrong clock at sending — keeping their\n * order and spacing, and one still out after that (a batch mixing two wrong clocks) is on no clock\n * at all and takes the server's time. Corrected rather than rejected, for the same reason values\n * are truncated: a wrong clock should cost the event its time, not the batch its events.\n */\nfunction alignClock<T extends { timestamp: string }>(events: T[], now = Date.now()): T[] {\n const within = (time: number) => Math.abs(now - time) <= MAX_CLOCK_SKEW;\n const times = events.map((event) => Date.parse(event.timestamp));\n const wrong = times.filter((time) => !within(time));\n if (wrong.length === 0) return events;\n const offset = now - Math.max(...wrong);\n return events.map((event, i) => {\n if (within(times[i])) return event;\n const shifted = times[i] + offset;\n return { ...event, timestamp: new Date(within(shifted) ? shifted : now).toISOString() };\n });\n}\n\nexport const createTrackEventSchema = pipe(\n array(\n object({\n /**\n * The event's id, generated by the client when the event was tracked (12.1) and given to\n * the browser pixels as their deduplication id. Store the event under it with\n * `on conflict (id) do nothing`: a batch retried after the server committed it then\n * stores nothing twice. Optional for clients before 12.1, which send none — generate one\n * on the server for those.\n */\n id: optional(uuid({ version: 'v7' })),\n name: string().check(trim(), minLength(1), maxLength(64)),\n // Generated by the SDK, like `id` (`visitorId()`, `Session`): uuidv7 as well, so the\n // constraint is checked here once and the server need not check it again.\n visitor_id: uuid({ version: 'v7' }),\n session_id: uuid({ version: 'v7' }),\n platform: _enum(ALL_PLATFORMS),\n environment: _enum(ALL_ENVIRONMENTS),\n timestamp: iso.datetime(),\n tags: tagsSchema,\n properties: propertiesSchema,\n })\n ).check(minLength(1), maxLength(100)),\n transform((events) => alignClock(events))\n);\n\n/**\n * `POST /visitors`, what clients before 11.0 create their visitor with; 11.0 generates the id\n * itself and the server creates the visitor from its first events (README, \"Visitors\").\n * Kept for servers that still serve older clients.\n */\nexport const createVisitorSchema = object({\n device_id: string().check(trim(), minLength(1), maxLength(36)),\n platform: _enum(ALL_PLATFORMS),\n environment: _enum(ALL_ENVIRONMENTS),\n tags: tagsSchema,\n});\n\nconst emailValue = pipe(string().check(trim(), toLowerCase(), maxLength(320)), email());\n\n/** E.164: a plus sign (+) prefix, country code, then digits only, no dashes/parens/spaces. */\nconst phoneValue = pipe(string().check(trim()), e164());\n\nconst addressValue = object({\n first_name: optional(string().check(trim(), maxLength(128))),\n last_name: optional(string().check(trim(), maxLength(128))),\n street: optional(string().check(trim(), maxLength(256))),\n city: optional(string().check(trim(), maxLength(128))),\n /** User province, state, or region. Example: `Hampshire` */\n region: optional(string().check(trim(), maxLength(128))),\n postal_code: optional(string().check(trim(), maxLength(32))),\n /** 2-letter country code, per the ISO 3166-1 alpha-2 standard. Example: `UK` */\n country: optional(string().check(trim(), toUpperCase(), regex(/^[A-Z]{2}$/))),\n});\n\n/**\n * User-provided data (UPD) used for enhanced conversions, Customer Match, and demographics.\n * Values are sent unhashed; Google normalizes and hashes them before they reach its servers.\n *\n * Multiple values may be sent to increase the match rate: up to 3 emails, 3 phone numbers, and\n * 2 addresses.\n *\n * @see https://support.google.com/analytics/answer/14078702\n * @see https://support.google.com/google-ads/answer/13258081\n */\nexport const userProvidedDataSchema = object({\n email: optional(union([emailValue, array(emailValue).check(minLength(1), maxLength(3))])),\n phone_number: optional(union([phoneValue, array(phoneValue).check(minLength(1), maxLength(3))])),\n address: optional(union([addressValue, array(addressValue).check(minLength(1), maxLength(2))])),\n});\n\nexport const updateVisitorSchema = object({\n user_id: optional(uuid()),\n user_data: optional(userProvidedDataSchema),\n /**\n * Sent by clients before 11.1, which PATCHed their tags on every page load. From 11.1 the\n * server refreshes `visitor.tags` from each `session_start` — the moment the visit arrives —\n * and `identify` sends none: at sign-in the page is no longer where the visit came in.\n */\n tags: optional(tagsSchema),\n});\n\nexport const createFeedbackSchema = object({\n name: string().check(minLength(1), maxLength(256)),\n // Trimmed and lower-cased like every other email the SDK accepts, so a host stores the\n // normalized form without wrapping the schema.\n email: emailValue,\n message: string().check(minLength(1), maxLength(65536)),\n /**\n * The Cloudflare Turnstile token the host verifies before storing the feedback (the same field\n * `@shware/security`'s email-code request carries). Required: without it `POST /feedback` is an\n * open free-text write that only a rate limit protects. Single-use: Turnstile spends the token\n * at verification, so the caller resets the widget after every submit, success or failure.\n */\n turnstileToken: string().check(minLength(1), maxLength(2048)),\n});\n\nconst noEmptyString = pipe(\n string().check(maxLength(256)),\n transform((v) => (v ? v : undefined))\n);\n\n/**\n * The schema for creating a link.\n * @see https://support.google.com/analytics/answer/10917952\n * */\nexport const createLinkSchema = object({\n /** The URL that the user is redirected to. */\n url: url().check(minLength(1), maxLength(1024)), // required\n\n /**\n * Campaign ID. Used to identify a specific campaign or promotion. This is a required key for GA4\n * data import. Use the same IDs that you use when uploading campaign cost data.\n */\n utm_id: optional(noEmptyString),\n\n /** Referrer, for example: google, newsletter4, billboard */\n utm_source: string().check(minLength(1), maxLength(256)), // required\n\n /** Marketing medium, for example: cpc, banner, email */\n utm_medium: string().check(minLength(1), maxLength(256)), // required\n\n /** Product, slogan, promo code, for example, spring_sale */\n utm_campaign: string().check(minLength(1), maxLength(256)), // required\n\n /** Paid keyword */\n utm_term: optional(noEmptyString),\n\n /**\n * Use to differentiate creatives. For example, if you have two call-to-action links within the\n * same email message, you can use utm_content and set different values for each so you can tell\n * which version is more effective.\n */\n utm_content: optional(noEmptyString),\n\n /**\n * The platform responsible for directing traffic to a given Analytics property (such as a buying\n * platform that sets budgets and targeting criteria or a platform that manages organic traffic\n * data). For example, Search Ads 360 or Display & Video 360.\n */\n utm_source_platform: optional(noEmptyString),\n\n /**\n * Type of creative, for example, display, native, video, search, utm_creative_format is not\n * currently reported in Google Analytics 4 properties.\n */\n utm_creative_format: optional(noEmptyString),\n\n /**\n * Targeting criteria applied to a campaign, for example, remarketing, prospecting,\n * utm_marketing_tactic is not currently reported in Google Analytics 4 properties.\n * */\n utm_marketing_tactic: optional(noEmptyString),\n});\n\nexport type CreateTrackEventDTO = z.output<typeof createTrackEventSchema>;\nexport type CreateFeedbackDTO = z.output<typeof createFeedbackSchema>;\nexport type CreateLinkDTO = z.output<typeof createLinkSchema>;\nexport type CreateVisitorDTO = z.output<typeof createVisitorSchema>;\nexport type UserProvidedDataDTO = z.output<typeof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,WAAW,MAAO,IAAI,IAAI,KAAA,CAAU,CACtC;;;;;AAMA,MAAa,mBAAmB,OAAO;;CAErC,KAAK,IAAI,CAAC,CAAC,MAAM,UAAU,CAAC,GAAG,UAAU,IAAI,CAAC;;;;;CAM9C,QAAQ,SAAS,aAAa;;CAG9B,YAAY,OAAO,CAAC,CAAC,MAAM,UAAU,CAAC,GAAG,UAAU,GAAG,CAAC;;CAGvD,YAAY,OAAO,CAAC,CAAC,MAAM,UAAU,CAAC,GAAG,UAAU,GAAG,CAAC;;CAGvD,cAAc,OAAO,CAAC,CAAC,MAAM,UAAU,CAAC,GAAG,UAAU,GAAG,CAAC;;CAGzD,UAAU,SAAS,aAAa;;;;;;CAOhC,aAAa,SAAS,aAAa;;;;;;CAOnC,qBAAqB,SAAS,aAAa;;;;;CAM3C,qBAAqB,SAAS,aAAa;;;;;CAM3C,sBAAsB,SAAS,aAAa;AAC9C,CAAC"}
1
+ {"version":3,"file":"index.mjs","names":["_null","_enum"],"sources":["../../src/schema/index.ts"],"sourcesContent":["import {\n enum as _enum,\n null as _null,\n array,\n boolean,\n e164,\n email,\n iso,\n maxLength,\n minLength,\n number,\n object,\n optional,\n pipe,\n record,\n regex,\n string,\n toLowerCase,\n toUpperCase,\n transform,\n trim,\n union,\n url,\n uuid,\n type z,\n} from 'zod/mini';\nimport type { Environment, Platform } from '../track/types';\n\nconst MAX_KEY_LENGTH = 128;\nconst MAX_VALUE_LENGTH = 512;\nconst MAX_PROPERTIES = 64;\n\n/**\n * Truncated rather than rejected. These schemas validate a whole batch at once, so refusing one\n * oversized value costs every event that traveled with it — and the values that overrun are the\n * ones derived from the page (a link's text, a URL carrying a long query), which no client can\n * bound in advance. A shortened value is worth more than a lost batch.\n */\nconst propertyText = pipe(\n string(),\n transform((value) => value.slice(0, MAX_VALUE_LENGTH))\n);\n\n/**\n * Tags are truncated for the same reason property values are, and they are stored more than once\n * (on the event, the session and the visitor), so an unbounded one costs several times over.\n * 1024 sits just above what GA4 itself keeps (1000 characters of page_location, 420 of\n * page_referrer, 300 of page_title). Real tags stay under ~500 characters; the rare longer ones\n * are page_referrer values from search and ad redirect URLs, where the kept prefix — host and\n * path — is the part that matters.\n */\nconst MAX_TAG_LENGTH = 1024;\n\nconst tagText = pipe(\n string(),\n transform((value) => value.slice(0, MAX_TAG_LENGTH))\n);\n\n/**\n * Keys are written by hand in instrumentation code, so an unusable one is a mistake in the host\n * rather than something the visitor typed. It is still dropped rather than rejected, for the same\n * reason: the mistake should cost that property, not the batch it happens to be in. Truncating a\n * key is not an option — two long keys would silently become one field.\n *\n * The key schema below is deliberately permissive so that this transform is reached at all; the\n * trimming it used to do happens here instead. `MAX_PROPERTIES` keeps the first N in insertion\n * order.\n */\nfunction takeProperties<T>(data: Record<string, T>): Record<string, T> {\n const result: Record<string, T> = {};\n let count = 0;\n for (const [rawKey, value] of Object.entries(data)) {\n if (count >= MAX_PROPERTIES) break;\n const key = rawKey.trim();\n if (!key || key.length > MAX_KEY_LENGTH) continue;\n result[key] = value;\n count++;\n }\n return result;\n}\n\n/**\n * Capped at GA4's own item-list limit, and truncated rather than rejected like every other\n * property limit here: an unbounded array is the one field a caller could still blow a batch\n * up with after the value and key limits.\n */\nconst MAX_ITEMS = 200;\n\nconst items = pipe(\n array(\n pipe(\n record(string(), union([propertyText, number(), boolean(), _null()])),\n transform(takeProperties)\n )\n ),\n transform((list) => list.slice(0, MAX_ITEMS))\n);\n\nexport const ALL_PLATFORMS = [\n 'ios',\n 'android',\n 'web',\n 'macos',\n 'windows',\n 'linux',\n 'unknown',\n] as const satisfies Platform[];\n\nexport const ALL_ENVIRONMENTS = ['development', 'production'] as const satisfies Environment[];\n\nexport const tagsSchema = object({\n os: optional(tagText),\n os_name: optional(tagText),\n os_version: optional(tagText),\n browser: optional(tagText),\n browser_name: optional(tagText),\n browser_version: optional(tagText),\n device: optional(tagText),\n device_id: optional(string().check(trim(), minLength(1), maxLength(36))),\n device_type: optional(tagText),\n device_vendor: optional(tagText),\n device_pixel_ratio: optional(number()),\n screen_width: optional(number()),\n screen_height: optional(number()),\n screen_resolution: optional(\n pipe(\n string().check(regex(/^\\d+x\\d+$/)),\n transform((v) => v as `${number}x${number}`)\n )\n ),\n webdriver: optional(boolean()),\n release: optional(tagText),\n language: optional(tagText),\n time_zone: optional(tagText),\n page_location: optional(tagText),\n page_referrer: optional(tagText),\n page_title: optional(tagText),\n page_load_id: optional(tagText),\n /**\n * @deprecated Renamed to `page_location` in 7.0.0. Accepted so that events from clients\n * still on an older SDK are not stripped of their page URL at this boundary — a browser\n * bundle stays cached long after a backend deploys. Remove once those clients are gone;\n * `pageLocation` in `server/page-location.ts` is the only reader.\n */\n // oxlint-disable-next-line typescript/no-deprecated -- Legacy input from pre-7.0 clients must survive validation.\n source_url: optional(tagText),\n // app info\n advertising_id: optional(tagText),\n install_referrer: optional(tagText),\n // Ad click ids (URL parameters) and ad platform cookies (underscore names); see AdvertisingInfo.\n // Meta Ads\n fbclid: optional(tagText),\n ad_id: optional(tagText),\n ad_name: optional(tagText),\n adset_id: optional(tagText),\n adset_name: optional(tagText),\n campaign_id: optional(tagText),\n campaign_name: optional(tagText),\n placement: optional(tagText),\n _fbc: optional(tagText),\n _fbp: optional(tagText),\n /**\n * @deprecated `fbc` / `fbp` / `rdt_uuid` were renamed to `_fbc` / `_fbp` / `_rdt_uuid` in 9.0.0.\n * Accepted so that conversions from clients still on an older SDK keep their match keys; the\n * senders read them only as a fallback (`server/click-ids.ts`). Remove once those clients are\n * gone.\n */\n // oxlint-disable-next-line typescript/no-deprecated -- Legacy pre-9.0 click-id fields must survive validation.\n fbc: optional(tagText),\n fbp: optional(tagText),\n rdt_uuid: optional(tagText),\n // Google Ads\n gclid: optional(tagText),\n gclsrc: optional(tagText),\n gad_source: optional(tagText),\n gad_campaignid: optional(tagText),\n network: optional(tagText),\n match_type: optional(tagText),\n wbraid: optional(tagText),\n gbraid: optional(tagText),\n dclid: optional(tagText),\n _gcl_aw: optional(tagText),\n _gcl_gb: optional(tagText),\n // Microsoft Ads\n msclkid: optional(tagText),\n _uetmsclkid: optional(tagText),\n // Reddit Ads\n rdt_cid: optional(tagText),\n _rdt_cid: optional(tagText),\n _rdt_uuid: optional(tagText),\n // LinkedIn Ads\n li_fat_id: optional(tagText),\n _li_fat_id: optional(tagText),\n // OpenAI Ads\n oppref: optional(tagText),\n __oppref: optional(tagText),\n __obref: optional(tagText),\n // other click ids\n ko_click_id: optional(tagText),\n ScCid: optional(tagText),\n ttclid: optional(tagText),\n twclid: optional(tagText),\n yclid: optional(tagText),\n epik: optional(tagText),\n // utm params\n utm_source: optional(tagText),\n utm_medium: optional(tagText),\n utm_campaign: optional(tagText),\n utm_term: optional(tagText),\n utm_content: optional(tagText),\n utm_id: optional(tagText),\n utm_source_platform: optional(tagText),\n utm_creative_format: optional(tagText),\n utm_marketing_tactic: optional(tagText),\n});\n\nexport const propertiesSchema = optional(\n pipe(\n record(string(), union([propertyText, number(), boolean(), _null(), items])),\n transform(takeProperties)\n )\n);\n\n/**\n * How far behind the server's an event's time may be before the client clock it was stamped with\n * is taken as wrong. A batch legitimately arrives late — a tab frozen in the background, a\n * session_start held back after a failed batch — by hours, not days; a phone set to another year\n * writes its sessions into that year. Ahead of the server's is wrong by any amount: an event\n * cannot have happened after it arrived, and a clock a few minutes fast is common enough that the\n * conversions APIs, which reject a future event, turned its events away by the hundred.\n */\nconst MAX_CLOCK_SKEW = 24 * 60 * 60 * 1000;\n\n/**\n * Puts the events stamped by a wrong client clock onto the server's, where they are parsed. Only\n * the events ahead of the server, or further behind it than `MAX_CLOCK_SKEW`, move, so one bad\n * event cannot drag the rest of its batch along: they move together by their own latest one — the\n * wrong clock at sending — keeping their order and spacing, and one still out after that (a batch mixing two wrong clocks) is on no clock\n * at all and takes the server's time. Corrected rather than rejected, for the same reason values\n * are truncated: a wrong clock should cost the event its time, not the batch its events.\n */\nfunction alignClock<T extends { timestamp: string }>(events: T[], now = Date.now()): T[] {\n const within = (time: number) => time <= now && now - time <= MAX_CLOCK_SKEW;\n const times = events.map((event) => Date.parse(event.timestamp));\n const wrong = times.filter((time) => !within(time));\n if (wrong.length === 0) return events;\n const offset = now - Math.max(...wrong);\n return events.map((event, i) => {\n if (within(times[i])) return event;\n const shifted = times[i] + offset;\n return { ...event, timestamp: new Date(within(shifted) ? shifted : now).toISOString() };\n });\n}\n\nexport const createTrackEventSchema = pipe(\n array(\n object({\n /**\n * The event's id, generated by the client when the event was tracked (12.1) and given to\n * the browser pixels as their deduplication id. Store the event under it with\n * `on conflict (id) do nothing`: a batch retried after the server committed it then\n * stores nothing twice. Optional for clients before 12.1, which send none — generate one\n * on the server for those.\n */\n id: optional(uuid({ version: 'v7' })),\n name: string().check(trim(), minLength(1), maxLength(64)),\n // Generated by the SDK, like `id` (`visitorId()`, `Session`): uuidv7 as well, so the\n // constraint is checked here once and the server need not check it again.\n visitor_id: uuid({ version: 'v7' }),\n session_id: uuid({ version: 'v7' }),\n platform: _enum(ALL_PLATFORMS),\n environment: _enum(ALL_ENVIRONMENTS),\n timestamp: iso.datetime(),\n tags: tagsSchema,\n properties: propertiesSchema,\n })\n ).check(minLength(1), maxLength(100)),\n transform((events) => alignClock(events))\n);\n\n/**\n * `POST /visitors`, what clients before 11.0 create their visitor with; 11.0 generates the id\n * itself and the server creates the visitor from its first events (README, \"Visitors\").\n * Kept for servers that still serve older clients.\n */\nexport const createVisitorSchema = object({\n device_id: string().check(trim(), minLength(1), maxLength(36)),\n platform: _enum(ALL_PLATFORMS),\n environment: _enum(ALL_ENVIRONMENTS),\n tags: tagsSchema,\n});\n\nconst emailValue = pipe(string().check(trim(), toLowerCase(), maxLength(320)), email());\n\n/** E.164: a plus sign (+) prefix, country code, then digits only, no dashes/parens/spaces. */\nconst phoneValue = pipe(string().check(trim()), e164());\n\nconst addressValue = object({\n first_name: optional(string().check(trim(), maxLength(128))),\n last_name: optional(string().check(trim(), maxLength(128))),\n street: optional(string().check(trim(), maxLength(256))),\n city: optional(string().check(trim(), maxLength(128))),\n /** User province, state, or region. Example: `Hampshire` */\n region: optional(string().check(trim(), maxLength(128))),\n postal_code: optional(string().check(trim(), maxLength(32))),\n /** 2-letter country code, per the ISO 3166-1 alpha-2 standard. Example: `UK` */\n country: optional(string().check(trim(), toUpperCase(), regex(/^[A-Z]{2}$/))),\n});\n\n/**\n * User-provided data (UPD) used for enhanced conversions, Customer Match, and demographics.\n * Values are sent unhashed; Google normalizes and hashes them before they reach its servers.\n *\n * Multiple values may be sent to increase the match rate: up to 3 emails, 3 phone numbers, and\n * 2 addresses.\n *\n * @see https://support.google.com/analytics/answer/14078702\n * @see https://support.google.com/google-ads/answer/13258081\n */\nexport const userProvidedDataSchema = object({\n email: optional(union([emailValue, array(emailValue).check(minLength(1), maxLength(3))])),\n phone_number: optional(union([phoneValue, array(phoneValue).check(minLength(1), maxLength(3))])),\n address: optional(union([addressValue, array(addressValue).check(minLength(1), maxLength(2))])),\n});\n\nexport const updateVisitorSchema = object({\n user_id: optional(uuid()),\n user_data: optional(userProvidedDataSchema),\n /**\n * Sent by clients before 11.1, which PATCHed their tags on every page load. From 11.1 the\n * server refreshes `visitor.tags` from each `session_start` — the moment the visit arrives —\n * and `identify` sends none: at sign-in the page is no longer where the visit came in.\n */\n tags: optional(tagsSchema),\n});\n\nexport const createFeedbackSchema = object({\n name: string().check(minLength(1), maxLength(256)),\n // Trimmed and lower-cased like every other email the SDK accepts, so a host stores the\n // normalized form without wrapping the schema.\n email: emailValue,\n message: string().check(minLength(1), maxLength(65536)),\n /**\n * The Cloudflare Turnstile token the host verifies before storing the feedback (the same field\n * `@shware/security`'s email-code request carries). Required: without it `POST /feedback` is an\n * open free-text write that only a rate limit protects. Single-use: Turnstile spends the token\n * at verification, so the caller resets the widget after every submit, success or failure.\n */\n turnstileToken: string().check(minLength(1), maxLength(2048)),\n});\n\nconst noEmptyString = pipe(\n string().check(maxLength(256)),\n transform((v) => (v ? v : undefined))\n);\n\n/**\n * The schema for creating a link.\n * @see https://support.google.com/analytics/answer/10917952\n * */\nexport const createLinkSchema = object({\n /** The URL that the user is redirected to. */\n url: url().check(minLength(1), maxLength(1024)), // required\n\n /**\n * Campaign ID. Used to identify a specific campaign or promotion. This is a required key for GA4\n * data import. Use the same IDs that you use when uploading campaign cost data.\n */\n utm_id: optional(noEmptyString),\n\n /** Referrer, for example: google, newsletter4, billboard */\n utm_source: string().check(minLength(1), maxLength(256)), // required\n\n /** Marketing medium, for example: cpc, banner, email */\n utm_medium: string().check(minLength(1), maxLength(256)), // required\n\n /** Product, slogan, promo code, for example, spring_sale */\n utm_campaign: string().check(minLength(1), maxLength(256)), // required\n\n /** Paid keyword */\n utm_term: optional(noEmptyString),\n\n /**\n * Use to differentiate creatives. For example, if you have two call-to-action links within the\n * same email message, you can use utm_content and set different values for each so you can tell\n * which version is more effective.\n */\n utm_content: optional(noEmptyString),\n\n /**\n * The platform responsible for directing traffic to a given Analytics property (such as a buying\n * platform that sets budgets and targeting criteria or a platform that manages organic traffic\n * data). For example, Search Ads 360 or Display & Video 360.\n */\n utm_source_platform: optional(noEmptyString),\n\n /**\n * Type of creative, for example, display, native, video, search, utm_creative_format is not\n * currently reported in Google Analytics 4 properties.\n */\n utm_creative_format: optional(noEmptyString),\n\n /**\n * Targeting criteria applied to a campaign, for example, remarketing, prospecting,\n * utm_marketing_tactic is not currently reported in Google Analytics 4 properties.\n * */\n utm_marketing_tactic: optional(noEmptyString),\n});\n\nexport type CreateTrackEventDTO = z.output<typeof createTrackEventSchema>;\nexport type CreateFeedbackDTO = z.output<typeof createFeedbackSchema>;\nexport type CreateLinkDTO = z.output<typeof createLinkSchema>;\nexport type CreateVisitorDTO = z.output<typeof createVisitorSchema>;\nexport type UserProvidedDataDTO = z.output<typeof userProvidedDataSchema>;\nexport type UpdateVisitorDTO = z.output<typeof updateVisitorSchema>;\n"],"mappings":";;AA4BA,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;;;;;;;AAQvB,MAAM,eAAe,KACnB,OAAO,GAC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aAAa;;CAG9B,YAAY,OAAO,CAAC,CAAC,MAAM,UAAU,CAAC,GAAG,UAAU,GAAG,CAAC;;CAGvD,YAAY,OAAO,CAAC,CAAC,MAAM,UAAU,CAAC,GAAG,UAAU,GAAG,CAAC;;CAGvD,cAAc,OAAO,CAAC,CAAC,MAAM,UAAU,CAAC,GAAG,UAAU,GAAG,CAAC;;CAGzD,UAAU,SAAS,aAAa;;;;;;CAOhC,aAAa,SAAS,aAAa;;;;;;CAOnC,qBAAqB,SAAS,aAAa;;;;;CAM3C,qBAAqB,SAAS,aAAa;;;;;CAM3C,sBAAsB,SAAS,aAAa;AAC9C,CAAC"}
@@ -0,0 +1,14 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ // src/server/event-time.ts
3
+ /**
4
+ * When an event happened, as a conversions API is told: its stored time, but never later than
5
+ * now. Microsoft, Reddit and Meta reject an event stamped in the future, and fail the whole
6
+ * request with it; a browser clock running a few minutes fast stamps exactly that, and an event
7
+ * cannot have happened after the moment it is sent.
8
+ */
9
+ function eventTimeMs(createdAt) {
10
+ return Math.min(Date.parse(createdAt), Date.now());
11
+ }
12
+ exports.eventTimeMs = eventTimeMs;
13
+
14
+ //# sourceMappingURL=event-time.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-time.cjs","names":[],"sources":["../../src/server/event-time.ts"],"sourcesContent":["/**\n * When an event happened, as a conversions API is told: its stored time, but never later than\n * now. Microsoft, Reddit and Meta reject an event stamped in the future, and fail the whole\n * request with it; a browser clock running a few minutes fast stamps exactly that, and an event\n * cannot have happened after the moment it is sent.\n */\nexport function eventTimeMs(createdAt: string): number {\n return Math.min(Date.parse(createdAt), Date.now());\n}\n"],"mappings":";;;;;;;;AAMA,SAAgB,YAAY,WAA2B;CACrD,OAAO,KAAK,IAAI,KAAK,MAAM,SAAS,GAAG,KAAK,IAAI,CAAC;AACnD"}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * When an event happened, as a conversions API is told: its stored time, but never later than
3
+ * now. Microsoft, Reddit and Meta reject an event stamped in the future, and fail the whole
4
+ * request with it; a browser clock running a few minutes fast stamps exactly that, and an event
5
+ * cannot have happened after the moment it is sent.
6
+ */
7
+ export declare function eventTimeMs(createdAt: string): number;
8
+ //# sourceMappingURL=event-time.d.cts.map