@logbrew/react-native 0.1.39 → 0.1.41

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 (99) hide show
  1. package/README.md +3 -3
  2. package/android-native-diagnostics.d.ts +15 -5
  3. package/android-native-diagnostics.js +170 -94
  4. package/apollo.cjs +435 -226
  5. package/apollo.d.cts +2 -70
  6. package/apollo.d.ts +24 -12
  7. package/apollo.js +438 -221
  8. package/apple-native-diagnostics-config.js +176 -0
  9. package/apple-native-diagnostics-context.js +232 -0
  10. package/apple-native-diagnostics-module.js +229 -0
  11. package/apple-native-diagnostics.d.ts +42 -11
  12. package/apple-native-diagnostics.js +60 -389
  13. package/expo.cjs +29 -16
  14. package/expo.d.ts +10 -9
  15. package/expo.js +4 -3
  16. package/fatal-admission.cjs +113 -0
  17. package/fatal-record.cjs +317 -0
  18. package/fatal-replay.cjs +297 -508
  19. package/global-errors-capture.cjs +369 -0
  20. package/global-errors-event.cjs +174 -0
  21. package/global-errors-support.cjs +128 -0
  22. package/global-errors.cjs +75 -351
  23. package/global-errors.d.cts +29 -278
  24. package/global-errors.d.ts +57 -27
  25. package/global-errors.js +7 -2
  26. package/global-errors.native.js +83 -48
  27. package/index-breadcrumbs.cjs +139 -0
  28. package/index-errors.cjs +167 -0
  29. package/index-events.cjs +365 -0
  30. package/index-navigation.cjs +327 -0
  31. package/index-random.cjs +120 -0
  32. package/index-react.cjs +189 -0
  33. package/index-spans.cjs +190 -0
  34. package/index-trace-fetch.cjs +322 -0
  35. package/index-trace.cjs +335 -0
  36. package/index-transport.cjs +201 -0
  37. package/index-values.cjs +232 -0
  38. package/index.cjs +97 -1245
  39. package/index.d.cts +2 -505
  40. package/index.d.ts +130 -469
  41. package/index.native.d.ts +146 -22
  42. package/index.native.js +184 -159
  43. package/instrumentation-fetch.cjs +113 -0
  44. package/instrumentation-install.cjs +241 -0
  45. package/instrumentation-runtime.cjs +65 -0
  46. package/instrumentation-teardown.cjs +93 -0
  47. package/instrumentation-values.cjs +282 -0
  48. package/instrumentation-xhr-request.cjs +298 -0
  49. package/instrumentation-xhr.cjs +233 -0
  50. package/instrumentation.cjs +110 -599
  51. package/instrumentation.d.cts +2 -84
  52. package/instrumentation.d.ts +22 -8
  53. package/ios/AppleDiagnostics/LBRNAppleNativeDiagnostics.swift +1 -1
  54. package/ios/GeneratedAppleDiagnostics/LogBrew/DeliveryLifecycle.swift +1 -1
  55. package/ios/GeneratedAppleDiagnostics/SOURCE-MANIFEST.json +1 -1
  56. package/lifecycle.cjs +181 -78
  57. package/lifecycle.d.cts +1 -50
  58. package/lifecycle.d.ts +17 -6
  59. package/metadata.cjs +279 -114
  60. package/metro-debug-id.cjs +296 -0
  61. package/metro-serializer.cjs +219 -0
  62. package/metro.cjs +153 -297
  63. package/metro.d.cts +2 -57
  64. package/metro.d.ts +27 -13
  65. package/metro.js +2 -3
  66. package/native-bridge-async.cjs +165 -0
  67. package/native-bridge-scope.cjs +148 -0
  68. package/native-bridge.cjs +83 -186
  69. package/native-bridge.d.cts +2 -94
  70. package/native-bridge.d.ts +28 -15
  71. package/native-client-bindings.js +230 -0
  72. package/native-diagnostics-values.js +120 -0
  73. package/native-module-lookup.js +31 -0
  74. package/native-null.js +3 -0
  75. package/null-value.cjs +4 -0
  76. package/package.json +43 -1
  77. package/persistent-delivery-store.js +247 -0
  78. package/persistent-delivery.native.js +183 -261
  79. package/promise-rejection-handlers.cjs +368 -0
  80. package/promise-rejections.cjs +169 -361
  81. package/react-native.config.js +3 -1
  82. package/release-artifacts-files.cjs +94 -0
  83. package/release-artifacts-options.cjs +182 -0
  84. package/release-artifacts.cjs +278 -207
  85. package/release-artifacts.d.cts +2 -55
  86. package/release-artifacts.d.ts +18 -7
  87. package/release-artifacts.js +2 -4
  88. package/resource-fetch-graphql.cjs +265 -0
  89. package/resource-fetch-size.cjs +156 -0
  90. package/resource-fetch.cjs +227 -428
  91. package/resource-fetch.d.cts +1 -60
  92. package/resource-fetch.d.ts +17 -6
  93. package/scripts/sync-apple-native-sources.mjs +101 -53
  94. package/types/capture.d.ts +95 -0
  95. package/types/config.d.ts +85 -0
  96. package/types/defaults.d.ts +55 -0
  97. package/types/events.d.ts +203 -0
  98. package/types/provider.d.ts +81 -0
  99. package/types/trace.d.ts +104 -0
