@posthog/core 1.52.2 → 1.53.0

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 (113) hide show
  1. package/dist/index.d.ts +7 -0
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +82 -21
  4. package/dist/index.mjs +4 -0
  5. package/dist/logs/index.d.ts +3 -2
  6. package/dist/logs/index.d.ts.map +1 -1
  7. package/dist/logs/index.js +28 -22
  8. package/dist/logs/index.mjs +29 -23
  9. package/dist/logs/logs-utils.js +1 -1
  10. package/dist/logs/logs-utils.mjs +2 -2
  11. package/dist/logs/types.d.ts +2 -2
  12. package/dist/metrics/index.d.ts +5 -2
  13. package/dist/metrics/index.d.ts.map +1 -1
  14. package/dist/metrics/index.js +28 -14
  15. package/dist/metrics/index.mjs +29 -15
  16. package/dist/metrics/metrics-utils.d.ts.map +1 -1
  17. package/dist/metrics/metrics-utils.js +1 -2
  18. package/dist/metrics/metrics-utils.mjs +2 -3
  19. package/dist/metrics/types.d.ts +7 -0
  20. package/dist/metrics/types.d.ts.map +1 -1
  21. package/dist/posthog-core-stateless.d.ts +32 -4
  22. package/dist/posthog-core-stateless.d.ts.map +1 -1
  23. package/dist/posthog-core-stateless.js +68 -20
  24. package/dist/posthog-core-stateless.mjs +68 -20
  25. package/dist/traces/config.d.ts +13 -0
  26. package/dist/traces/config.d.ts.map +1 -0
  27. package/dist/traces/config.js +101 -0
  28. package/dist/traces/config.mjs +63 -0
  29. package/dist/traces/context.d.ts +18 -0
  30. package/dist/traces/context.d.ts.map +1 -0
  31. package/dist/traces/context.js +53 -0
  32. package/dist/traces/context.mjs +15 -0
  33. package/dist/traces/ids.d.ts +12 -0
  34. package/dist/traces/ids.d.ts.map +1 -0
  35. package/dist/traces/ids.js +92 -0
  36. package/dist/traces/ids.mjs +42 -0
  37. package/dist/traces/index.d.ts +150 -0
  38. package/dist/traces/index.d.ts.map +1 -0
  39. package/dist/traces/index.js +551 -0
  40. package/dist/traces/index.mjs +513 -0
  41. package/dist/traces/otlp.d.ts +24 -0
  42. package/dist/traces/otlp.d.ts.map +1 -0
  43. package/dist/traces/otlp.js +158 -0
  44. package/dist/traces/otlp.mjs +108 -0
  45. package/dist/traces/sanitize.d.ts +32 -0
  46. package/dist/traces/sanitize.d.ts.map +1 -0
  47. package/dist/traces/sanitize.js +93 -0
  48. package/dist/traces/sanitize.mjs +43 -0
  49. package/dist/traces/span.d.ts +189 -0
  50. package/dist/traces/span.d.ts.map +1 -0
  51. package/dist/traces/span.js +533 -0
  52. package/dist/traces/span.mjs +462 -0
  53. package/dist/traces/traceparent.d.ts +51 -0
  54. package/dist/traces/traceparent.d.ts.map +1 -0
  55. package/dist/traces/traceparent.js +116 -0
  56. package/dist/traces/traceparent.mjs +63 -0
  57. package/dist/traces/types.d.ts +114 -0
  58. package/dist/traces/types.d.ts.map +1 -0
  59. package/dist/traces/types.js +18 -0
  60. package/dist/traces/types.mjs +1 -0
  61. package/dist/utils/backoff.d.ts +23 -0
  62. package/dist/utils/backoff.d.ts.map +1 -0
  63. package/dist/utils/backoff.js +65 -0
  64. package/dist/utils/backoff.mjs +14 -0
  65. package/dist/utils/flush-timer.d.ts +26 -0
  66. package/dist/utils/flush-timer.d.ts.map +1 -0
  67. package/dist/utils/flush-timer.js +67 -0
  68. package/dist/utils/flush-timer.mjs +29 -0
  69. package/dist/utils/json-utils.d.ts +7 -0
  70. package/dist/utils/json-utils.d.ts.map +1 -1
  71. package/dist/utils/json-utils.js +27 -0
  72. package/dist/utils/json-utils.mjs +25 -1
  73. package/dist/utils/otlp-resource.d.ts +13 -2
  74. package/dist/utils/otlp-resource.d.ts.map +1 -1
  75. package/dist/utils/otlp-resource.js +34 -7
  76. package/dist/utils/otlp-resource.mjs +26 -2
  77. package/dist/utils/retry-after.d.ts +55 -0
  78. package/dist/utils/retry-after.d.ts.map +1 -0
  79. package/dist/utils/retry-after.js +95 -0
  80. package/dist/utils/retry-after.mjs +50 -0
  81. package/package.json +3 -3
  82. package/src/index.ts +18 -0
  83. package/src/logs/index.spec.ts +490 -2
  84. package/src/logs/index.ts +63 -31
  85. package/src/logs/logs-utils.ts +2 -2
  86. package/src/logs/types.ts +2 -2
  87. package/src/metrics/index.spec.ts +304 -0
  88. package/src/metrics/index.ts +53 -16
  89. package/src/metrics/metrics-utils.ts +2 -3
  90. package/src/metrics/types.ts +10 -2
  91. package/src/posthog-core-stateless.ts +157 -38
  92. package/src/traces/config.spec.ts +271 -0
  93. package/src/traces/config.ts +142 -0
  94. package/src/traces/context.ts +30 -0
  95. package/src/traces/ids.spec.ts +115 -0
  96. package/src/traces/ids.ts +75 -0
  97. package/src/traces/index.spec.ts +3187 -0
  98. package/src/traces/index.ts +1060 -0
  99. package/src/traces/live-spans.spec.ts +69 -0
  100. package/src/traces/otlp.spec.ts +368 -0
  101. package/src/traces/otlp.ts +191 -0
  102. package/src/traces/sanitize.ts +116 -0
  103. package/src/traces/span.spec.ts +1122 -0
  104. package/src/traces/span.ts +822 -0
  105. package/src/traces/traceparent.spec.ts +184 -0
  106. package/src/traces/traceparent.ts +172 -0
  107. package/src/traces/types.ts +140 -0
  108. package/src/utils/backoff.ts +44 -0
  109. package/src/utils/flush-timer.ts +50 -0
  110. package/src/utils/json-utils.ts +33 -0
  111. package/src/utils/otlp-resource.spec.ts +55 -9
  112. package/src/utils/otlp-resource.ts +45 -4
  113. package/src/utils/retry-after.ts +135 -0
