posthog-node 5.32.1 → 5.33.1

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.
package/dist/client.d.ts CHANGED
@@ -1,8 +1,13 @@
1
1
  import { FeatureFlagValue, JsonType, PostHogCaptureOptions, PostHogCoreStateless, PostHogFetchOptions, PostHogFetchResponse, PostHogFlagsAndPayloadsResponse, PostHogPersistedProperty } from '@posthog/core';
2
2
  import { EventMessage, FeatureFlagResult, GroupIdentifyMessage, IdentifyMessage, IPostHog, OverrideFeatureFlagsOptions, PostHogOptions, FlagEvaluationOptions, AllFlagsOptions } from './types';
3
+ import { FeatureFlagEvaluations, FlagCalledEventParams } from './feature-flag-evaluations';
3
4
  import ErrorTracking from './extensions/error-tracking';
4
5
  import { PostHogEventProperties } from '@posthog/core';
5
6
  import { ContextData, ContextOptions, IPostHogContext } from './extensions/context/types';
7
+ /**
8
+ * @internal — clears the process-wide deprecation dedup set. Test-only.
9
+ */
10
+ export declare function _resetDeprecationWarningsForTests(): void;
6
11
  export declare abstract class PostHogBackendClient extends PostHogCoreStateless implements IPostHog {
7
12
  private _memoryStorage;
8
13
  private featureFlagsPoller?;
@@ -448,6 +453,11 @@ export declare abstract class PostHogBackendClient extends PostHogCoreStateless
448
453
  *
449
454
  * {@label Feature flags}
450
455
  *
456
+ * @deprecated Use {@link evaluateFlags} and call `flags.getFlag(key)` on the returned snapshot.
457
+ * This consolidates flag evaluation into a single `/flags` request per incoming request and
458
+ * avoids drift between the values your code branched on and the values attached to events.
459
+ * Will be removed in the next major version.
460
+ *
451
461
  * @param key - The feature flag key
452
462
  * @param distinctId - The user's distinct ID
453
463
  * @param options - Optional configuration for flag evaluation
@@ -490,6 +500,10 @@ export declare abstract class PostHogBackendClient extends PostHogCoreStateless
490
500
  *
491
501
  * {@label Feature flags}
492
502
  *
503
+ * @deprecated Use {@link evaluateFlags} and call `flags.getFlagPayload(key)` on the returned
504
+ * snapshot. This consolidates flag evaluation into a single `/flags` request per incoming
505
+ * request. Will be removed in the next major version.
506
+ *
493
507
  * @param key - The feature flag key
494
508
  * @param distinctId - The user's distinct ID
495
509
  * @param matchValue - Optional match value to get payload for
@@ -584,6 +598,10 @@ export declare abstract class PostHogBackendClient extends PostHogCoreStateless
584
598
  *
585
599
  * {@label Feature flags}
586
600
  *
601
+ * @deprecated Use {@link evaluateFlags} and call `flags.isEnabled(key)` on the returned snapshot.
602
+ * This consolidates flag evaluation into a single `/flags` request per incoming request.
603
+ * Will be removed in the next major version.
604
+ *
587
605
  * @param key - The feature flag key
588
606
  * @param distinctId - The user's distinct ID
589
607
  * @param options - Optional configuration for flag evaluation
@@ -668,6 +686,84 @@ export declare abstract class PostHogBackendClient extends PostHogCoreStateless
668
686
  */
669
687
  getAllFlagsAndPayloads(options?: AllFlagsOptions): Promise<PostHogFlagsAndPayloadsResponse>;
670
688
  getAllFlagsAndPayloads(distinctId: string, options?: AllFlagsOptions): Promise<PostHogFlagsAndPayloadsResponse>;
689
+ /**
690
+ * Evaluate all feature flags for a user in a single call and return a
691
+ * {@link FeatureFlagEvaluations} snapshot. Branch on `.isEnabled()` / `.getFlag()`,
692
+ * then pass the same snapshot to `capture()` via the `flags` option so the
693
+ * captured event carries the exact flag values the code branched on.
694
+ *
695
+ * Prefer this over repeated `isFeatureEnabled()` / `getFeatureFlag()` calls and
696
+ * over `capture({ sendFeatureFlags: true })` — it consolidates flag evaluation
697
+ * into a single `/flags` request per incoming request.
698
+ *
699
+ * **Local evaluation is transparent.** When the poller can resolve a flag from
700
+ * cached definitions, no network call is made and the snapshot's `$feature_flag_called`
701
+ * events are tagged `locally_evaluated: true`.
702
+ *
703
+ * **Trim the request.** Pass `flagKeys` to scope the underlying `/flags` request
704
+ * to a subset of flags — useful when you only need a few flags and want to reduce
705
+ * the response payload.
706
+ *
707
+ * **Trim the event payload.** Use `flags.only([...])` or `flags.onlyAccessed()`
708
+ * to filter which flags get attached to a captured event without re-fetching.
709
+ *
710
+ * @example
711
+ * Basic usage:
712
+ * ```ts
713
+ * const flags = await client.evaluateFlags('user_123', {
714
+ * personProperties: { plan: 'enterprise' },
715
+ * })
716
+ * if (flags.isEnabled('new-dashboard')) {
717
+ * renderNewDashboard()
718
+ * }
719
+ * client.capture({ distinctId: 'user_123', event: 'page_viewed', flags })
720
+ * ```
721
+ *
722
+ * @example
723
+ * Scope the `/flags` request to specific keys:
724
+ * ```ts
725
+ * const flags = await client.evaluateFlags('user_123', {
726
+ * flagKeys: ['new-dashboard', 'checkout-flow'],
727
+ * personProperties: { plan: 'enterprise' },
728
+ * })
729
+ * ```
730
+ *
731
+ * @example
732
+ * Attach only the flags the developer actually checked:
733
+ * ```ts
734
+ * const flags = await client.evaluateFlags('user_123')
735
+ * if (flags.isEnabled('new-dashboard')) { ... }
736
+ * client.capture({ distinctId: 'user_123', event: 'page_viewed', flags: flags.onlyAccessed() })
737
+ * ```
738
+ *
739
+ * @example
740
+ * Use `withContext()` to avoid repeating the distinctId:
741
+ * ```ts
742
+ * await client.withContext({ distinctId: 'user_123' }, async () => {
743
+ * const flags = await client.evaluateFlags()
744
+ * if (flags.isEnabled('new-dashboard')) { ... }
745
+ * client.capture({ event: 'page_viewed', flags })
746
+ * })
747
+ * ```
748
+ *
749
+ * {@label Feature flags}
750
+ *
751
+ * @param distinctIdOrOptions - The user's distinct ID, or options when the distinctId comes from `withContext()`
752
+ * @param options - Optional configuration for flag evaluation. Supports the same fields as `getAllFlags()`, including `flagKeys` to scope the `/flags` request.
753
+ * @returns Promise that resolves to a `FeatureFlagEvaluations` snapshot
754
+ */
755
+ evaluateFlags(options?: AllFlagsOptions): Promise<FeatureFlagEvaluations>;
756
+ evaluateFlags(distinctId: string, options?: AllFlagsOptions): Promise<FeatureFlagEvaluations>;
757
+ /**
758
+ * Fires a `$feature_flag_called` event for the given flag if the (distinctId, flag, response)
759
+ * triple hasn't already been reported for this client. Shared by the single-flag evaluation
760
+ * path and `FeatureFlagEvaluations.isEnabled() / getFlag()` so both paths dedupe identically.
761
+ *
762
+ * @internal
763
+ */
764
+ protected _captureFlagCalledEventIfNeeded(params: FlagCalledEventParams): void;
765
+ private _featureFlagEvaluationsHost?;
766
+ private _getFeatureFlagEvaluationsHost;
671
767
  /**
672
768
  * Create or update a group and its properties.
673
769
  *
@@ -874,8 +970,10 @@ export declare abstract class PostHogBackendClient extends PostHogCoreStateless
874
970
  * @param error - The error to capture
875
971
  * @param distinctId - Optional user distinct ID
876
972
  * @param additionalProperties - Optional additional properties to include
973
+ * @param uuid - Optional event UUID
974
+ * @param flags - Optional `FeatureFlagEvaluations` snapshot to attach the same flag context as your other events
877
975
  */
878
- captureException(error: unknown, distinctId?: string, additionalProperties?: Record<string | number, any>, uuid?: EventMessage['uuid']): void;
976
+ captureException(error: unknown, distinctId?: string, additionalProperties?: Record<string | number, any>, uuid?: EventMessage['uuid'], flags?: FeatureFlagEvaluations): void;
879
977
  /**
880
978
  * Capture an error exception as an event immediately (synchronously).
881
979
  *
@@ -909,9 +1007,10 @@ export declare abstract class PostHogBackendClient extends PostHogCoreStateless
909
1007
  * @param error - The error to capture
910
1008
  * @param distinctId - Optional user distinct ID
911
1009
  * @param additionalProperties - Optional additional properties to include
1010
+ * @param flags - Optional `FeatureFlagEvaluations` snapshot to attach the same flag context as your other events
912
1011
  * @returns Promise that resolves when the error is captured
913
1012
  */
914
- captureExceptionImmediate(error: unknown, distinctId?: string, additionalProperties?: Record<string | number, any>): Promise<void>;
1013
+ captureExceptionImmediate(error: unknown, distinctId?: string, additionalProperties?: Record<string | number, any>, flags?: FeatureFlagEvaluations): Promise<void>;
915
1014
  prepareEventMessage(props: EventMessage): Promise<{
916
1015
  distinctId: string;
917
1016
  event: string;
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,gBAAgB,EAGhB,QAAQ,EACR,qBAAqB,EACrB,oBAAoB,EACpB,mBAAmB,EACnB,oBAAoB,EACpB,+BA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EAAE,YAAY,CAAC,MAAM,CAAC,EAC3B,KAAK,CAAC,EAAE,sBAAsB,GAC7B,IAAI;IAWP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAmCG;IACG,yBAAyB,CAC7B,KAAK,EAAE,OAAO,EACd,UAAU,CAAC,EAAE,MAAM,EACnB,oBAAoB,CAAC,EAAE,MAAM,CAAC,MAAM,GAAG,MAAM,EAAE,GAAG,CAAC,EACnD,KAAK,CAAC,EAAE,sBAAsB,GAC7B,OAAO,CAAC,IAAI,CAAC;IAWH,mBAAmB,CAAC,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC;QAC7D,UAAU,EAAE,MAAM,CAAA;QAClB,KAAK,EAAE,MAAM,CAAA;QACb,UAAU,EAAE,sBAAsB,CAAA;QAClC,OAAO,EAAE,qBAAqB,CAAA;KAC/B,CAAC;IA8HF,OAAO,CAAC,cAAc;CAuBvB"}
package/dist/client.js CHANGED
@@ -33,11 +33,13 @@ var __webpack_require__ = {};
33
33
  var __webpack_exports__ = {};
34
34
  __webpack_require__.r(__webpack_exports__);
35
35
  __webpack_require__.d(__webpack_exports__, {
36
+ _resetDeprecationWarningsForTests: ()=>_resetDeprecationWarningsForTests,
36
37
  PostHogBackendClient: ()=>PostHogBackendClient
37
38
  });
38
39
  const external_version_js_namespaceObject = require("./version.js");
39
40
  const core_namespaceObject = require("@posthog/core");
40
41
  const external_types_js_namespaceObject = require("./types.js");
42
+ const external_feature_flag_evaluations_js_namespaceObject = require("./feature-flag-evaluations.js");
41
43
  const feature_flags_js_namespaceObject = require("./extensions/feature-flags/feature-flags.js");
42
44
  const index_js_namespaceObject = require("./extensions/error-tracking/index.js");
43
45
  var index_js_default = /*#__PURE__*/ __webpack_require__.n(index_js_namespaceObject);
@@ -48,6 +50,15 @@ const MAX_CACHE_SIZE = 50000;
48
50
  const WAITUNTIL_DEBOUNCE_MS = 50;
49
51
  const WAITUNTIL_MAX_WAIT_MS = 500;
50
52
  const DEFAULT_NODE_HOST = 'https://us.i.posthog.com';
53
+ const _emittedDeprecations = new Set();
54
+ function emitDeprecationWarningOnce(id, message) {
55
+ if (_emittedDeprecations.has(id)) return;
56
+ _emittedDeprecations.add(id);
57
+ console.warn(`[PostHog] ${message}`);
58
+ }
59
+ function _resetDeprecationWarningsForTests() {
60
+ _emittedDeprecations.clear();
61
+ }
51
62
  function normalizeApiKey(value) {
52
63
  return 'string' == typeof value ? value.trim() : '';
53
64
  }
@@ -59,6 +70,14 @@ function normalizeHost(value) {
59
70
  const normalizedValue = 'string' == typeof value ? value.trim() : '';
60
71
  return normalizedValue || DEFAULT_NODE_HOST;
61
72
  }
73
+ function buildFlagEventProperties(flagValues) {
74
+ if (!flagValues) return {};
75
+ const additionalProperties = {};
76
+ for (const [feature, variant] of Object.entries(flagValues))additionalProperties[`$feature/${feature}`] = variant;
77
+ const activeFlags = Object.keys(flagValues).filter((flag)=>false !== flagValues[flag]).sort();
78
+ if (activeFlags.length > 0) additionalProperties['$active_feature_flags'] = activeFlags;
79
+ return additionalProperties;
80
+ }
62
81
  class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
63
82
  constructor(apiKey, options = {}){
64
83
  const normalizedApiKey = normalizeApiKey(apiKey);
@@ -355,37 +374,30 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
355
374
  }
356
375
  if (sendFeatureFlagEvents) {
357
376
  const response = void 0 === result ? void 0 : false === result.enabled ? false : result.variant ?? true;
358
- const featureFlagReportedKey = `${key}_${response}`;
359
- if (!(distinctId in this.distinctIdHasSentFlagCalls) || !this.distinctIdHasSentFlagCalls[distinctId].includes(featureFlagReportedKey)) {
360
- if (Object.keys(this.distinctIdHasSentFlagCalls).length >= this.maxCacheSize) this.distinctIdHasSentFlagCalls = {};
361
- if (Array.isArray(this.distinctIdHasSentFlagCalls[distinctId])) this.distinctIdHasSentFlagCalls[distinctId].push(featureFlagReportedKey);
362
- else this.distinctIdHasSentFlagCalls[distinctId] = [
363
- featureFlagReportedKey
364
- ];
365
- const properties = {
366
- $feature_flag: key,
367
- $feature_flag_response: response,
368
- $feature_flag_id: flagId,
369
- $feature_flag_version: flagVersion,
370
- $feature_flag_reason: flagReason,
371
- locally_evaluated: flagWasLocallyEvaluated,
372
- [`$feature/${key}`]: response,
373
- $feature_flag_request_id: requestId,
374
- $feature_flag_evaluated_at: flagWasLocallyEvaluated ? Date.now() : evaluatedAt
375
- };
376
- if (flagWasLocallyEvaluated && this.featureFlagsPoller) {
377
- const flagDefinitionsLoadedAt = this.featureFlagsPoller.getFlagDefinitionsLoadedAt();
378
- if (void 0 !== flagDefinitionsLoadedAt) properties.$feature_flag_definitions_loaded_at = flagDefinitionsLoadedAt;
379
- }
380
- if (featureFlagError) properties.$feature_flag_error = featureFlagError;
381
- this.capture({
382
- distinctId,
383
- event: '$feature_flag_called',
384
- properties,
385
- groups,
386
- disableGeoip
387
- });
377
+ const properties = {
378
+ $feature_flag: key,
379
+ $feature_flag_response: response,
380
+ $feature_flag_id: flagId,
381
+ $feature_flag_version: flagVersion,
382
+ $feature_flag_reason: flagReason,
383
+ locally_evaluated: flagWasLocallyEvaluated,
384
+ [`$feature/${key}`]: response,
385
+ $feature_flag_request_id: requestId,
386
+ $feature_flag_evaluated_at: flagWasLocallyEvaluated ? Date.now() : evaluatedAt
387
+ };
388
+ if (flagWasLocallyEvaluated && this.featureFlagsPoller) {
389
+ const flagDefinitionsLoadedAt = this.featureFlagsPoller.getFlagDefinitionsLoadedAt();
390
+ if (void 0 !== flagDefinitionsLoadedAt) properties.$feature_flag_definitions_loaded_at = flagDefinitionsLoadedAt;
388
391
  }
392
+ if (featureFlagError) properties.$feature_flag_error = featureFlagError;
393
+ this._captureFlagCalledEventIfNeeded({
394
+ distinctId,
395
+ key,
396
+ response,
397
+ groups,
398
+ disableGeoip,
399
+ properties
400
+ });
389
401
  }
390
402
  if (void 0 !== result && void 0 !== this._payloadOverrides && key in this._payloadOverrides) result = {
391
403
  ...result,
@@ -394,6 +406,7 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
394
406
  return result;
395
407
  }
396
408
  async getFeatureFlag(key, distinctId, options) {
409
+ emitDeprecationWarningOnce('getFeatureFlag', "`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");
397
410
  const result = await this._getFeatureFlagResult(key, distinctId, {
398
411
  ...options,
399
412
  sendFeatureFlagEvents: options?.sendFeatureFlagEvents ?? this.options.sendFeatureFlagEvent ?? true
@@ -403,6 +416,7 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
403
416
  return result.variant ?? true;
404
417
  }
405
418
  async getFeatureFlagPayload(key, distinctId, matchValue, options) {
419
+ emitDeprecationWarningOnce('getFeatureFlagPayload', "`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");
406
420
  if (void 0 !== this._payloadOverrides && key in this._payloadOverrides) return this._payloadOverrides[key];
407
421
  const result = await this._getFeatureFlagResult(key, distinctId, {
408
422
  ...options,
@@ -430,8 +444,14 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
430
444
  return parsed;
431
445
  }
432
446
  async isFeatureEnabled(key, distinctId, options) {
433
- const feat = await this.getFeatureFlag(key, distinctId, options);
434
- if (void 0 === feat) return;
447
+ emitDeprecationWarningOnce('isFeatureEnabled', "`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");
448
+ const result = await this._getFeatureFlagResult(key, distinctId, {
449
+ ...options,
450
+ sendFeatureFlagEvents: options?.sendFeatureFlagEvents ?? this.options.sendFeatureFlagEvent ?? true
451
+ });
452
+ if (void 0 === result) return;
453
+ if (false === result.enabled) return false;
454
+ const feat = result.variant ?? true;
435
455
  return !!feat || false;
436
456
  }
437
457
  async getAllFlags(distinctIdOrOptions, options) {
@@ -492,6 +512,136 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
492
512
  featureFlagPayloads
493
513
  };
494
514
  }
515
+ async evaluateFlags(distinctIdOrOptions, options) {
516
+ const { distinctId: resolvedDistinctId, options: resolvedOptions } = this._resolveDistinctId(distinctIdOrOptions, options);
517
+ if (!resolvedDistinctId) {
518
+ this._logger.warn("[PostHog] distinctId is required to evaluate feature flags \u2014 pass it explicitly or use withContext()");
519
+ return new external_feature_flag_evaluations_js_namespaceObject.FeatureFlagEvaluations({
520
+ host: this._getFeatureFlagEvaluationsHost(),
521
+ distinctId: '',
522
+ flags: {}
523
+ });
524
+ }
525
+ const { groups, disableGeoip, flagKeys } = resolvedOptions || {};
526
+ let { onlyEvaluateLocally, personProperties, groupProperties } = resolvedOptions || {};
527
+ const adjustedProperties = this.addLocalPersonAndGroupProperties(resolvedDistinctId, groups, personProperties, groupProperties);
528
+ personProperties = adjustedProperties.allPersonProperties;
529
+ groupProperties = adjustedProperties.allGroupProperties;
530
+ const evaluationContext = this.createFeatureFlagEvaluationContext(resolvedDistinctId, groups, personProperties, groupProperties);
531
+ if (void 0 == onlyEvaluateLocally) onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;
532
+ const records = {};
533
+ let requestId;
534
+ let evaluatedAt;
535
+ let errorsWhileComputing = false;
536
+ let quotaLimited = false;
537
+ const localResult = await this.featureFlagsPoller?.getAllFlagsAndPayloads(evaluationContext, flagKeys);
538
+ const locallyEvaluatedKeys = new Set();
539
+ if (localResult) for (const [key, value] of Object.entries(localResult.response)){
540
+ const flagDef = this.featureFlagsPoller?.featureFlagsByKey[key];
541
+ records[key] = {
542
+ key,
543
+ enabled: false !== value,
544
+ variant: 'string' == typeof value ? value : void 0,
545
+ payload: localResult.payloads[key],
546
+ id: flagDef?.id,
547
+ version: void 0,
548
+ reason: 'Evaluated locally',
549
+ locallyEvaluated: true
550
+ };
551
+ locallyEvaluatedKeys.add(key);
552
+ }
553
+ const fallbackToFlags = localResult ? localResult.fallbackToFlags : true;
554
+ if (fallbackToFlags && !onlyEvaluateLocally) {
555
+ const details = await super.getFeatureFlagDetailsStateless(evaluationContext.distinctId, evaluationContext.groups, evaluationContext.personProperties, evaluationContext.groupProperties, disableGeoip, flagKeys);
556
+ if (details) {
557
+ requestId = details.requestId;
558
+ evaluatedAt = details.evaluatedAt;
559
+ errorsWhileComputing = Boolean(details.errorsWhileComputingFlags);
560
+ quotaLimited = Array.isArray(details.quotaLimited) && details.quotaLimited.includes('feature_flags');
561
+ for (const [key, detail] of Object.entries(details.flags)){
562
+ if (locallyEvaluatedKeys.has(key)) continue;
563
+ let parsedPayload;
564
+ if (detail.metadata?.payload !== void 0) try {
565
+ parsedPayload = JSON.parse(detail.metadata.payload);
566
+ } catch {
567
+ parsedPayload = detail.metadata.payload;
568
+ }
569
+ records[key] = {
570
+ key,
571
+ enabled: detail.enabled,
572
+ variant: detail.variant,
573
+ payload: parsedPayload,
574
+ id: detail.metadata?.id,
575
+ version: detail.metadata?.version,
576
+ reason: detail.reason?.description ?? detail.reason?.code,
577
+ locallyEvaluated: false
578
+ };
579
+ }
580
+ }
581
+ }
582
+ if (void 0 !== this._flagOverrides) for (const [key, value] of Object.entries(this._flagOverrides)){
583
+ if (void 0 === value) {
584
+ delete records[key];
585
+ continue;
586
+ }
587
+ const existing = records[key];
588
+ records[key] = {
589
+ key,
590
+ enabled: false !== value,
591
+ variant: 'string' == typeof value ? value : void 0,
592
+ payload: existing?.payload,
593
+ id: existing?.id,
594
+ version: existing?.version,
595
+ reason: existing?.reason,
596
+ locallyEvaluated: existing?.locallyEvaluated ?? false
597
+ };
598
+ }
599
+ if (void 0 !== this._payloadOverrides) for (const [key, payload] of Object.entries(this._payloadOverrides)){
600
+ const existing = records[key];
601
+ if (existing) records[key] = {
602
+ ...existing,
603
+ payload
604
+ };
605
+ }
606
+ return new external_feature_flag_evaluations_js_namespaceObject.FeatureFlagEvaluations({
607
+ host: this._getFeatureFlagEvaluationsHost(),
608
+ distinctId: resolvedDistinctId,
609
+ groups,
610
+ disableGeoip,
611
+ flags: records,
612
+ requestId,
613
+ evaluatedAt,
614
+ flagDefinitionsLoadedAt: this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),
615
+ errorsWhileComputing,
616
+ quotaLimited
617
+ });
618
+ }
619
+ _captureFlagCalledEventIfNeeded(params) {
620
+ const { distinctId, key, response, groups, disableGeoip, properties } = params;
621
+ const featureFlagReportedKey = `${key}_${response}`;
622
+ if (distinctId in this.distinctIdHasSentFlagCalls && this.distinctIdHasSentFlagCalls[distinctId].includes(featureFlagReportedKey)) return;
623
+ if (Object.keys(this.distinctIdHasSentFlagCalls).length >= this.maxCacheSize) this.distinctIdHasSentFlagCalls = {};
624
+ if (Array.isArray(this.distinctIdHasSentFlagCalls[distinctId])) this.distinctIdHasSentFlagCalls[distinctId].push(featureFlagReportedKey);
625
+ else this.distinctIdHasSentFlagCalls[distinctId] = [
626
+ featureFlagReportedKey
627
+ ];
628
+ this.capture({
629
+ distinctId,
630
+ event: '$feature_flag_called',
631
+ properties,
632
+ groups,
633
+ disableGeoip
634
+ });
635
+ }
636
+ _getFeatureFlagEvaluationsHost() {
637
+ if (!this._featureFlagEvaluationsHost) this._featureFlagEvaluationsHost = {
638
+ captureFlagCalledEventIfNeeded: (params)=>this._captureFlagCalledEventIfNeeded(params),
639
+ logWarning: (message)=>{
640
+ if (false !== this.options.featureFlagsLogWarnings) console.warn(`[PostHog] ${message}`);
641
+ }
642
+ };
643
+ return this._featureFlagEvaluationsHost;
644
+ }
495
645
  groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip }) {
496
646
  super.groupIdentifyStateless(groupType, groupKey, properties, {
497
647
  disableGeoip
@@ -668,27 +818,31 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
668
818
  evaluationCache: {}
669
819
  };
670
820
  }
671
- captureException(error, distinctId, additionalProperties, uuid) {
821
+ captureException(error, distinctId, additionalProperties, uuid, flags) {
672
822
  if (!index_js_default().isPreviouslyCapturedError(error)) {
673
823
  const syntheticException = new Error('PostHog syntheticException');
674
824
  this.addPendingPromise(index_js_default().buildEventMessage(error, {
675
825
  syntheticException
676
826
  }, distinctId, additionalProperties).then((msg)=>this.capture({
677
827
  ...msg,
678
- uuid
828
+ uuid,
829
+ flags
679
830
  })));
680
831
  }
681
832
  }
682
- async captureExceptionImmediate(error, distinctId, additionalProperties) {
833
+ async captureExceptionImmediate(error, distinctId, additionalProperties, flags) {
683
834
  if (!index_js_default().isPreviouslyCapturedError(error)) {
684
835
  const syntheticException = new Error('PostHog syntheticException');
685
836
  return this.addPendingPromise(index_js_default().buildEventMessage(error, {
686
837
  syntheticException
687
- }, distinctId, additionalProperties).then((msg)=>this.captureImmediate(msg)));
838
+ }, distinctId, additionalProperties).then((msg)=>this.captureImmediate({
839
+ ...msg,
840
+ flags
841
+ })));
688
842
  }
689
843
  }
690
844
  async prepareEventMessage(props) {
691
- const { distinctId, event, properties, groups, sendFeatureFlags, timestamp, disableGeoip, uuid } = props;
845
+ const { distinctId, event, properties, groups, flags, sendFeatureFlags, timestamp, disableGeoip, uuid } = props;
692
846
  const contextData = this.context?.get();
693
847
  let mergedDistinctId = distinctId || contextData?.distinctId;
694
848
  const mergedProperties = {
@@ -706,6 +860,7 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
706
860
  event,
707
861
  properties: mergedProperties,
708
862
  groups,
863
+ flags,
709
864
  sendFeatureFlags,
710
865
  timestamp,
711
866
  disableGeoip,
@@ -713,18 +868,17 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
713
868
  });
714
869
  if (!eventMessage) return Promise.reject(null);
715
870
  const eventProperties = await Promise.resolve().then(async ()=>{
871
+ if (flags) {
872
+ if (sendFeatureFlags) console.warn('[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`.');
873
+ return flags._getEventProperties();
874
+ }
716
875
  if (sendFeatureFlags) {
876
+ emitDeprecationWarningOnce('sendFeatureFlags', "`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead — it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");
717
877
  const sendFeatureFlagsOptions = 'object' == typeof sendFeatureFlags ? sendFeatureFlags : void 0;
718
- return await this.getFeatureFlagsForEvent(eventMessage.distinctId, groups, disableGeoip, sendFeatureFlagsOptions);
878
+ const flagValues = await this.getFeatureFlagsForEvent(eventMessage.distinctId, groups, disableGeoip, sendFeatureFlagsOptions);
879
+ return buildFlagEventProperties(flagValues);
719
880
  }
720
- eventMessage.event;
721
881
  return {};
722
- }).then((flags)=>{
723
- const additionalProperties = {};
724
- if (flags) for (const [feature, variant] of Object.entries(flags))additionalProperties[`$feature/${feature}`] = variant;
725
- const activeFlags = Object.keys(flags || {}).filter((flag)=>flags?.[flag] !== false).sort();
726
- if (activeFlags.length > 0) additionalProperties['$active_feature_flags'] = activeFlags;
727
- return additionalProperties;
728
882
  }).catch(()=>({})).then((additionalProperties)=>{
729
883
  const props = {
730
884
  ...additionalProperties,
@@ -772,8 +926,10 @@ class PostHogBackendClient extends core_namespaceObject.PostHogCoreStateless {
772
926
  }
773
927
  }
774
928
  exports.PostHogBackendClient = __webpack_exports__.PostHogBackendClient;
929
+ exports._resetDeprecationWarningsForTests = __webpack_exports__._resetDeprecationWarningsForTests;
775
930
  for(var __webpack_i__ in __webpack_exports__)if (-1 === [
776
- "PostHogBackendClient"
931
+ "PostHogBackendClient",
932
+ "_resetDeprecationWarningsForTests"
777
933
  ].indexOf(__webpack_i__)) exports[__webpack_i__] = __webpack_exports__[__webpack_i__];
778
934
  Object.defineProperty(exports, '__esModule', {
779
935
  value: true