@@ -2,465 +2,264 @@
2
2
 
3
3
  const { SdkError } = require("@logbrew/sdk");
4
4
  const {
5
- captureReactNativeResourceSpan,
6
- createReactNativeTraceContext,
7
- createTraceparentFetch,
8
- getActiveLogBrewTrace
9
- } = require("./index.cjs");
10
- const {
11
- createSafeReactNativeMetadata,
12
- safeReactNativeMetadataFactoryResult
13
- } = require("./metadata.cjs");
14
-
15
- const MAX_GRAPHQL_BODY_CHARS = 16_384;
16
- const MAX_GRAPHQL_OPERATION_NAME_CHARS = 128;
17
- const GRAPHQL_OPERATION_NAME_RE = /^[_A-Za-z][_0-9A-Za-z]*$/u;
18
- const GRAPHQL_OPERATION_RE = /^(query|mutation|subscription)\b(?:\s+([_A-Za-z][_0-9A-Za-z]*))?/u;
19
-
20
- function createReactNativeResourceFetch(client, {
21
- appState,
22
- fetchImpl,
23
- metadata = {},
24
- metadataFactory,
25
- measureResponseBodySize = false,
26
- now = () => new Date().toISOString(),
27
- nowMs = () => Date.now(),
28
- platform,
29
- randomValues,
30
- routeTemplate,
31
- routeTemplateFactory = defaultRouteTemplateFactory,
32
- screen,
33
- sessionId,
34
- trace,
35
- traceFlags = "01",
36
- tracePropagationTargets = []
37
- } = {}) {
38
- if (routeTemplateFactory !== undefined && typeof routeTemplateFactory !== "function") {
39
- throw new SdkError("configuration_error", "routeTemplateFactory must be a function");
40
- }
41
- if (metadataFactory !== undefined && typeof metadataFactory !== "function") {
42
- throw new SdkError("configuration_error", "metadataFactory must be a function");
43
- }
44
-
45
- return async function logBrewResourceFetch(input, init) {
46
- const startedAtMs = nowMs();
47
- const timestamp = now();
48
- const activeTrace = resourceTraceContext({ randomValues, trace, traceFlags });
49
- const tracedFetch = createTraceparentFetch({
50
- fetchImpl,
51
- trace: activeTrace,
52
- tracePropagationTargets
53
- });
54
- const method = requestMethod(input, init);
55
- const url = requestUrl(input);
56
- const safeRouteTemplate = routeTemplate ?? routeTemplateFactory({ input, init, url });
57
- try {
58
- const response = await tracedFetch(input, init);
59
- const responseStartDurationMs = elapsedMs(startedAtMs, nowMs);
60
- const statusCode = responseStatusCode(response);
61
- const responseSizeBytes = await responseSizeBytesFromResponse(response, { measureResponseBodySize });
62
- const durationMs = elapsedMs(startedAtMs, nowMs);
63
- captureReactNativeResourceSpan(client, {
64
- appState,
65
- durationMs,
66
- metadata: {
67
- ...createSafeReactNativeMetadata(metadata, metadataFactory, {
68
- durationMs,
69
- init,
70
- input,
71
- method,
72
- response,
73
- responseSizeBytes,
74
- responseStartDurationMs,
75
- routeTemplate: safeRouteTemplate,
76
- statusCode,
77
- url
78
- }),
79
- responseStartDurationMs
80
- },
81
- method,
82
- platform,
83
- routeTemplate: safeRouteTemplate,
84
- screen,
85
- sessionId,
86
- responseSizeBytes,
87
- statusCode,
88
- timestamp,
89
- trace: activeTrace
90
- });
91
- return response;
92
- } catch (error) {
93
- const durationMs = elapsedMs(startedAtMs, nowMs);
94
- captureReactNativeResourceSpan(client, {
95
- appState,
96
- durationMs,
97
- metadata: {
98
- ...createSafeReactNativeMetadata(metadata, metadataFactory, {
99
- durationMs,
100
- error,
101
- init,
102
- input,
103
- method,
104
- routeTemplate: safeRouteTemplate,
105
- status: "error",
106
- url
107
- }),
108
- fetchErrorName: errorName(error),
109
- fetchErrorValueType: typeof error
110
- },
111
- method,
112
- platform,
113
- routeTemplate: safeRouteTemplate,
114
- screen,
115
- sessionId,
116
- status: "error",
117
- timestamp,
118
- trace: activeTrace
119
- });
120
- throw error;
121
- }
122
- };
123
- }
124
-
125
- function createReactNativeGraphQLMetadataFactory({
126
- endpoint,
127
- metadataFactory
128
- } = {}) {
129
- const endpointMatchers = normalizeGraphQLEndpointMatchers(endpoint);
130
- if (metadataFactory !== undefined && typeof metadataFactory !== "function") {
131
- throw new SdkError("configuration_error", "metadataFactory must be a function");
132
- }
133
- return function logBrewReactNativeGraphQLMetadata(context) {
134
- const safeMetadata = safeReactNativeMetadataFactoryResult(typeof metadataFactory === "function" ? metadataFactory(context) : undefined);
135
- if (endpointMatchers.length > 0 && !matchesGraphQLEndpoint(context, endpointMatchers)) {
136
- return safeMetadata;
137
- }
138
- return {
139
- ...safeMetadata,
140
- ...graphqlMetadataFromContext(context)
141
- };
142
- };
143
- }
144
-
145
- function normalizeGraphQLEndpointMatchers(endpoint) {
146
- if (endpoint === undefined) {
147
- return [];
148
- }
149
- const endpoints = Array.isArray(endpoint) ? endpoint : [endpoint];
150
- return endpoints.map((candidate) => {
151
- if (typeof candidate === "string" || candidate instanceof String) {
152
- const value = normalizeEndpointString(candidate.toString());
153
- if (value === "") {
154
- throw new SdkError("configuration_error", "GraphQL endpoint strings must not be empty");
155
- }
156
- return value;
157
- }
158
- if (candidate instanceof RegExp || typeof candidate === "function") {
159
- return candidate;
160
- }
161
- throw new SdkError("configuration_error", "GraphQL endpoint must be a string, RegExp, function, or array");
162
- });
163
- }
164
-
165
- function matchesGraphQLEndpoint(context, endpointMatchers) {
166
- const candidates = graphqlEndpointCandidates(context);
167
- return endpointMatchers.some((matcher) => {
168
- if (typeof matcher === "string") {
169
- return candidates.includes(matcher);
170
- }
171
- if (matcher instanceof RegExp) {
172
- return candidates.some((candidate) => endpointRegExpMatches(matcher, candidate));
173
- }
174
- return matcher(context) === true;
175
- });
176
- }
177
-
178
- function endpointRegExpMatches(matcher, candidate) {
179
- matcher.lastIndex = 0;
180
- const matched = matcher.test(candidate);
181
- matcher.lastIndex = 0;
182
- return matched;
183
- }
184
-
185
- function graphqlEndpointCandidates(context) {
186
- const candidates = new Set();
187
- if (typeof context?.routeTemplate === "string" && context.routeTemplate.trim() !== "") {
188
- candidates.add(context.routeTemplate);
189
- }
190
- for (const candidate of endpointCandidatesFromUrl(context?.url)) {
191
- candidates.add(candidate);
192
- }
193
- return Array.from(candidates);
194
- }
195
-
196
- function normalizeEndpointString(endpoint) {
197
- const value = endpoint.trim();
198
- const candidates = endpointCandidatesFromUrl(value);
199
- return candidates[candidates.length - 1] ?? value.split(/[?#]/u, 1)[0];
200
- }
201
-
202
- function endpointCandidatesFromUrl(value) {
203
- if (typeof value !== "string" || value.trim() === "") {
204
- return [];
205
- }
206
- const URLConstructor = globalThis.URL;
207
- if (typeof URLConstructor === "function") {
208
- try {
209
- const parsedUrl = new URLConstructor(value, "https://logbrew.local");
210
- const candidates = [parsedUrl.pathname];
211
- if (/^https?:\/\//iu.test(value)) {
212
- candidates.push(`${parsedUrl.origin}${parsedUrl.pathname}`);
213
- }
214
- return candidates;
215
- } catch {
216
- // Fall back to query/hash stripping below for non-standard request keys.
217
- }
218
- }
219
- return [value.split(/[?#]/u, 1)[0]];
220
- }
221
-
222
- function graphqlMetadataFromContext(context) {
223
- const payload = graphqlPayloadFromBody(requestBody(context));
224
- if (!payload) {
225
- return {};
226
- }
227
- const operation = graphqlOperationDetails(payload.query);
228
- const operationName = safeGraphqlOperationName(payload.operationName) ?? operation.operationName;
229
- const metadata = {};
230
- if (operationName) {
231
- metadata.graphqlOperationName = operationName;
232
- }
233
- if (operation.operationType) {
234
- metadata.graphqlOperationType = operation.operationType;
235
- }
236
- return metadata;
237
- }
238
-
239
- function requestBody(context) {
240
- const body = context?.init?.body ?? context?.input?.body;
241
- if (typeof body === "string") {
242
- return body;
243
- }
244
- if (body instanceof String) {
245
- return body.toString();
246
- }
247
- return undefined;
248
- }
249
-
250
- function graphqlPayloadFromBody(body) {
251
- if (typeof body !== "string" || body.length > MAX_GRAPHQL_BODY_CHARS) {
252
- return undefined;
253
- }
254
- try {
255
- const payload = JSON.parse(body);
256
- return payload && typeof payload === "object" && !Array.isArray(payload) ? payload : undefined;
257
- } catch {
258
- return undefined;
259
- }
260
- }
261
-
262
- function graphqlOperationDetails(query) {
263
- if (typeof query !== "string" || query.length > MAX_GRAPHQL_BODY_CHARS) {
264
- return {};
265
- }
266
- const source = query.trimStart();
267
- if (source.startsWith("{")) {
268
- return { operationType: "query" };
269
- }
270
- const match = GRAPHQL_OPERATION_RE.exec(stripLeadingGraphQLComments(source));
271
- if (!match) {
272
- return {};
273
- }
274
- return {
275
- operationName: safeGraphqlOperationName(match[2]),
276
- operationType: match[1]
277
- };
278
- }
279
-
280
- function stripLeadingGraphQLComments(source) {
281
- return source.replace(/^(?:#[^\n\r]*(?:\r?\n|$)\s*)+/u, "").trimStart();
282
- }
283
-
284
- function safeGraphqlOperationName(value) {
285
- if (typeof value !== "string") {
286
- return undefined;
287
- }
288
- const name = value.trim();
289
- if (
290
- name.length === 0 ||
291
- name.length > MAX_GRAPHQL_OPERATION_NAME_CHARS ||
292
- !GRAPHQL_OPERATION_NAME_RE.test(name)
293
- ) {
294
- return undefined;
295
- }
296
- return name;
297
- }
298
-
5
+ defaultRouteTemplateFactory,
6
+ elapsedMs,
7
+ errorName,
8
+ indexRuntime,
9
+ isCallable,
10
+ metadataRuntime,
11
+ readField,
12
+ toText,
13
+ urlConstructor
14
+ } = require("./instrumentation-values.cjs");
15
+ const { createReactNativeGraphQLMetadataFactory } = require("./resource-fetch-graphql.cjs");
16
+ const { responseSizeBytesFromResponse } = require("./resource-fetch-size.cjs");
17
+
18
+ /**
19
+ * @import { LogBrewClient, Metadata } from "@logbrew/sdk"
20
+ * @import { TracePropagationTarget } from "./index.cjs"
21
+ * @import { AppStateInput, Callable, PlatformInput, RandomValues, TraceInput } from "./instrumentation-values.cjs"
22
+ * @import { ResourceFetchOptions } from "./instrumentation-runtime.cjs"
23
+ */
24
+
25
+ /**
26
+ * @typedef {{
27
+ * readonly appState: AppStateInput | undefined,
28
+ * readonly client: LogBrewClient,
29
+ * readonly fetchImpl: unknown,
30
+ * readonly measureResponseBodySize: boolean,
31
+ * readonly metadata: Readonly<Metadata>,
32
+ * readonly metadataFactory: unknown,
33
+ * readonly now: () => string,
34
+ * readonly nowMs: () => number,
35
+ * readonly platform: PlatformInput | undefined,
36
+ * readonly randomValues: RandomValues | undefined,
37
+ * readonly routeTemplate: string | undefined,
38
+ * readonly routeTemplateFactory: Callable,
39
+ * readonly screen: string | undefined,
40
+ * readonly sessionId: string | undefined,
41
+ * readonly trace: TraceInput | undefined,
42
+ * readonly traceFlags: string,
43
+ * readonly tracePropagationTargets: readonly TracePropagationTarget[]
44
+ * }} ResourceFetchSettings
45
+ * @typedef {{
46
+ * readonly init: unknown,
47
+ * readonly input: unknown,
48
+ * readonly method: string,
49
+ * readonly routeTemplate: unknown,
50
+ * readonly startedAtMs: number,
51
+ * readonly timestamp: string,
52
+ * readonly trace: TraceInput,
53
+ * readonly url: string
54
+ * }} ResourceRequest
55
+ */
56
+
57
+ /**
58
+ * @param {unknown} input
59
+ * @param {unknown} init
60
+ * @returns {string}
61
+ */
299
62
  function requestMethod(input, init) {
300
- const method = init?.method ?? input?.method ?? "GET";
301
- return String(method).toUpperCase();
302
- }
303
-
304
- function resourceTraceContext({ randomValues, trace, traceFlags }) {
305
- if (typeof trace === "string") {
306
- return createReactNativeTraceContext({ randomValues, traceFlags, traceparent: trace });
307
- }
308
- return trace ?? getActiveLogBrewTrace() ?? createReactNativeTraceContext({ randomValues, traceFlags });
63
+ return toText(readField(init, "method") ?? readField(input, "method") ?? "GET").toUpperCase();
309
64
  }
310
65
 
66
+ /**
67
+ * @param {unknown} input
68
+ * @returns {string}
69
+ */
311
70
  function requestUrl(input) {
312
71
  if (typeof input === "string") {
313
72
  return input;
314
73
  }
315
- const URLConstructor = globalThis.URL;
316
- if (typeof URLConstructor === "function" && input instanceof URLConstructor) {
74
+ const URLConstructor = urlConstructor();
75
+ if (URLConstructor !== undefined && input instanceof URLConstructor) {
317
76
  return input.toString();
318
77
  }
319
- if (typeof input?.url === "string") {
320
- return input.url;
78
+ const url = readField(input, "url");
79
+ if (typeof url === "string") {
80
+ return url;
321
81
  }
322
- return String(input);
82
+ return toText(input);
323
83
  }
324
84
 
325
- function defaultRouteTemplateFactory({ url }) {
326
- const URLConstructor = globalThis.URL;
327
- if (typeof URLConstructor === "function") {
328
- try {
329
- const parsedUrl = new URLConstructor(url, "https://logbrew.local");
330
- return parsedUrl.pathname;
331
- } catch {
332
- // Fall back to query/hash stripping below for non-standard request keys.
333
- }
85
+ /**
86
+ * @param {ResourceFetchSettings} settings
87
+ * @returns {TraceInput}
88
+ */
89
+ function resourceTraceContext({ randomValues, trace, traceFlags }) {
90
+ if (typeof trace === "string") {
91
+ return indexRuntime.createReactNativeTraceContext({ randomValues, traceFlags, traceparent: trace });
334
92
  }
335
- return String(url).split(/[?#]/u, 1)[0];
336
- }
337
-
338
- function elapsedMs(startedAtMs, nowMs) {
339
- const durationMs = nowMs() - startedAtMs;
340
- return Number.isFinite(durationMs) ? Math.max(0, durationMs) : undefined;
93
+ return trace ?? indexRuntime.getActiveLogBrewTrace() ?? indexRuntime.createReactNativeTraceContext({ randomValues, traceFlags });
341
94
  }
342
95
 
96
+ /**
97
+ * @param {unknown} response
98
+ * @returns {number | undefined}
99
+ */
343
100
  function responseStatusCode(response) {
344
- return typeof response?.status === "number" && Number.isFinite(response.status) ? response.status : undefined;
101
+ const status = readField(response, "status");
102
+ return typeof status === "number" && Number.isFinite(status) ? status : undefined;
345
103
  }
346
104
 
347
- async function responseSizeBytesFromResponse(response, { measureResponseBodySize = false } = {}) {
348
- const contentLength = responseContentLengthBytes(response);
349
- if (contentLength !== undefined) {
350
- return contentLength;
351
- }
352
- return measureResponseBodySize ? clonedResponseBodySizeBytes(response) : undefined;
353
- }
354
-
355
- function responseContentLengthBytes(response) {
356
- const header = responseHeader(response, "Content-Length");
357
- const value = Number.parseInt(String(header ?? ""), 10);
358
- return Number.isFinite(value) && value >= 0 ? value : undefined;
359
- }
360
-
361
- function responseHeader(response, name) {
362
- if (typeof response?.headers?.get !== "function") {
363
- return undefined;
364
- }
365
- try {
366
- return response.headers.get(name) ?? response.headers.get(name.toLowerCase()) ?? undefined;
367
- } catch {
368
- return undefined;
369
- }
370
- }
371
-
372
- async function clonedResponseBodySizeBytes(response) {
373
- if (typeof response?.clone !== "function") {
374
- return undefined;
375
- }
376
- let clonedResponse;
377
- try {
378
- clonedResponse = response.clone();
379
- } catch {
380
- return undefined;
381
- }
382
- return responseBodySizeBytes(clonedResponse);
105
+ /**
106
+ * @param {ResourceFetchSettings} settings
107
+ * @param {ResourceRequest} request
108
+ * @param {unknown} response
109
+ * @returns {Promise<void>}
110
+ */
111
+ async function captureResourceResponse(settings, request, response) {
112
+ const responseStartDurationMs = elapsedMs(request.startedAtMs, settings.nowMs);
113
+ const statusCode = responseStatusCode(response);
114
+ const responseSizeBytes = await responseSizeBytesFromResponse(response, settings.measureResponseBodySize);
115
+ const durationMs = elapsedMs(request.startedAtMs, settings.nowMs);
116
+ indexRuntime.captureReactNativeResourceSpan(settings.client, {
117
+ appState: settings.appState,
118
+ durationMs,
119
+ metadata: {
120
+ ...metadataRuntime.createSafeReactNativeMetadata(settings.metadata, settings.metadataFactory, {
121
+ durationMs,
122
+ init: request.init,
123
+ input: request.input,
124
+ method: request.method,
125
+ response,
126
+ responseSizeBytes,
127
+ responseStartDurationMs,
128
+ routeTemplate: request.routeTemplate,
129
+ statusCode,
130
+ url: request.url
131
+ }),
132
+ responseStartDurationMs
133
+ },
134
+ method: request.method,
135
+ platform: settings.platform,
136
+ responseSizeBytes,
137
+ routeTemplate: request.routeTemplate,
138
+ screen: settings.screen,
139
+ sessionId: settings.sessionId,
140
+ statusCode,
141
+ timestamp: request.timestamp,
142
+ trace: request.trace
143
+ });
383
144
  }
384
145
 
385
- async function responseBodySizeBytes(response) {
386
- const arrayBufferSize = await responseArrayBufferSizeBytes(response);
387
- if (arrayBufferSize !== undefined) {
388
- return arrayBufferSize;
389
- }
390
- const blobSize = await responseBlobSizeBytes(response);
391
- if (blobSize !== undefined) {
392
- return blobSize;
393
- }
394
- return responseTextSizeBytes(response);
146
+ /**
147
+ * @param {ResourceFetchSettings} settings
148
+ * @param {ResourceRequest} request
149
+ * @param {unknown} error
150
+ * @returns {void}
151
+ */
152
+ function captureResourceFailure(settings, request, error) {
153
+ const durationMs = elapsedMs(request.startedAtMs, settings.nowMs);
154
+ indexRuntime.captureReactNativeResourceSpan(settings.client, {
155
+ appState: settings.appState,
156
+ durationMs,
157
+ metadata: {
158
+ ...metadataRuntime.createSafeReactNativeMetadata(settings.metadata, settings.metadataFactory, {
159
+ durationMs,
160
+ error,
161
+ init: request.init,
162
+ input: request.input,
163
+ method: request.method,
164
+ routeTemplate: request.routeTemplate,
165
+ status: "error",
166
+ url: request.url
167
+ }),
168
+ fetchErrorName: errorName(error),
169
+ fetchErrorValueType: typeof error
170
+ },
171
+ method: request.method,
172
+ platform: settings.platform,
173
+ routeTemplate: request.routeTemplate,
174
+ screen: settings.screen,
175
+ sessionId: settings.sessionId,
176
+ status: "error",
177
+ timestamp: request.timestamp,
178
+ trace: request.trace
179
+ });
395
180
  }
396
181
 
397
- async function responseArrayBufferSizeBytes(response) {
398
- if (typeof response?.arrayBuffer !== "function") {
399
- return undefined;
400
- }
401
- try {
402
- return binaryByteLength(await response.arrayBuffer());
403
- } catch {
404
- return undefined;
405
- }
406
- }
182
+ /**
183
+ * @param {ResourceFetchSettings} settings
184
+ * @param {unknown} input
185
+ * @param {unknown} init
186
+ * @returns {{ readonly request: ResourceRequest, readonly tracedFetch: (input: unknown, init?: unknown) => unknown }}
187
+ */
188
+ function prepareResourceRequest(settings, input, init) {
189
+ const startedAtMs = settings.nowMs();
190
+ const timestamp = settings.now();
191
+ const trace = resourceTraceContext(settings);
192
+ const tracedFetch = indexRuntime.createTraceparentFetch({
193
+ fetchImpl: settings.fetchImpl,
194
+ trace,
195
+ tracePropagationTargets: settings.tracePropagationTargets
196
+ });
197
+ const method = requestMethod(input, init);
198
+ const url = requestUrl(input);
199
+ const routeTemplate = settings.routeTemplate ?? settings.routeTemplateFactory({
200
+ input,
407
201
 
408
- async function responseBlobSizeBytes(response) {
409
- if (typeof response?.blob !== "function") {
410
- return undefined;
411
- }
412
- try {
413
- const blob = await response.blob();
414
- return typeof blob?.size === "number" && Number.isFinite(blob.size) && blob.size >= 0 ? blob.size : undefined;
415
- } catch {
416
- return undefined;
417
- }
202
+ init,
203
+ url
204
+ });
205
+ return { request: { init, input, method, routeTemplate, startedAtMs, timestamp, trace, url }, tracedFetch };
418
206
  }
419
207
 
420
- async function responseTextSizeBytes(response) {
421
- if (typeof response?.text !== "function") {
422
- return undefined;
423
- }
208
+ /**
209
+ * @param {ResourceFetchSettings} settings
210
+ * @param {unknown} input
211
+ * @param {unknown} init
212
+ * @returns {Promise<unknown>}
213
+ */
214
+ async function runResourceFetch(settings, input, init) {
215
+ const { request, tracedFetch } = prepareResourceRequest(settings, input, init);
424
216
  try {
425
- const text = await response.text();
426
- return typeof text === "string" || text instanceof String ? utf8ByteLength(text.toString()) : undefined;
427
- } catch {
428
- return undefined;
217
+ const response = await tracedFetch(input, init);
218
+ await captureResourceResponse(settings, request, response);
219
+ return response;
220
+ } catch (error) {
221
+ captureResourceFailure(settings, request, error);
222
+ throw error;
429
223
  }
430
224
  }
431
225
 
432
- function binaryByteLength(value) {
433
- if (typeof value?.byteLength === "number" && Number.isFinite(value.byteLength) && value.byteLength >= 0) {
434
- return value.byteLength;
226
+ /**
227
+ * @param {LogBrewClient} client
228
+ * @param {ResourceFetchOptions} [options]
229
+ * @returns {(input: unknown, init?: unknown) => Promise<unknown>}
230
+ */
231
+ function createReactNativeResourceFetch(client, {
232
+ appState,
233
+ fetchImpl,
234
+ metadata = {},
235
+ metadataFactory,
236
+ measureResponseBodySize = false,
237
+ now = () => new Date().toISOString(),
238
+ nowMs = () => Date.now(),
239
+ platform,
240
+ randomValues,
241
+ routeTemplate,
242
+ routeTemplateFactory = defaultRouteTemplateFactory,
243
+ screen,
244
+ sessionId,
245
+ trace,
246
+ traceFlags = "01",
247
+ tracePropagationTargets = []
248
+ } = {}) {
249
+ if (!isCallable(routeTemplateFactory)) {
250
+ throw new SdkError("configuration_error", "routeTemplateFactory must be a function");
435
251
  }
436
- return undefined;
437
- }
438
-
439
- function utf8ByteLength(value) {
440
- let bytes = 0;
441
- for (let index = 0; index < value.length; index += 1) {
442
- const code = value.charCodeAt(index);
443
- if (code <= 0x7f) {
444
- bytes += 1;
445
- } else if (code <= 0x7ff) {
446
- bytes += 2;
447
- } else if (code >= 0xd800 && code <= 0xdbff && index + 1 < value.length) {
448
- const next = value.charCodeAt(index + 1);
449
- if (next >= 0xdc00 && next <= 0xdfff) {
450
- bytes += 4;
451
- index += 1;
452
- } else {
453
- bytes += 3;
454
- }
455
- } else {
456
- bytes += 3;
457
- }
252
+ if (metadataFactory !== undefined && typeof metadataFactory !== "function") {
253
+ throw new SdkError("configuration_error", "metadataFactory must be a function");
458
254
  }
459
- return bytes;
460
- }
461
-
462
- function errorName(error) {
463
- return typeof error?.name === "string" && error.name.trim() !== "" ? error.name : "Error";
255
+ /** @type {ResourceFetchSettings} */
256
+ const settings = {
257
+ appState, client, fetchImpl, measureResponseBodySize, metadata, metadataFactory, now, nowMs, platform,
258
+ randomValues, routeTemplate, routeTemplateFactory, screen, sessionId, trace, traceFlags, tracePropagationTargets
259
+ };
260
+ return async function logBrewResourceFetch(input, init) {
261
+ return runResourceFetch(settings, input, init);
262
+ };
464
263
  }
465
264
 
466
265
  module.exports = {