@datadog/mobile-react-native 3.5.3 → 3.6.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 (206) hide show
  1. package/README.md +10 -0
  2. package/android/build.gradle +22 -8
  3. package/android/src/main/kotlin/com/datadog/reactnative/DdRumImplementation.kt +23 -4
  4. package/android/src/main/kotlin/com/datadog/reactnative/DdSdkNativeInitialization.kt +3 -2
  5. package/android/src/main/kotlin/com/datadog/reactnative/HeatmapActionHandler.kt +121 -0
  6. package/android/src/main/kotlin/com/datadog/reactnative/HeatmapTouchResolver.kt +108 -0
  7. package/android/src/main/kotlin/com/datadog/reactnative/SdkVersion.kt +1 -1
  8. package/android/src/newarch/kotlin/com/datadog/reactnative/DdRum.kt +19 -2
  9. package/android/src/newarch/kotlin/com/datadog/reactnative/DdSdk.kt +1 -1
  10. package/android/src/oldarch/kotlin/com/datadog/reactnative/HeatmapViewResolverFactory.kt +38 -0
  11. package/android/src/oldarch65/kotlin/com/datadog/reactnative/HeatmapViewResolverFactory.kt +20 -0
  12. package/android/src/{oldarch → oldarchCommon}/kotlin/com/datadog/reactnative/DdRum.kt +15 -2
  13. package/android/src/test/kotlin/com/datadog/reactnative/DdRumTest.kt +482 -0
  14. package/android/src/test/kotlin/com/datadog/reactnative/DdSdkTest.kt +94 -49
  15. package/android/src/test/kotlin/com/datadog/reactnative/HeatmapTouchResolverTest.kt +529 -0
  16. package/datadog-configuration.schema.json +4 -0
  17. package/ios/Sources/DdSdk.mm +2 -0
  18. package/ios/Sources/DdSdkImplementation.swift +0 -1
  19. package/ios/Sources/SdkVersion.swift +1 -1
  20. package/lib/commonjs/DdSdkReactNative.js +3 -1
  21. package/lib/commonjs/DdSdkReactNative.js.map +1 -1
  22. package/lib/commonjs/config/FileBasedConfiguration.js +1 -0
  23. package/lib/commonjs/config/FileBasedConfiguration.js.map +1 -1
  24. package/lib/commonjs/config/async/AutoInstrumentationConfiguration.js +1 -0
  25. package/lib/commonjs/config/async/AutoInstrumentationConfiguration.js.map +1 -1
  26. package/lib/commonjs/config/features/RumConfiguration.js +4 -0
  27. package/lib/commonjs/config/features/RumConfiguration.js.map +1 -1
  28. package/lib/commonjs/flags/FlagsClient.js +268 -3
  29. package/lib/commonjs/flags/FlagsClient.js.map +1 -1
  30. package/lib/commonjs/flags/configuration/context.js +70 -0
  31. package/lib/commonjs/flags/configuration/context.js.map +1 -0
  32. package/lib/commonjs/flags/configuration/index.js +39 -0
  33. package/lib/commonjs/flags/configuration/index.js.map +1 -0
  34. package/lib/commonjs/flags/configuration/precomputed.js +172 -0
  35. package/lib/commonjs/flags/configuration/precomputed.js.map +1 -0
  36. package/lib/commonjs/flags/configuration/types.js +33 -0
  37. package/lib/commonjs/flags/configuration/types.js.map +1 -0
  38. package/lib/commonjs/flags/configuration/wire.js +19 -0
  39. package/lib/commonjs/flags/configuration/wire.js.map +1 -0
  40. package/lib/commonjs/flags/internal.js +7 -3
  41. package/lib/commonjs/flags/internal.js.map +1 -1
  42. package/lib/commonjs/index.js +13 -0
  43. package/lib/commonjs/index.js.map +1 -1
  44. package/lib/commonjs/rum/instrumentation/resourceTracking/DdRumResourceTracking.js +27 -13
  45. package/lib/commonjs/rum/instrumentation/resourceTracking/DdRumResourceTracking.js.map +1 -1
  46. package/lib/commonjs/rum/instrumentation/resourceTracking/requestProxy/FetchProxy/FetchProxy.js +270 -0
  47. package/lib/commonjs/rum/instrumentation/resourceTracking/requestProxy/FetchProxy/FetchProxy.js.map +1 -0
  48. package/lib/commonjs/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/XHRProxy.js +38 -72
  49. package/lib/commonjs/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/XHRProxy.js.map +1 -1
  50. package/lib/commonjs/rum/instrumentation/resourceTracking/requestProxy/common/FetchProxyState.js +33 -0
  51. package/lib/commonjs/rum/instrumentation/resourceTracking/requestProxy/common/FetchProxyState.js.map +1 -0
  52. package/lib/commonjs/rum/instrumentation/resourceTracking/requestProxy/common/RequestContext.js +39 -0
  53. package/lib/commonjs/rum/instrumentation/resourceTracking/requestProxy/common/RequestContext.js.map +1 -0
  54. package/lib/commonjs/rum/instrumentation/resourceTracking/requestProxy/{XHRProxy/DatadogRumResource → common}/ResourceReporter.js +4 -4
  55. package/lib/commonjs/rum/instrumentation/resourceTracking/requestProxy/common/ResourceReporter.js.map +1 -0
  56. package/lib/commonjs/rum/instrumentation/resourceTracking/requestProxy/{XHRProxy/DatadogRumResource → common}/internalDevResourceBlocklist.js +0 -18
  57. package/lib/commonjs/rum/instrumentation/resourceTracking/requestProxy/common/internalDevResourceBlocklist.js.map +1 -0
  58. package/lib/commonjs/rum/instrumentation/resourceTracking/requestProxy/common/requestHeaders.js +109 -0
  59. package/lib/commonjs/rum/instrumentation/resourceTracking/requestProxy/common/requestHeaders.js.map +1 -0
  60. package/lib/commonjs/rum/instrumentation/resourceTracking/requestProxy/{XHRProxy/DatadogRumResource → common}/resourceTiming.js +0 -9
  61. package/lib/commonjs/rum/instrumentation/resourceTracking/requestProxy/common/resourceTiming.js.map +1 -0
  62. package/lib/commonjs/version.js +1 -1
  63. package/lib/module/DdSdkReactNative.js +3 -1
  64. package/lib/module/DdSdkReactNative.js.map +1 -1
  65. package/lib/module/config/FileBasedConfiguration.js +1 -0
  66. package/lib/module/config/FileBasedConfiguration.js.map +1 -1
  67. package/lib/module/config/async/AutoInstrumentationConfiguration.js +1 -0
  68. package/lib/module/config/async/AutoInstrumentationConfiguration.js.map +1 -1
  69. package/lib/module/config/features/RumConfiguration.js +4 -0
  70. package/lib/module/config/features/RumConfiguration.js.map +1 -1
  71. package/lib/module/flags/FlagsClient.js +268 -3
  72. package/lib/module/flags/FlagsClient.js.map +1 -1
  73. package/lib/module/flags/configuration/context.js +62 -0
  74. package/lib/module/flags/configuration/context.js.map +1 -0
  75. package/lib/module/flags/configuration/index.js +18 -0
  76. package/lib/module/flags/configuration/index.js.map +1 -0
  77. package/lib/module/flags/configuration/precomputed.js +165 -0
  78. package/lib/module/flags/configuration/precomputed.js.map +1 -0
  79. package/lib/module/flags/configuration/types.js +27 -0
  80. package/lib/module/flags/configuration/types.js.map +1 -0
  81. package/lib/module/flags/configuration/wire.js +13 -0
  82. package/lib/module/flags/configuration/wire.js.map +1 -0
  83. package/lib/module/flags/internal.js +7 -3
  84. package/lib/module/flags/internal.js.map +1 -1
  85. package/lib/module/index.js +2 -1
  86. package/lib/module/index.js.map +1 -1
  87. package/lib/module/rum/instrumentation/resourceTracking/DdRumResourceTracking.js +27 -13
  88. package/lib/module/rum/instrumentation/resourceTracking/DdRumResourceTracking.js.map +1 -1
  89. package/lib/module/rum/instrumentation/resourceTracking/requestProxy/FetchProxy/FetchProxy.js +263 -0
  90. package/lib/module/rum/instrumentation/resourceTracking/requestProxy/FetchProxy/FetchProxy.js.map +1 -0
  91. package/lib/module/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/XHRProxy.js +38 -72
  92. package/lib/module/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/XHRProxy.js.map +1 -1
  93. package/lib/module/rum/instrumentation/resourceTracking/requestProxy/common/FetchProxyState.js +25 -0
  94. package/lib/module/rum/instrumentation/resourceTracking/requestProxy/common/FetchProxyState.js.map +1 -0
  95. package/lib/module/rum/instrumentation/resourceTracking/requestProxy/common/RequestContext.js +32 -0
  96. package/lib/module/rum/instrumentation/resourceTracking/requestProxy/common/RequestContext.js.map +1 -0
  97. package/lib/module/rum/instrumentation/resourceTracking/requestProxy/{XHRProxy/DatadogRumResource → common}/ResourceReporter.js +4 -4
  98. package/lib/module/rum/instrumentation/resourceTracking/requestProxy/common/ResourceReporter.js.map +1 -0
  99. package/lib/module/rum/instrumentation/resourceTracking/requestProxy/{XHRProxy/DatadogRumResource → common}/internalDevResourceBlocklist.js +0 -18
  100. package/lib/module/rum/instrumentation/resourceTracking/requestProxy/common/internalDevResourceBlocklist.js.map +1 -0
  101. package/lib/module/rum/instrumentation/resourceTracking/requestProxy/common/requestHeaders.js +101 -0
  102. package/lib/module/rum/instrumentation/resourceTracking/requestProxy/common/requestHeaders.js.map +1 -0
  103. package/lib/module/rum/instrumentation/resourceTracking/requestProxy/{XHRProxy/DatadogRumResource → common}/resourceTiming.js +0 -9
  104. package/lib/module/rum/instrumentation/resourceTracking/requestProxy/common/resourceTiming.js.map +1 -0
  105. package/lib/module/version.js +1 -1
  106. package/lib/typescript/DdSdkReactNative.d.ts.map +1 -1
  107. package/lib/typescript/config/FileBasedConfiguration.d.ts.map +1 -1
  108. package/lib/typescript/config/FileBasedConfiguration.type.d.ts +1 -0
  109. package/lib/typescript/config/FileBasedConfiguration.type.d.ts.map +1 -1
  110. package/lib/typescript/config/async/AutoInstrumentationConfiguration.d.ts +2 -0
  111. package/lib/typescript/config/async/AutoInstrumentationConfiguration.d.ts.map +1 -1
  112. package/lib/typescript/config/features/RumConfiguration.d.ts +2 -0
  113. package/lib/typescript/config/features/RumConfiguration.d.ts.map +1 -1
  114. package/lib/typescript/config/features/RumConfiguration.type.d.ts +7 -0
  115. package/lib/typescript/config/features/RumConfiguration.type.d.ts.map +1 -1
  116. package/lib/typescript/flags/FlagsClient.d.ts +96 -0
  117. package/lib/typescript/flags/FlagsClient.d.ts.map +1 -1
  118. package/lib/typescript/flags/configuration/context.d.ts +20 -0
  119. package/lib/typescript/flags/configuration/context.d.ts.map +1 -0
  120. package/lib/typescript/flags/configuration/index.d.ts +5 -0
  121. package/lib/typescript/flags/configuration/index.d.ts.map +1 -0
  122. package/lib/typescript/flags/configuration/precomputed.d.ts +25 -0
  123. package/lib/typescript/flags/configuration/precomputed.d.ts.map +1 -0
  124. package/lib/typescript/flags/configuration/types.d.ts +24 -0
  125. package/lib/typescript/flags/configuration/types.d.ts.map +1 -0
  126. package/lib/typescript/flags/configuration/wire.d.ts +2 -0
  127. package/lib/typescript/flags/configuration/wire.d.ts.map +1 -0
  128. package/lib/typescript/flags/internal.d.ts.map +1 -1
  129. package/lib/typescript/flags/types.d.ts +1 -1
  130. package/lib/typescript/flags/types.d.ts.map +1 -1
  131. package/lib/typescript/index.d.ts +4 -2
  132. package/lib/typescript/index.d.ts.map +1 -1
  133. package/lib/typescript/rum/instrumentation/resourceTracking/DdRumResourceTracking.d.ts +3 -2
  134. package/lib/typescript/rum/instrumentation/resourceTracking/DdRumResourceTracking.d.ts.map +1 -1
  135. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/FetchProxy/FetchProxy.d.ts +29 -0
  136. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/FetchProxy/FetchProxy.d.ts.map +1 -0
  137. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/XHRProxy.d.ts +1 -1
  138. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/XHRProxy.d.ts.map +1 -1
  139. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/common/FetchProxyState.d.ts +8 -0
  140. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/common/FetchProxyState.d.ts.map +1 -0
  141. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/common/RequestContext.d.ts +20 -0
  142. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/common/RequestContext.d.ts.map +1 -0
  143. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/{XHRProxy/DatadogRumResource → common}/ResourceReporter.d.ts +2 -2
  144. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/common/ResourceReporter.d.ts.map +1 -0
  145. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/common/internalDevResourceBlocklist.d.ts +3 -0
  146. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/common/internalDevResourceBlocklist.d.ts.map +1 -0
  147. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/common/requestHeaders.d.ts +18 -0
  148. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/common/requestHeaders.d.ts.map +1 -0
  149. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/{XHRProxy/DatadogRumResource → common}/resourceTiming.d.ts +0 -6
  150. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/common/resourceTiming.d.ts.map +1 -0
  151. package/lib/typescript/version.d.ts +1 -1
  152. package/package.json +12 -2
  153. package/src/DdSdkReactNative.tsx +5 -1
  154. package/src/__tests__/DdSdkReactNative.test.tsx +5 -2
  155. package/src/__tests__/DdSdkReactNativeConfiguration.test.ts +3 -0
  156. package/src/config/FileBasedConfiguration.ts +2 -0
  157. package/src/config/FileBasedConfiguration.type.ts +1 -0
  158. package/src/config/__tests__/FileBasedConfiguration.test.ts +3 -0
  159. package/src/config/__tests__/__fixtures__/configuration-all-fields.json +1 -0
  160. package/src/config/async/AutoInstrumentationConfiguration.ts +5 -0
  161. package/src/config/features/RumConfiguration.ts +4 -0
  162. package/src/config/features/RumConfiguration.type.ts +8 -0
  163. package/src/flags/FlagsClient.ts +305 -3
  164. package/src/flags/__tests__/FlagsClient.test.ts +596 -0
  165. package/src/flags/__tests__/internal.test.ts +45 -0
  166. package/src/flags/configuration/__tests__/context.test.ts +120 -0
  167. package/src/flags/configuration/__tests__/precomputed.test.ts +301 -0
  168. package/src/flags/configuration/__tests__/wire.test.ts +127 -0
  169. package/src/flags/configuration/context.ts +76 -0
  170. package/src/flags/configuration/index.ts +27 -0
  171. package/src/flags/configuration/precomputed.ts +215 -0
  172. package/src/flags/configuration/types.ts +47 -0
  173. package/src/flags/configuration/wire.ts +15 -0
  174. package/src/flags/internal.ts +6 -3
  175. package/src/flags/types.ts +3 -1
  176. package/src/index.tsx +8 -0
  177. package/src/rum/instrumentation/resourceTracking/DdRumResourceTracking.tsx +38 -13
  178. package/src/rum/instrumentation/resourceTracking/__tests__/DdRumResourceTracking.test.ts +101 -0
  179. package/src/rum/instrumentation/resourceTracking/requestProxy/FetchProxy/FetchProxy.ts +316 -0
  180. package/src/rum/instrumentation/resourceTracking/requestProxy/FetchProxy/__tests__/FetchProxy.test.ts +393 -0
  181. package/src/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/DatadogRumResource/__tests__/ResourceReporter.test.ts +1 -1
  182. package/src/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/DatadogRumResource/__tests__/internalDevResourceBlocklist.test.ts +1 -1
  183. package/src/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/XHRProxy.ts +49 -115
  184. package/src/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/__tests__/XHRProxy.test.ts +1 -1
  185. package/src/rum/instrumentation/resourceTracking/requestProxy/common/FetchProxyState.ts +25 -0
  186. package/src/rum/instrumentation/resourceTracking/requestProxy/common/RequestContext.ts +54 -0
  187. package/src/rum/instrumentation/resourceTracking/requestProxy/{XHRProxy/DatadogRumResource → common}/ResourceReporter.ts +5 -5
  188. package/src/rum/instrumentation/resourceTracking/requestProxy/{XHRProxy/DatadogRumResource → common}/internalDevResourceBlocklist.ts +1 -17
  189. package/src/rum/instrumentation/resourceTracking/requestProxy/common/requestHeaders.ts +106 -0
  190. package/src/rum/instrumentation/resourceTracking/requestProxy/{XHRProxy/DatadogRumResource → common}/resourceTiming.ts +0 -18
  191. package/src/sdk/DatadogProvider/__tests__/initialization.test.tsx +1 -0
  192. package/src/version.ts +1 -1
  193. package/lib/commonjs/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/DatadogRumResource/ResourceReporter.js.map +0 -1
  194. package/lib/commonjs/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/DatadogRumResource/internalDevResourceBlocklist.js.map +0 -1
  195. package/lib/commonjs/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/DatadogRumResource/resourceTiming.js.map +0 -1
  196. package/lib/module/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/DatadogRumResource/ResourceReporter.js.map +0 -1
  197. package/lib/module/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/DatadogRumResource/internalDevResourceBlocklist.js.map +0 -1
  198. package/lib/module/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/DatadogRumResource/resourceTiming.js.map +0 -1
  199. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/DatadogRumResource/ResourceReporter.d.ts.map +0 -1
  200. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/DatadogRumResource/internalDevResourceBlocklist.d.ts +0 -7
  201. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/DatadogRumResource/internalDevResourceBlocklist.d.ts.map +0 -1
  202. package/lib/typescript/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/DatadogRumResource/resourceTiming.d.ts.map +0 -1
  203. /package/android/src/{oldarch → oldarchCommon}/kotlin/com/datadog/reactnative/DdFlags.kt +0 -0
  204. /package/android/src/{oldarch → oldarchCommon}/kotlin/com/datadog/reactnative/DdLogs.kt +0 -0
  205. /package/android/src/{oldarch → oldarchCommon}/kotlin/com/datadog/reactnative/DdSdk.kt +0 -0
  206. /package/android/src/{oldarch → oldarchCommon}/kotlin/com/datadog/reactnative/DdTrace.kt +0 -0