@@ -41,6 +41,7 @@ const external_featureFlagUtils_js_namespaceObject = require("./featureFlagUtils
41
41
  const external_gzip_js_namespaceObject = require("./gzip.js");
42
42
  const external_types_js_namespaceObject = require("./types.js");
43
43
  const index_js_namespaceObject = require("./utils/index.js");
44
+ const retry_after_js_namespaceObject = require("./utils/retry-after.js");
44
45
  const uuidv7_js_namespaceObject = require("./vendor/uuidv7.js");
45
46
  const external_error_tracking_index_js_namespaceObject = require("./error-tracking/index.js");
46
47
  class PostHogFetchHttpError extends Error {
@@ -50,6 +51,13 @@ class PostHogFetchHttpError extends Error {
50
51
  get status() {
51
52
  return this.response.status;
52
53
  }
54
+ get retryAfterMs() {
55
+ try {
56
+ return (0, retry_after_js_namespaceObject.parseRetryAfterMs)(this.response.headers?.get('retry-after'));
57
+ } catch {
58
+ return;
59
+ }
60
+ }
53
61
  get bodyReadTimedOut() {
54
62
  return this._bodyReadTimedOut;
55
63
  }
@@ -132,6 +140,16 @@ function isRetryableFlagsFetchError(err) {
132
140
  const code = cause?.code ?? cause?.cause?.code;
133
141
  return 'ECONNREFUSED' !== code;
134
142
  }
143
+ const OTLP_MAX_BODY_BYTES = 10485760;
144
+ function byteLengthOf(body) {
145
+ try {
146
+ if ('string' != typeof body) return body instanceof Uint8Array ? body.byteLength : body.size;
147
+ if ("u" > typeof Buffer) return Buffer.byteLength(body, index_js_namespaceObject.STRING_FORMAT);
148
+ return new TextEncoder().encode(body).length;
149
+ } catch {
150
+ return 0;
151
+ }
152
+ }
135
153
  function isPostHogFetchContentTooLargeError(err) {
136
154
  return 'object' == typeof err && err instanceof PostHogFetchHttpError && 413 === err.status;
137
155
  }
@@ -686,10 +704,13 @@ class PostHogCoreStateless {
686
704
  }
687
705
  flushBackground() {
688
706
  if (this.pendingFlushPromise) return;
689
- this.flush().catch(async (err)=>{
707
+ this.flushAutomatic().catch(async (err)=>{
690
708
  await logFlushError(err);
691
709
  });
692
710
  }
711
+ flushAutomatic() {
712
+ return this.flush();
713
+ }
693
714
  async waitForPendingPromises(maxPromiseId, ignoredPromises = []) {
694
715
  const ignoredPendingPromises = ignoredPromises.filter((promise)=>!!promise);
695
716
  let iteration = 0;
@@ -847,24 +868,45 @@ class PostHogCoreStateless {
847
868
  sentFromRoute += batchMessages.length;
848
869
  }
849
870
  }
850
- async _sendOtlpBatch({ path, payload }) {
871
+ async _sendOtlpBatch({ path, auth, payload }) {
851
872
  if (this.disabled) return {
852
873
  kind: 'fatal',
853
874
  error: new Error('The client is disabled')
854
875
  };
855
- const serialized = JSON.stringify(payload);
856
- const url = `${this.host}/i/v1/${path}?token=${encodeURIComponent(this.apiKey)}`;
876
+ let serialized;
877
+ try {
878
+ serialized = JSON.stringify(payload);
879
+ } catch (error) {
880
+ this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${path} batch; reporting it as too large`, error));
881
+ return {
882
+ kind: 'too-large',
883
+ measuredLocally: true
884
+ };
885
+ }
886
+ const payloadBytes = byteLengthOf(serialized);
887
+ if (payloadBytes > OTLP_MAX_BODY_BYTES) {
888
+ this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${path} batch of ${payloadBytes} bytes: the endpoint accepts at most ${OTLP_MAX_BODY_BYTES}`));
889
+ return {
890
+ kind: 'too-large',
891
+ measuredLocally: true
892
+ };
893
+ }
894
+ const url = 'bearer' === auth ? `${this.host}/i/v1/${path}` : `${this.host}/i/v1/${path}?token=${encodeURIComponent(this.apiKey)}`;
857
895
  const gzippedPayload = this.disableCompression ? null : await this.compressPayload(serialized);
896
+ const body = gzippedPayload || serialized;
858
897
  const fetchOptions = {
859
898
  method: 'POST',
860
899
  headers: {
861
900
  ...this.getCustomHeaders(),
862
901
  'Content-Type': 'application/json',
902
+ ...'bearer' === auth && {
903
+ Authorization: `Bearer ${this.apiKey}`
904
+ },
863
905
  ...null !== gzippedPayload && {
864
906
  'Content-Encoding': 'gzip'
865
907
  }
866
908
  },
867
- body: gzippedPayload || serialized
909
+ body
868
910
  };
869
911
  try {
870
912
  await this.fetchWithRetry(url, fetchOptions, {
@@ -872,6 +914,7 @@ class PostHogCoreStateless {
872
914
  }, {
873
915
  retryCheck: (err)=>{
874
916
  if (isPostHogFetchContentTooLargeError(err)) return false;
917
+ if (err instanceof PostHogFetchHttpError && void 0 !== err.retryAfterMs) return false;
875
918
  return isPostHogFetchRetryableError(err);
876
919
  }
877
920
  });
@@ -882,10 +925,16 @@ class PostHogCoreStateless {
882
925
  if (isPostHogFetchContentTooLargeError(err)) return {
883
926
  kind: 'too-large'
884
927
  };
885
- if (isPostHogFetchRetryableError(err)) return {
886
- kind: 'retry-later',
887
- error: err
888
- };
928
+ if (isPostHogFetchRetryableError(err)) {
929
+ const retryAfterMs = err instanceof PostHogFetchHttpError ? err.retryAfterMs : void 0;
930
+ return {
931
+ kind: 'retry-later',
932
+ error: err,
933
+ ...void 0 !== retryAfterMs && {
934
+ retryAfterMs
935
+ }
936
+ };
937
+ }
889
938
  return {
890
939
  kind: 'fatal',
891
940
  error: err
@@ -895,28 +944,27 @@ class PostHogCoreStateless {
895
944
  async _sendLogsBatch(payload) {
896
945
  return this._sendOtlpBatch({
897
946
  path: 'logs',
947
+ auth: 'query-token',
898
948
  payload
899
949
  });
900
950
  }
901
951
  async _sendMetricsBatch(payload) {
902
952
  return this._sendOtlpBatch({
903
953
  path: 'metrics',
954
+ auth: 'query-token',
955
+ payload
956
+ });
957
+ }
958
+ async _sendTracesBatch(payload) {
959
+ return this._sendOtlpBatch({
960
+ path: 'traces',
961
+ auth: 'bearer',
904
962
  payload
905
963
  });
906
964
  }
907
965
  async fetchWithRetry(url, options, responseHandling, retryOptions, requestTimeout) {
908
966
  const body = options.body ? options.body : '';
909
- let reqByteLength = -1;
910
- try {
911
- reqByteLength = body instanceof Blob ? body.size : body instanceof Uint8Array ? body.byteLength : Buffer.byteLength(body, index_js_namespaceObject.STRING_FORMAT);
912
- } catch {
913
- if (body instanceof Blob) reqByteLength = body.size;
914
- else if (body instanceof Uint8Array) reqByteLength = body.byteLength;
915
- else {
916
- const encoded = new TextEncoder().encode(body);
917
- reqByteLength = encoded.length;
918
- }
919
- }
967
+ const reqByteLength = byteLengthOf(body);
920
968
  const retriableOptions = {
921
969
  ...this._retryOptions,
922
970
  ...retryOptions
@@ -3,6 +3,7 @@ import { getFeatureFlagValue, minimizeFlagCalledEventProperties, normalizeFlagsR
3
3
  import { gzipCompress, isGzipSupported } from "./gzip.mjs";
4
4
  import { PostHogPersistedProperty } from "./types.mjs";
5
5
  import { PromiseQueue, STRING_FORMAT, allSettled, createLogger, createNamedError, currentISOTime, getEventUuid, raceWithTimeout, removeTrailingSlash, retriable, safeJsonStringify, safeSetTimeout } from "./utils/index.mjs";
6
+ import { parseRetryAfterMs } from "./utils/retry-after.mjs";
6
7
  import { uuidv7 } from "./vendor/uuidv7.mjs";
7
8
  import { ErrorCoercer, ErrorPropertiesBuilder, ObjectCoercer, PrimitiveCoercer, StringCoercer, createDefaultStackParser } from "./error-tracking/index.mjs";
8
9
  class PostHogFetchHttpError extends Error {
@@ -12,6 +13,13 @@ class PostHogFetchHttpError extends Error {
12
13
  get status() {
13
14
  return this.response.status;
14
15
  }
16
+ get retryAfterMs() {
17
+ try {
18
+ return parseRetryAfterMs(this.response.headers?.get('retry-after'));
19
+ } catch {
20
+ return;
21
+ }
22
+ }
15
23
  get bodyReadTimedOut() {
16
24
  return this._bodyReadTimedOut;
17
25
  }
@@ -94,6 +102,16 @@ function isRetryableFlagsFetchError(err) {
94
102
  const code = cause?.code ?? cause?.cause?.code;
95
103
  return 'ECONNREFUSED' !== code;
96
104
  }
105
+ const OTLP_MAX_BODY_BYTES = 10485760;
106
+ function byteLengthOf(body) {
107
+ try {
108
+ if ('string' != typeof body) return body instanceof Uint8Array ? body.byteLength : body.size;
109
+ if ("u" > typeof Buffer) return Buffer.byteLength(body, STRING_FORMAT);
110
+ return new TextEncoder().encode(body).length;
111
+ } catch {
112
+ return 0;
113
+ }
114
+ }
97
115
  function isPostHogFetchContentTooLargeError(err) {
98
116
  return 'object' == typeof err && err instanceof PostHogFetchHttpError && 413 === err.status;
99
117
  }
@@ -648,10 +666,13 @@ class PostHogCoreStateless {
648
666
  }
649
667
  flushBackground() {
650
668
  if (this.pendingFlushPromise) return;
651
- this.flush().catch(async (err)=>{
669
+ this.flushAutomatic().catch(async (err)=>{
652
670
  await logFlushError(err);
653
671
  });
654
672
  }
673
+ flushAutomatic() {
674
+ return this.flush();
675
+ }
655
676
  async waitForPendingPromises(maxPromiseId, ignoredPromises = []) {
656
677
  const ignoredPendingPromises = ignoredPromises.filter((promise)=>!!promise);
657
678
  let iteration = 0;
@@ -809,24 +830,45 @@ class PostHogCoreStateless {
809
830
  sentFromRoute += batchMessages.length;
810
831
  }
811
832
  }
812
- async _sendOtlpBatch({ path, payload }) {
833
+ async _sendOtlpBatch({ path, auth, payload }) {
813
834
  if (this.disabled) return {
814
835
  kind: 'fatal',
815
836
  error: new Error('The client is disabled')
816
837
  };
817
- const serialized = JSON.stringify(payload);
818
- const url = `${this.host}/i/v1/${path}?token=${encodeURIComponent(this.apiKey)}`;
838
+ let serialized;
839
+ try {
840
+ serialized = JSON.stringify(payload);
841
+ } catch (error) {
842
+ this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${path} batch; reporting it as too large`, error));
843
+ return {
844
+ kind: 'too-large',
845
+ measuredLocally: true
846
+ };
847
+ }
848
+ const payloadBytes = byteLengthOf(serialized);
849
+ if (payloadBytes > OTLP_MAX_BODY_BYTES) {
850
+ this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${path} batch of ${payloadBytes} bytes: the endpoint accepts at most ${OTLP_MAX_BODY_BYTES}`));
851
+ return {
852
+ kind: 'too-large',
853
+ measuredLocally: true
854
+ };
855
+ }
856
+ const url = 'bearer' === auth ? `${this.host}/i/v1/${path}` : `${this.host}/i/v1/${path}?token=${encodeURIComponent(this.apiKey)}`;
819
857
  const gzippedPayload = this.disableCompression ? null : await this.compressPayload(serialized);
858
+ const body = gzippedPayload || serialized;
820
859
  const fetchOptions = {
821
860
  method: 'POST',
822
861
  headers: {
823
862
  ...this.getCustomHeaders(),
824
863
  'Content-Type': 'application/json',
864
+ ...'bearer' === auth && {
865
+ Authorization: `Bearer ${this.apiKey}`
866
+ },
825
867
  ...null !== gzippedPayload && {
826
868
  'Content-Encoding': 'gzip'
827
869
  }
828
870
  },
829
- body: gzippedPayload || serialized
871
+ body
830
872
  };
831
873
  try {
832
874
  await this.fetchWithRetry(url, fetchOptions, {
@@ -834,6 +876,7 @@ class PostHogCoreStateless {
834
876
  }, {
835
877
  retryCheck: (err)=>{
836
878
  if (isPostHogFetchContentTooLargeError(err)) return false;
879
+ if (err instanceof PostHogFetchHttpError && void 0 !== err.retryAfterMs) return false;
837
880
  return isPostHogFetchRetryableError(err);
838
881
  }
839
882
  });
@@ -844,10 +887,16 @@ class PostHogCoreStateless {
844
887
  if (isPostHogFetchContentTooLargeError(err)) return {
845
888
  kind: 'too-large'
846
889
  };
847
- if (isPostHogFetchRetryableError(err)) return {
848
- kind: 'retry-later',
849
- error: err
850
- };
890
+ if (isPostHogFetchRetryableError(err)) {
891
+ const retryAfterMs = err instanceof PostHogFetchHttpError ? err.retryAfterMs : void 0;
892
+ return {
893
+ kind: 'retry-later',
894
+ error: err,
895
+ ...void 0 !== retryAfterMs && {
896
+ retryAfterMs
897
+ }
898
+ };
899
+ }
851
900
  return {
852
901
  kind: 'fatal',
853
902
  error: err
@@ -857,28 +906,27 @@ class PostHogCoreStateless {
857
906
  async _sendLogsBatch(payload) {
858
907
  return this._sendOtlpBatch({
859
908
  path: 'logs',
909
+ auth: 'query-token',
860
910
  payload
861
911
  });
862
912
  }
863
913
  async _sendMetricsBatch(payload) {
864
914
  return this._sendOtlpBatch({
865
915
  path: 'metrics',
916
+ auth: 'query-token',
917
+ payload
918
+ });
919
+ }
920
+ async _sendTracesBatch(payload) {
921
+ return this._sendOtlpBatch({
922
+ path: 'traces',
923
+ auth: 'bearer',
866
924
  payload
867
925
  });
868
926
  }
869
927
  async fetchWithRetry(url, options, responseHandling, retryOptions, requestTimeout) {
870
928
  const body = options.body ? options.body : '';
871
- let reqByteLength = -1;
872
- try {
873
- reqByteLength = body instanceof Blob ? body.size : body instanceof Uint8Array ? body.byteLength : Buffer.byteLength(body, STRING_FORMAT);
874
- } catch {
875
- if (body instanceof Blob) reqByteLength = body.size;
876
- else if (body instanceof Uint8Array) reqByteLength = body.byteLength;
877
- else {
878
- const encoded = new TextEncoder().encode(body);
879
- reqByteLength = encoded.length;
880
- }
881
- }
929
+ const reqByteLength = byteLengthOf(body);
882
930
  const retriableOptions = {
883
931
  ...this._retryOptions,
884
932
  ...retryOptions
@@ -0,0 +1,13 @@
1
+ import type { ResolvedTracesConfig } from './types';
2
+ import type { TracesConfig } from '@posthog/types';
3
+ import type { Logger } from '../types';
4
+ /**
5
+ * Resolves the public `traces` config into the shape core `PostHogTraces` consumes.
6
+ * OTLP resource attributes take precedence over the named fields, matching the
7
+ * logs config. `hostResourceAttributes` are runtime-detected by the entrypoint and
8
+ * merge first, so a user-supplied value of the same key wins.
9
+ *
10
+ * @internal Exposed for cross-package use within this SDK; not part of the stable public API.
11
+ */
12
+ export declare function resolveTracesConfig(config: TracesConfig | undefined, hostResourceAttributes?: Record<string, string>, logger?: Logger): ResolvedTracesConfig;
13
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/traces/config.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AACnD,OAAO,KAAK,EAAoB,YAAY,EAAE,MAAM,gBAAgB,CAAA;AACpE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,CAAA;AAqGtC;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,YAAY,GAAG,SAAS,EAChC,sBAAsB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAC/C,MAAM,CAAC,EAAE,MAAM,GACd,oBAAoB,CAyBtB"}
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, getters, values)=>{
5
+ var define = (defs, kind)=>{
6
+ for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
7
+ enumerable: true,
8
+ [kind]: defs[key]
9
+ });
10
+ };
11
+ define(getters, "get");
12
+ define(values, "value");
13
+ };
14
+ })();
15
+ (()=>{
16
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
17
+ })();
18
+ (()=>{
19
+ __webpack_require__.r = (exports1)=>{
20
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
21
+ value: 'Module'
22
+ });
23
+ Object.defineProperty(exports1, '__esModule', {
24
+ value: true
25
+ });
26
+ };
27
+ })();
28
+ var __webpack_exports__ = {};
29
+ __webpack_require__.r(__webpack_exports__);
30
+ __webpack_require__.d(__webpack_exports__, {
31
+ resolveTracesConfig: ()=>resolveTracesConfig
32
+ });
33
+ const json_utils_js_namespaceObject = require("../utils/json-utils.js");
34
+ const DEFAULT_FLUSH_INTERVAL_MS = 5000;
35
+ const DEFAULT_MAX_EXPORT_BATCH_SIZE = 512;
36
+ const DEFAULT_MAX_QUEUE_SIZE = 2048;
37
+ const DEFAULT_MAX_ATTRIBUTES_PER_SPAN = 128;
38
+ const DEFAULT_MAX_EVENTS_PER_SPAN = 128;
39
+ const DEFAULT_MAX_ATTRIBUTES_PER_EVENT = 128;
40
+ const DEFAULT_MAX_ATTRIBUTE_VALUE_LENGTH = 8192;
41
+ const DEFAULT_MAX_LIVE_SPANS = 10000;
42
+ const DEFAULT_MAX_SPAN_AGE_MS = 3600000;
43
+ function positiveInteger(value, fallback) {
44
+ return 'number' == typeof value && Number.isInteger(value) && value >= 1 ? value : fallback;
45
+ }
46
+ const IDENTITY_KEYS = [
47
+ 'service.name',
48
+ 'service.version',
49
+ 'deployment.environment'
50
+ ];
51
+ function withUsableIdentityKeys(attributes) {
52
+ if (!attributes || 'object' != typeof attributes || Array.isArray(attributes)) return;
53
+ try {
54
+ if (IDENTITY_KEYS.every((key)=>!(key in attributes) || 'string' == typeof attributes[key])) return attributes;
55
+ const usable = {
56
+ ...attributes
57
+ };
58
+ for (const key of IDENTITY_KEYS)if (key in usable && 'string' != typeof usable[key]) delete usable[key];
59
+ return usable;
60
+ } catch {
61
+ return;
62
+ }
63
+ }
64
+ function resolveBeforeSpanSend(beforeSpanSend, logger) {
65
+ if (!beforeSpanSend) return [];
66
+ const supplied = [
67
+ beforeSpanSend
68
+ ].flat().filter((hook)=>Boolean(hook));
69
+ const hooks = supplied.filter((hook)=>'function' == typeof hook);
70
+ if (hooks.length !== supplied.length) logger?.critical(`beforeSpanSend: ignoring ${supplied.length - hooks.length} of ${supplied.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`);
71
+ return hooks;
72
+ }
73
+ function resolveTracesConfig(config, hostResourceAttributes, logger) {
74
+ const resourceAttributes = (0, json_utils_js_namespaceObject.assignUserAttributes)({
75
+ ...hostResourceAttributes
76
+ }, withUsableIdentityKeys(config?.resourceAttributes));
77
+ const maxExportBatchSize = positiveInteger(config?.maxExportBatchSize, DEFAULT_MAX_EXPORT_BATCH_SIZE);
78
+ return {
79
+ serviceName: resourceAttributes?.['service.name'] ?? config?.serviceName,
80
+ serviceVersion: resourceAttributes?.['service.version'] ?? config?.serviceVersion,
81
+ environment: resourceAttributes?.['deployment.environment'] ?? config?.environment,
82
+ resourceAttributes,
83
+ beforeSpanSend: resolveBeforeSpanSend(config?.beforeSpanSend, logger),
84
+ maxAttributesPerSpan: positiveInteger(config?.maxAttributesPerSpan, DEFAULT_MAX_ATTRIBUTES_PER_SPAN),
85
+ maxEventsPerSpan: positiveInteger(config?.maxEventsPerSpan, DEFAULT_MAX_EVENTS_PER_SPAN),
86
+ maxAttributesPerEvent: DEFAULT_MAX_ATTRIBUTES_PER_EVENT,
87
+ maxAttributeValueLength: positiveInteger(config?.maxAttributeValueLength, DEFAULT_MAX_ATTRIBUTE_VALUE_LENGTH),
88
+ flushIntervalMs: positiveInteger(config?.flushIntervalMs, DEFAULT_FLUSH_INTERVAL_MS),
89
+ maxExportBatchSize,
90
+ maxQueueSize: Math.max(positiveInteger(config?.maxQueueSize, DEFAULT_MAX_QUEUE_SIZE), maxExportBatchSize),
91
+ maxLiveSpans: positiveInteger(config?.maxLiveSpans, DEFAULT_MAX_LIVE_SPANS),
92
+ maxSpanAgeMs: positiveInteger(config?.maxSpanAgeMs, DEFAULT_MAX_SPAN_AGE_MS)
93
+ };
94
+ }
95
+ exports.resolveTracesConfig = __webpack_exports__.resolveTracesConfig;
96
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
97
+ "resolveTracesConfig"
98
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
99
+ Object.defineProperty(exports, '__esModule', {
100
+ value: true
101
+ });
@@ -0,0 +1,63 @@
1
+ import { assignUserAttributes } from "../utils/json-utils.mjs";
2
+ const DEFAULT_FLUSH_INTERVAL_MS = 5000;
3
+ const DEFAULT_MAX_EXPORT_BATCH_SIZE = 512;
4
+ const DEFAULT_MAX_QUEUE_SIZE = 2048;
5
+ const DEFAULT_MAX_ATTRIBUTES_PER_SPAN = 128;
6
+ const DEFAULT_MAX_EVENTS_PER_SPAN = 128;
7
+ const DEFAULT_MAX_ATTRIBUTES_PER_EVENT = 128;
8
+ const DEFAULT_MAX_ATTRIBUTE_VALUE_LENGTH = 8192;
9
+ const DEFAULT_MAX_LIVE_SPANS = 10000;
10
+ const DEFAULT_MAX_SPAN_AGE_MS = 3600000;
11
+ function positiveInteger(value, fallback) {
12
+ return 'number' == typeof value && Number.isInteger(value) && value >= 1 ? value : fallback;
13
+ }
14
+ const IDENTITY_KEYS = [
15
+ 'service.name',
16
+ 'service.version',
17
+ 'deployment.environment'
18
+ ];
19
+ function withUsableIdentityKeys(attributes) {
20
+ if (!attributes || 'object' != typeof attributes || Array.isArray(attributes)) return;
21
+ try {
22
+ if (IDENTITY_KEYS.every((key)=>!(key in attributes) || 'string' == typeof attributes[key])) return attributes;
23
+ const usable = {
24
+ ...attributes
25
+ };
26
+ for (const key of IDENTITY_KEYS)if (key in usable && 'string' != typeof usable[key]) delete usable[key];
27
+ return usable;
28
+ } catch {
29
+ return;
30
+ }
31
+ }
32
+ function resolveBeforeSpanSend(beforeSpanSend, logger) {
33
+ if (!beforeSpanSend) return [];
34
+ const supplied = [
35
+ beforeSpanSend
36
+ ].flat().filter((hook)=>Boolean(hook));
37
+ const hooks = supplied.filter((hook)=>'function' == typeof hook);
38
+ if (hooks.length !== supplied.length) logger?.critical(`beforeSpanSend: ignoring ${supplied.length - hooks.length} of ${supplied.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`);
39
+ return hooks;
40
+ }
41
+ function resolveTracesConfig(config, hostResourceAttributes, logger) {
42
+ const resourceAttributes = assignUserAttributes({
43
+ ...hostResourceAttributes
44
+ }, withUsableIdentityKeys(config?.resourceAttributes));
45
+ const maxExportBatchSize = positiveInteger(config?.maxExportBatchSize, DEFAULT_MAX_EXPORT_BATCH_SIZE);
46
+ return {
47
+ serviceName: resourceAttributes?.['service.name'] ?? config?.serviceName,
48
+ serviceVersion: resourceAttributes?.['service.version'] ?? config?.serviceVersion,
49
+ environment: resourceAttributes?.['deployment.environment'] ?? config?.environment,
50
+ resourceAttributes,
51
+ beforeSpanSend: resolveBeforeSpanSend(config?.beforeSpanSend, logger),
52
+ maxAttributesPerSpan: positiveInteger(config?.maxAttributesPerSpan, DEFAULT_MAX_ATTRIBUTES_PER_SPAN),
53
+ maxEventsPerSpan: positiveInteger(config?.maxEventsPerSpan, DEFAULT_MAX_EVENTS_PER_SPAN),
54
+ maxAttributesPerEvent: DEFAULT_MAX_ATTRIBUTES_PER_EVENT,
55
+ maxAttributeValueLength: positiveInteger(config?.maxAttributeValueLength, DEFAULT_MAX_ATTRIBUTE_VALUE_LENGTH),
56
+ flushIntervalMs: positiveInteger(config?.flushIntervalMs, DEFAULT_FLUSH_INTERVAL_MS),
57
+ maxExportBatchSize,
58
+ maxQueueSize: Math.max(positiveInteger(config?.maxQueueSize, DEFAULT_MAX_QUEUE_SIZE), maxExportBatchSize),
59
+ maxLiveSpans: positiveInteger(config?.maxLiveSpans, DEFAULT_MAX_LIVE_SPANS),
60
+ maxSpanAgeMs: positiveInteger(config?.maxSpanAgeMs, DEFAULT_MAX_SPAN_AGE_MS)
61
+ };
62
+ }
63
+ export { resolveTracesConfig };
@@ -0,0 +1,18 @@
1
+ import type { Span } from '@posthog/types';
2
+ import type { SpanContextManager } from './types';
3
+ /**
4
+ * Synchronous active-span tracking: restores the previous active span when the
5
+ * callback returns, which for an async callback means when it returns its
6
+ * promise — so spans started after an `await` won't see it as active.
7
+ *
8
+ * The fallback for runtimes with no ambient async context; Node injects an
9
+ * `AsyncLocalStorage`-backed manager instead. `parent` is the escape hatch.
10
+ *
11
+ * @internal Exposed for cross-package use within this SDK; not part of the stable public API.
12
+ */
13
+ export declare class SyncSpanContextManager implements SpanContextManager {
14
+ private _active;
15
+ active(): Span | undefined;
16
+ with<T>(span: Span, fn: () => T): T;
17
+ }
18
+ //# sourceMappingURL=context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../src/traces/context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAA;AAC1C,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAA;AAEjD;;;;;;;;;GASG;AACH,qBAAa,sBAAuB,YAAW,kBAAkB;IAC/D,OAAO,CAAC,OAAO,CAAkB;IAEjC,MAAM,IAAI,IAAI,GAAG,SAAS;IAI1B,IAAI,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC;CASpC"}
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, getters, values)=>{
5
+ var define = (defs, kind)=>{
6
+ for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
7
+ enumerable: true,
8
+ [kind]: defs[key]
9
+ });
10
+ };
11
+ define(getters, "get");
12
+ define(values, "value");
13
+ };
14
+ })();
15
+ (()=>{
16
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
17
+ })();
18
+ (()=>{
19
+ __webpack_require__.r = (exports1)=>{
20
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
21
+ value: 'Module'
22
+ });
23
+ Object.defineProperty(exports1, '__esModule', {
24
+ value: true
25
+ });
26
+ };
27
+ })();
28
+ var __webpack_exports__ = {};
29
+ __webpack_require__.r(__webpack_exports__);
30
+ class SyncSpanContextManager {
31
+ active() {
32
+ return this._active;
33
+ }
34
+ with(span, fn) {
35
+ const previous = this._active;
36
+ this._active = span;
37
+ try {
38
+ return fn();
39
+ } finally{
40
+ this._active = previous;
41
+ }
42
+ }
43
+ }
44
+ __webpack_require__.d(__webpack_exports__, {
45
+ SyncSpanContextManager: ()=>SyncSpanContextManager
46
+ });
47
+ exports.SyncSpanContextManager = __webpack_exports__.SyncSpanContextManager;
48
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
49
+ "SyncSpanContextManager"
50
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
51
+ Object.defineProperty(exports, '__esModule', {
52
+ value: true
53
+ });
@@ -0,0 +1,15 @@
1
+ class SyncSpanContextManager {
2
+ active() {
3
+ return this._active;
4
+ }
5
+ with(span, fn) {
6
+ const previous = this._active;
7
+ this._active = span;
8
+ try {
9
+ return fn();
10
+ } finally{
11
+ this._active = previous;
12
+ }
13
+ }
14
+ }
15
+ export { SyncSpanContextManager };
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Random bytes from the platform's CSPRNG, falling back to `Math.random`.
3
+ *
4
+ * The fallback exists for React Native, which has no global `crypto` without a
5
+ * polyfill. Trace ids need collision resistance, not unpredictability.
6
+ */
7
+ export declare function getRandomBytes(byteLength: number): Uint8Array;
8
+ export declare function newTraceId(): string;
9
+ export declare function newSpanId(): string;
10
+ export declare function isValidTraceId(value: unknown): value is string;
11
+ export declare function isValidSpanId(value: unknown): value is string;
12
+ //# sourceMappingURL=ids.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ids.d.ts","sourceRoot":"","sources":["../../src/traces/ids.ts"],"names":[],"mappings":"AAkBA;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,UAAU,EAAE,MAAM,GAAG,UAAU,CAe7D;AAiBD,wBAAgB,UAAU,IAAI,MAAM,CAEnC;AAED,wBAAgB,SAAS,IAAI,MAAM,CAElC;AAMD,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAE9D;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAE7D"}