@@ -0,0 +1,316 @@
1
+ /*
2
+ * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
3
+ * This product includes software developed at Datadog (https://www.datadoghq.com/).
4
+ * Copyright 2016-Present Datadog, Inc.
5
+ */
6
+
7
+ import { InternalLog } from '../../../../../InternalLog';
8
+ import { SdkVerbosity } from '../../../../../config/types';
9
+ import { extractGraphQLErrors } from '../../graphql/graphqlUtils';
10
+ import { getErrorData } from '../XHRProxy/xhrUtils';
11
+ import { callOriginalFetch } from '../common/FetchProxyState';
12
+ import type { RequestContext } from '../common/RequestContext';
13
+ import { createRequestContext } from '../common/RequestContext';
14
+ import { ResourceReporter } from '../common/ResourceReporter';
15
+ import { filterDevResource } from '../common/internalDevResourceBlocklist';
16
+ import {
17
+ getInstrumentationHeaders,
18
+ processRequestHeader
19
+ } from '../common/requestHeaders';
20
+ import type { RequestProxyOptions } from '../interfaces/RequestProxy';
21
+ import { RequestProxy } from '../interfaces/RequestProxy';
22
+
23
+ const RESPONSE_START_LABEL = 'response_start';
24
+ const MISSING_RESOURCE_SIZE = -1;
25
+
26
+ type FetchGlobal = {
27
+ fetch: typeof fetch;
28
+ };
29
+
30
+ interface FetchProxyProviders {
31
+ fetchGlobal: FetchGlobal;
32
+ headersType: typeof Headers;
33
+ resourceReporter: ResourceReporter;
34
+ }
35
+
36
+ /**
37
+ * Proxies global Fetch implementations.
38
+ */
39
+ export class FetchProxy extends RequestProxy {
40
+ private context: RequestProxyOptions | null = null;
41
+ private originalFetch: typeof fetch | null = null;
42
+ private installedFetch: typeof fetch | null = null;
43
+
44
+ constructor(private providers: FetchProxyProviders) {
45
+ super();
46
+ }
47
+
48
+ static createWithResourceReporter() {
49
+ return new FetchProxy({
50
+ fetchGlobal: globalThis,
51
+ headersType: Headers,
52
+ resourceReporter: new ResourceReporter([filterDevResource])
53
+ });
54
+ }
55
+
56
+ onTrackingStart = (context: RequestProxyOptions) => {
57
+ this.context = context;
58
+ const originalFetch = this.providers.fetchGlobal.fetch;
59
+ this.originalFetch = originalFetch;
60
+
61
+ const installedFetch: typeof fetch = (input, init) => {
62
+ return trackFetch({
63
+ input,
64
+ init,
65
+ originalFetch,
66
+ fetchThis: this.providers.fetchGlobal,
67
+ headersType: this.providers.headersType,
68
+ resourceReporter: this.providers.resourceReporter,
69
+ options: context
70
+ });
71
+ };
72
+
73
+ this.installedFetch = installedFetch;
74
+ this.providers.fetchGlobal.fetch = installedFetch;
75
+ };
76
+
77
+ onTrackingStop = () => {
78
+ if (
79
+ this.originalFetch !== null &&
80
+ this.providers.fetchGlobal.fetch === this.installedFetch
81
+ ) {
82
+ this.providers.fetchGlobal.fetch = this.originalFetch;
83
+ }
84
+
85
+ this.context = null;
86
+ this.originalFetch = null;
87
+ this.installedFetch = null;
88
+ };
89
+
90
+ onTrackingUpdate = (options: { tracingSamplingRate: number }) => {
91
+ if (this.context === null) {
92
+ return;
93
+ }
94
+ this.context.tracingSamplingRate = options.tracingSamplingRate;
95
+ };
96
+ }
97
+
98
+ const trackFetch = async ({
99
+ input,
100
+ init,
101
+ originalFetch,
102
+ fetchThis,
103
+ headersType,
104
+ resourceReporter,
105
+ options
106
+ }: {
107
+ input: Parameters<typeof fetch>[0];
108
+ init: Parameters<typeof fetch>[1];
109
+ originalFetch: typeof fetch;
110
+ fetchThis: FetchGlobal;
111
+ headersType: typeof Headers;
112
+ resourceReporter: ResourceReporter;
113
+ options: RequestProxyOptions;
114
+ }): Promise<Response> => {
115
+ const url = getRequestUrl(input);
116
+ const method = getRequestMethod(input, init);
117
+ const context = createRequestContext({ method, url, options });
118
+ const headers = buildHeaders({ input, init, context, headersType });
119
+
120
+ context.timer.start();
121
+
122
+ try {
123
+ const response = await callOriginalFetch(() =>
124
+ originalFetch.call(fetchThis, input, {
125
+ ...(init ?? {}),
126
+ headers
127
+ })
128
+ );
129
+
130
+ context.timer.recordTick(RESPONSE_START_LABEL);
131
+ context.timer.stop();
132
+ reportFetch({ context, response, resourceReporter }).catch(error => {
133
+ const errorData = getErrorData(error);
134
+ if (errorData) {
135
+ InternalLog.log(
136
+ `reportFetch failed: ${errorData}`,
137
+ SdkVerbosity.WARN
138
+ );
139
+ }
140
+ });
141
+ return response;
142
+ } catch (error) {
143
+ context.timer.stop();
144
+ reportFetchFailure({ context, resourceReporter });
145
+ throw error;
146
+ }
147
+ };
148
+
149
+ const getRequestUrl = (input: Parameters<typeof fetch>[0]): string => {
150
+ if (typeof input === 'string') {
151
+ return input;
152
+ }
153
+
154
+ if (
155
+ typeof input === 'object' &&
156
+ input !== null &&
157
+ 'url' in input &&
158
+ typeof input.url === 'string'
159
+ ) {
160
+ return input.url;
161
+ }
162
+
163
+ return String(input);
164
+ };
165
+
166
+ const getRequestMethod = (
167
+ input: Parameters<typeof fetch>[0],
168
+ init?: Parameters<typeof fetch>[1]
169
+ ): string => {
170
+ const requestMethod =
171
+ typeof input === 'object' &&
172
+ input !== null &&
173
+ 'method' in input &&
174
+ typeof input.method === 'string'
175
+ ? input.method
176
+ : undefined;
177
+
178
+ return (init?.method ?? requestMethod ?? 'GET').toUpperCase();
179
+ };
180
+
181
+ const buildHeaders = ({
182
+ input,
183
+ init,
184
+ context,
185
+ headersType
186
+ }: {
187
+ input: Parameters<typeof fetch>[0];
188
+ init?: Parameters<typeof fetch>[1];
189
+ context: RequestContext;
190
+ headersType: typeof Headers;
191
+ }): Headers => {
192
+ const requestHeaders =
193
+ typeof input === 'object' && input !== null && 'headers' in input
194
+ ? input.headers
195
+ : undefined;
196
+ const headers: Headers = new headersType(init?.headers ?? requestHeaders);
197
+ const originalHeaders: { header: string; value: string }[] = [];
198
+
199
+ headers.forEach((value: string, header: string) => {
200
+ originalHeaders.push({ header, value });
201
+ });
202
+
203
+ originalHeaders.forEach(({ header }) => headers.delete(header));
204
+ originalHeaders.forEach(({ header, value }) => {
205
+ applyHeader({ headers, context, header, value });
206
+ });
207
+ getInstrumentationHeaders(context).forEach(({ header, value }) => {
208
+ applyHeader({ headers, context, header, value });
209
+ });
210
+
211
+ return headers;
212
+ };
213
+
214
+ const applyHeader = ({
215
+ headers,
216
+ context,
217
+ header,
218
+ value
219
+ }: {
220
+ headers: Headers;
221
+ context: RequestContext;
222
+ header: string;
223
+ value: string;
224
+ }) => {
225
+ const processedHeader = processRequestHeader({ context, header, value });
226
+ if (processedHeader.type === 'send') {
227
+ headers.set(processedHeader.header, processedHeader.value);
228
+ }
229
+ };
230
+
231
+ const reportFetch = async ({
232
+ context,
233
+ response,
234
+ resourceReporter
235
+ }: {
236
+ context: RequestContext;
237
+ response: Response;
238
+ resourceReporter: ResourceReporter;
239
+ }): Promise<void> => {
240
+ // Only extract GraphQL errors if operationType is set AND error tracking is enabled
241
+ if (context.graphql.operationType && context.graphql.trackErrors) {
242
+ try {
243
+ const body = await response.clone().json();
244
+
245
+ const errors = body?.errors;
246
+ if (Array.isArray(errors) && errors.length > 0) {
247
+ const filtered = extractGraphQLErrors(errors);
248
+
249
+ if (filtered.length > 0) {
250
+ context.graphql.errors = filtered;
251
+ }
252
+ }
253
+ } catch (error) {
254
+ const errorData = getErrorData(error);
255
+ if (errorData) {
256
+ InternalLog.log(`reportFetch: ${errorData}`, SdkVerbosity.WARN);
257
+ }
258
+ }
259
+ }
260
+
261
+ resourceReporter.reportResource({
262
+ key: `${context.timer.startTime}/${context.method}`,
263
+ request: {
264
+ method: context.method,
265
+ url: context.url,
266
+ kind: 'fetch'
267
+ },
268
+ graphqlAttributes: context.graphql,
269
+ tracingAttributes: context.tracingAttributes,
270
+ response: {
271
+ statusCode: response.status,
272
+ size: getResponseSize(response)
273
+ },
274
+ timings: {
275
+ startTime: context.timer.startTime,
276
+ stopTime: context.timer.stopTime,
277
+ responseStartTime: context.timer.timeAt(RESPONSE_START_LABEL)
278
+ }
279
+ });
280
+ };
281
+
282
+ const reportFetchFailure = ({
283
+ context,
284
+ resourceReporter
285
+ }: {
286
+ context: RequestContext;
287
+ resourceReporter: ResourceReporter;
288
+ }) => {
289
+ resourceReporter.reportResource({
290
+ key: `${context.timer.startTime}/${context.method}`,
291
+ request: {
292
+ method: context.method,
293
+ url: context.url,
294
+ kind: 'fetch'
295
+ },
296
+ graphqlAttributes: context.graphql,
297
+ tracingAttributes: context.tracingAttributes,
298
+ response: {
299
+ statusCode: 0,
300
+ size: MISSING_RESOURCE_SIZE
301
+ },
302
+ timings: {
303
+ startTime: context.timer.startTime,
304
+ stopTime: context.timer.stopTime
305
+ }
306
+ });
307
+ };
308
+
309
+ const getResponseSize = (response: Response): number => {
310
+ const contentLength = response.headers.get('content-length');
311
+ if (contentLength === null || !/^\d+$/.test(contentLength)) {
312
+ return MISSING_RESOURCE_SIZE;
313
+ }
314
+
315
+ return Number(contentLength);
316
+ };
@@ -0,0 +1,393 @@
1
+ /*
2
+ * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
3
+ * This product includes software developed at Datadog (https://www.datadoghq.com/).
4
+ * Copyright 2016-Present Datadog, Inc.
5
+ */
6
+
7
+ import { PropagatorType } from '../../../../../types';
8
+ import { firstPartyHostsRegexMapBuilder } from '../../../distributedTracing/firstPartyHosts';
9
+ import {
10
+ PARENT_ID_HEADER_KEY,
11
+ SAMPLING_PRIORITY_HEADER_KEY,
12
+ TRACKED_BY_HEADER_KEY,
13
+ TRACKED_BY_HEADER_VALUE
14
+ } from '../../../distributedTracing/headers';
15
+ import {
16
+ DATADOG_GRAPH_QL_ERROR_HEADER,
17
+ DATADOG_GRAPH_QL_OPERATION_TYPE_HEADER
18
+ } from '../../../graphql/graphqlHeaders';
19
+ import type { ResourceReporter } from '../../common/ResourceReporter';
20
+ import type { RUMResource } from '../../interfaces/RumResource';
21
+ import { FetchProxy } from '../FetchProxy';
22
+
23
+ class HeadersMock {
24
+ private values = new Map<string, string>();
25
+
26
+ constructor(init?: HeadersInit) {
27
+ if (init instanceof HeadersMock) {
28
+ init.forEach((value, header) => this.set(header, value));
29
+ } else if (Array.isArray(init)) {
30
+ init.forEach(([header, value]) => this.set(header, value));
31
+ } else if (init && typeof init === 'object' && 'forEach' in init) {
32
+ (init as Headers).forEach((value, header) =>
33
+ this.set(header, value)
34
+ );
35
+ } else if (init) {
36
+ Object.entries(init).forEach(([header, value]) =>
37
+ this.set(header, value)
38
+ );
39
+ }
40
+ }
41
+
42
+ delete(header: string) {
43
+ this.values.delete(header.toLowerCase());
44
+ }
45
+
46
+ forEach(callback: (value: string, header: string) => void) {
47
+ this.values.forEach((value, header) => callback(value, header));
48
+ }
49
+
50
+ get(header: string): string | null {
51
+ return this.values.get(header.toLowerCase()) ?? null;
52
+ }
53
+
54
+ set(header: string, value: string) {
55
+ this.values.set(header.toLowerCase(), String(value));
56
+ }
57
+ }
58
+
59
+ const getOptions = (traceSampleRate = 100) => ({
60
+ tracingSamplingRate: traceSampleRate,
61
+ firstPartyHostsRegexMap: firstPartyHostsRegexMapBuilder([
62
+ {
63
+ match: 'api.example.com',
64
+ propagatorTypes: [PropagatorType.DATADOG]
65
+ }
66
+ ])
67
+ });
68
+
69
+ const createResponse = ({
70
+ status = 200,
71
+ headers = {},
72
+ body
73
+ }: {
74
+ status?: number;
75
+ headers?: Record<string, string>;
76
+ body?: unknown;
77
+ } = {}) => {
78
+ const response = ({
79
+ status,
80
+ headers: new HeadersMock(headers),
81
+ clone() {
82
+ return response;
83
+ },
84
+ json: () => Promise.resolve(body)
85
+ } as unknown) as Response;
86
+
87
+ return response;
88
+ };
89
+
90
+ const flushPromises = () =>
91
+ new Promise(jest.requireActual('timers').setImmediate);
92
+
93
+ const createProxy = ({
94
+ originalFetch,
95
+ reportResource
96
+ }: {
97
+ originalFetch: typeof fetch;
98
+ reportResource: jest.Mock;
99
+ }) => {
100
+ const fetchGlobal = { fetch: originalFetch };
101
+ const proxy = new FetchProxy({
102
+ fetchGlobal,
103
+ headersType: (HeadersMock as unknown) as typeof Headers,
104
+ resourceReporter: ({
105
+ reportResource
106
+ } as unknown) as ResourceReporter
107
+ });
108
+
109
+ return { fetchGlobal, proxy };
110
+ };
111
+
112
+ describe('FetchProxy', () => {
113
+ it('reports a successful Fetch resource without replacing the response', async () => {
114
+ const response = createResponse({
115
+ status: 201,
116
+ headers: { 'content-length': '42' }
117
+ });
118
+ const originalFetch = jest
119
+ .fn()
120
+ .mockResolvedValue(response) as jest.MockedFunction<typeof fetch>;
121
+ const reportResource = jest.fn();
122
+ const { fetchGlobal, proxy } = createProxy({
123
+ originalFetch,
124
+ reportResource
125
+ });
126
+ proxy.onTrackingStart(getOptions());
127
+
128
+ const result = await fetchGlobal.fetch(
129
+ 'https://api.example.com/users',
130
+ {
131
+ method: 'post'
132
+ }
133
+ );
134
+
135
+ expect(result).toBe(response);
136
+ expect(reportResource).toHaveBeenCalledTimes(1);
137
+ expect(reportResource).toHaveBeenCalledWith(
138
+ expect.objectContaining({
139
+ request: {
140
+ method: 'POST',
141
+ url: 'https://api.example.com/users',
142
+ kind: 'fetch'
143
+ },
144
+ response: {
145
+ statusCode: 201,
146
+ size: 42
147
+ }
148
+ })
149
+ );
150
+
151
+ const outgoingHeaders = (originalFetch.mock.calls[0][1]
152
+ ?.headers as unknown) as HeadersMock;
153
+ expect(outgoingHeaders.get(TRACKED_BY_HEADER_KEY)).toBe(
154
+ TRACKED_BY_HEADER_VALUE
155
+ );
156
+ expect(outgoingHeaders.get(SAMPLING_PRIORITY_HEADER_KEY)).toBe('1');
157
+ expect(outgoingHeaders.get(PARENT_ID_HEADER_KEY)).not.toBeNull();
158
+ });
159
+
160
+ it('extracts GraphQL metadata and removes its internal header', async () => {
161
+ const originalFetch = jest
162
+ .fn()
163
+ .mockResolvedValue(createResponse()) as jest.MockedFunction<
164
+ typeof fetch
165
+ >;
166
+ const reportResource = jest.fn();
167
+ const { fetchGlobal, proxy } = createProxy({
168
+ originalFetch,
169
+ reportResource
170
+ });
171
+ proxy.onTrackingStart(getOptions());
172
+
173
+ await fetchGlobal.fetch('https://api.example.com/graphql', {
174
+ headers: {
175
+ [DATADOG_GRAPH_QL_OPERATION_TYPE_HEADER]: 'query',
176
+ accept: 'application/json'
177
+ }
178
+ });
179
+
180
+ const resource = reportResource.mock.calls[0][0] as RUMResource;
181
+ expect(resource.graphqlAttributes?.operationType).toBe('query');
182
+ const outgoingHeaders = (originalFetch.mock.calls[0][1]
183
+ ?.headers as unknown) as HeadersMock;
184
+ expect(
185
+ outgoingHeaders.get(DATADOG_GRAPH_QL_OPERATION_TYPE_HEADER)
186
+ ).toBeNull();
187
+ expect(outgoingHeaders.get('accept')).toBe('application/json');
188
+ });
189
+
190
+ it('reports a failed resource and rethrows the original rejection', async () => {
191
+ const rejection = new Error('network failed');
192
+ const originalFetch = jest
193
+ .fn()
194
+ .mockRejectedValue(rejection) as jest.MockedFunction<typeof fetch>;
195
+ const reportResource = jest.fn();
196
+ const { fetchGlobal, proxy } = createProxy({
197
+ originalFetch,
198
+ reportResource
199
+ });
200
+ proxy.onTrackingStart(getOptions());
201
+
202
+ await expect(
203
+ fetchGlobal.fetch('https://api.example.com/users')
204
+ ).rejects.toBe(rejection);
205
+ expect(reportResource).toHaveBeenCalledWith(
206
+ expect.objectContaining({
207
+ response: {
208
+ statusCode: 0,
209
+ size: -1
210
+ }
211
+ })
212
+ );
213
+ });
214
+
215
+ it('applies sampling updates to subsequent Fetch requests', async () => {
216
+ const originalFetch = jest
217
+ .fn()
218
+ .mockResolvedValue(createResponse()) as jest.MockedFunction<
219
+ typeof fetch
220
+ >;
221
+ const { fetchGlobal, proxy } = createProxy({
222
+ originalFetch,
223
+ reportResource: jest.fn()
224
+ });
225
+ proxy.onTrackingStart(getOptions(0));
226
+ proxy.onTrackingUpdate({ tracingSamplingRate: 100 });
227
+
228
+ await fetchGlobal.fetch('https://api.example.com/users');
229
+
230
+ const outgoingHeaders = (originalFetch.mock.calls[0][1]
231
+ ?.headers as unknown) as HeadersMock;
232
+ expect(outgoingHeaders.get(SAMPLING_PRIORITY_HEADER_KEY)).toBe('1');
233
+ });
234
+
235
+ it('restores the original Fetch when tracking stops', () => {
236
+ const originalFetch = jest.fn() as jest.MockedFunction<typeof fetch>;
237
+ const { fetchGlobal, proxy } = createProxy({
238
+ originalFetch,
239
+ reportResource: jest.fn()
240
+ });
241
+ proxy.onTrackingStart(getOptions());
242
+
243
+ expect(fetchGlobal.fetch).not.toBe(originalFetch);
244
+ proxy.onTrackingStop();
245
+
246
+ expect(fetchGlobal.fetch).toBe(originalFetch);
247
+ });
248
+
249
+ it('does not overwrite a Fetch wrapper installed after Datadog', () => {
250
+ const originalFetch = jest.fn() as jest.MockedFunction<typeof fetch>;
251
+ const { fetchGlobal, proxy } = createProxy({
252
+ originalFetch,
253
+ reportResource: jest.fn()
254
+ });
255
+ proxy.onTrackingStart(getOptions());
256
+ const laterFetch = jest.fn() as jest.MockedFunction<typeof fetch>;
257
+ fetchGlobal.fetch = laterFetch;
258
+
259
+ proxy.onTrackingStop();
260
+
261
+ expect(fetchGlobal.fetch).toBe(laterFetch);
262
+ });
263
+
264
+ it('keeps a Fetch wrapper retained by another library callable after tracking stops', async () => {
265
+ const response = createResponse();
266
+ const originalFetch = jest
267
+ .fn()
268
+ .mockResolvedValue(response) as jest.MockedFunction<typeof fetch>;
269
+ const { fetchGlobal, proxy } = createProxy({
270
+ originalFetch,
271
+ reportResource: jest.fn()
272
+ });
273
+ proxy.onTrackingStart(getOptions());
274
+
275
+ // Another library installs its own wrapper after Datadog, capturing
276
+ // Datadog's installed Fetch as its own "original" delegate.
277
+ const capturedDatadogFetch = fetchGlobal.fetch;
278
+ fetchGlobal.fetch = ((input, init) =>
279
+ capturedDatadogFetch(input, init)) as typeof fetch;
280
+
281
+ proxy.onTrackingStop();
282
+
283
+ await expect(
284
+ capturedDatadogFetch('https://api.example.com/users')
285
+ ).resolves.toBe(response);
286
+ });
287
+
288
+ describe('GraphQL error filtering', () => {
289
+ it('extracts GraphQL errors from the response body when error tracking is enabled', async () => {
290
+ const graphqlResponse = {
291
+ data: { user: null },
292
+ errors: [
293
+ {
294
+ message: 'User not found',
295
+ locations: [{ line: 2, column: 3 }],
296
+ path: ['user', 0, 'id'],
297
+ extensions: { code: 'NOT_FOUND' }
298
+ }
299
+ ]
300
+ };
301
+ const originalFetch = jest
302
+ .fn()
303
+ .mockResolvedValue(
304
+ createResponse({ body: graphqlResponse })
305
+ ) as jest.MockedFunction<typeof fetch>;
306
+ const reportResource = jest.fn();
307
+ const { fetchGlobal, proxy } = createProxy({
308
+ originalFetch,
309
+ reportResource
310
+ });
311
+ proxy.onTrackingStart(getOptions());
312
+
313
+ await fetchGlobal.fetch('https://api.example.com/graphql', {
314
+ headers: {
315
+ [DATADOG_GRAPH_QL_OPERATION_TYPE_HEADER]: 'query',
316
+ [DATADOG_GRAPH_QL_ERROR_HEADER]: 'true'
317
+ }
318
+ });
319
+ await flushPromises();
320
+
321
+ const resource = reportResource.mock.calls[0][0] as RUMResource;
322
+ expect(resource.graphqlAttributes?.errors).toEqual([
323
+ {
324
+ message: 'User not found',
325
+ code: 'NOT_FOUND',
326
+ locations: [{ line: 2, column: 3 }],
327
+ path: ['user', 0, 'id']
328
+ }
329
+ ]);
330
+ });
331
+
332
+ it('reports without errors when the Fetch implementation does not support clone()', async () => {
333
+ // Some Fetch implementations (e.g. `expo/fetch` prior to Expo SDK
334
+ // 56) throw on `response.clone()`.
335
+ const response = createResponse({ body: { data: {} } });
336
+ response.clone = () => {
337
+ throw new Error('Not implemented');
338
+ };
339
+ const originalFetch = jest
340
+ .fn()
341
+ .mockResolvedValue(response) as jest.MockedFunction<
342
+ typeof fetch
343
+ >;
344
+ const reportResource = jest.fn();
345
+ const { fetchGlobal, proxy } = createProxy({
346
+ originalFetch,
347
+ reportResource
348
+ });
349
+ proxy.onTrackingStart(getOptions());
350
+
351
+ await expect(
352
+ fetchGlobal.fetch('https://api.example.com/graphql', {
353
+ headers: {
354
+ [DATADOG_GRAPH_QL_OPERATION_TYPE_HEADER]: 'query',
355
+ [DATADOG_GRAPH_QL_ERROR_HEADER]: 'true'
356
+ }
357
+ })
358
+ ).resolves.toBe(response);
359
+ await flushPromises();
360
+
361
+ const resource = reportResource.mock.calls[0][0] as RUMResource;
362
+ expect(resource.graphqlAttributes?.operationType).toBe('query');
363
+ expect(resource.graphqlAttributes?.errors).toBeUndefined();
364
+ });
365
+
366
+ it('does not read the response body when error tracking is disabled', async () => {
367
+ const response = createResponse({ body: { data: {} } });
368
+ const cloneSpy = jest.spyOn(response, 'clone');
369
+ const originalFetch = jest
370
+ .fn()
371
+ .mockResolvedValue(response) as jest.MockedFunction<
372
+ typeof fetch
373
+ >;
374
+ const reportResource = jest.fn();
375
+ const { fetchGlobal, proxy } = createProxy({
376
+ originalFetch,
377
+ reportResource
378
+ });
379
+ proxy.onTrackingStart(getOptions());
380
+
381
+ await fetchGlobal.fetch('https://api.example.com/graphql', {
382
+ headers: {
383
+ [DATADOG_GRAPH_QL_OPERATION_TYPE_HEADER]: 'query'
384
+ }
385
+ });
386
+ await flushPromises();
387
+
388
+ expect(cloneSpy).not.toHaveBeenCalled();
389
+ const resource = reportResource.mock.calls[0][0] as RUMResource;
390
+ expect(resource.graphqlAttributes?.errors).toBeUndefined();
391
+ });
392
+ });
393
+ });