@logbrew/react-native 0.1.38 → 0.1.40

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 (104) hide show
  1. package/LogBrewReactNative.podspec +1 -1
  2. package/README.md +17 -15
  3. package/android-native-diagnostics.d.ts +15 -5
  4. package/android-native-diagnostics.js +170 -94
  5. package/apollo.cjs +435 -226
  6. package/apollo.d.cts +2 -70
  7. package/apollo.d.ts +24 -12
  8. package/apollo.js +438 -221
  9. package/apple-native-diagnostics-config.js +176 -0
  10. package/apple-native-diagnostics-context.js +232 -0
  11. package/apple-native-diagnostics-module.js +229 -0
  12. package/apple-native-diagnostics.d.ts +42 -11
  13. package/apple-native-diagnostics.js +60 -389
  14. package/expo.cjs +29 -16
  15. package/expo.d.ts +10 -9
  16. package/expo.js +4 -3
  17. package/fatal-admission.cjs +113 -0
  18. package/fatal-record.cjs +317 -0
  19. package/fatal-replay.cjs +297 -508
  20. package/global-errors-capture.cjs +369 -0
  21. package/global-errors-event.cjs +174 -0
  22. package/global-errors-support.cjs +128 -0
  23. package/global-errors.cjs +75 -351
  24. package/global-errors.d.cts +29 -278
  25. package/global-errors.d.ts +57 -27
  26. package/global-errors.js +7 -2
  27. package/global-errors.native.js +83 -48
  28. package/index-breadcrumbs.cjs +139 -0
  29. package/index-errors.cjs +167 -0
  30. package/index-events.cjs +365 -0
  31. package/index-navigation.cjs +327 -0
  32. package/index-random.cjs +120 -0
  33. package/index-react.cjs +189 -0
  34. package/index-spans.cjs +190 -0
  35. package/index-trace-fetch.cjs +322 -0
  36. package/index-trace.cjs +335 -0
  37. package/index-transport.cjs +201 -0
  38. package/index-values.cjs +232 -0
  39. package/index.cjs +95 -1220
  40. package/index.d.cts +2 -505
  41. package/index.d.ts +130 -469
  42. package/index.native.d.ts +146 -22
  43. package/index.native.js +184 -159
  44. package/instrumentation-fetch.cjs +113 -0
  45. package/instrumentation-install.cjs +241 -0
  46. package/instrumentation-runtime.cjs +65 -0
  47. package/instrumentation-teardown.cjs +93 -0
  48. package/instrumentation-values.cjs +282 -0
  49. package/instrumentation-xhr-request.cjs +298 -0
  50. package/instrumentation-xhr.cjs +233 -0
  51. package/instrumentation.cjs +110 -599
  52. package/instrumentation.d.cts +2 -84
  53. package/instrumentation.d.ts +22 -8
  54. package/ios/AppleDiagnostics/LBRNAppleNativeDiagnostics.swift +1 -1
  55. package/ios/GeneratedAppleDiagnostics/LogBrew/DeliveryEngine.swift +7 -1
  56. package/ios/GeneratedAppleDiagnostics/LogBrew/DeliveryEngineAutomatic.swift +36 -4
  57. package/ios/GeneratedAppleDiagnostics/LogBrew/DeliveryEngineQueue.swift +17 -0
  58. package/ios/GeneratedAppleDiagnostics/LogBrew/DeliveryLifecycle.swift +2 -0
  59. package/ios/GeneratedAppleDiagnostics/LogBrew/Transport.swift +41 -6
  60. package/ios/GeneratedAppleDiagnostics/SOURCE-MANIFEST.json +5 -5
  61. package/lifecycle.cjs +181 -78
  62. package/lifecycle.d.cts +1 -50
  63. package/lifecycle.d.ts +17 -6
  64. package/metadata.cjs +279 -114
  65. package/metro-debug-id.cjs +296 -0
  66. package/metro-serializer.cjs +219 -0
  67. package/metro.cjs +153 -297
  68. package/metro.d.cts +2 -57
  69. package/metro.d.ts +27 -13
  70. package/metro.js +2 -3
  71. package/native-bridge-async.cjs +165 -0
  72. package/native-bridge-scope.cjs +148 -0
  73. package/native-bridge.cjs +83 -186
  74. package/native-bridge.d.cts +2 -94
  75. package/native-bridge.d.ts +28 -15
  76. package/native-client-bindings.js +230 -0
  77. package/native-diagnostics-values.js +120 -0
  78. package/native-module-lookup.js +31 -0
  79. package/native-null.js +3 -0
  80. package/null-value.cjs +4 -0
  81. package/package.json +44 -2
  82. package/persistent-delivery-store.js +247 -0
  83. package/persistent-delivery.native.js +183 -261
  84. package/promise-rejection-handlers.cjs +368 -0
  85. package/promise-rejections.cjs +169 -361
  86. package/react-native.config.js +3 -1
  87. package/release-artifacts-files.cjs +94 -0
  88. package/release-artifacts-options.cjs +182 -0
  89. package/release-artifacts.cjs +278 -207
  90. package/release-artifacts.d.cts +2 -55
  91. package/release-artifacts.d.ts +18 -7
  92. package/release-artifacts.js +2 -4
  93. package/resource-fetch-graphql.cjs +265 -0
  94. package/resource-fetch-size.cjs +156 -0
  95. package/resource-fetch.cjs +227 -428
  96. package/resource-fetch.d.cts +1 -60
  97. package/resource-fetch.d.ts +17 -6
  98. package/scripts/sync-apple-native-sources.mjs +101 -53
  99. package/types/capture.d.ts +95 -0
  100. package/types/config.d.ts +85 -0
  101. package/types/defaults.d.ts +55 -0
  102. package/types/events.d.ts +203 -0
  103. package/types/provider.d.ts +81 -0
  104. package/types/trace.d.ts +104 -0
package/apollo.js CHANGED
@@ -1,166 +1,282 @@
1
- import { SdkError } from "@logbrew/sdk";
2
1
  import {
3
- captureReactNativeResourceSpan,
4
- createReactNativeTraceContext,
5
- createReactNativeTraceHeaders,
6
- getActiveLogBrewTrace
2
+ captureReactNativeResourceSpan, createReactNativeTraceContext, createReactNativeTraceHeaders, getActiveLogBrewTrace
7
3
  } from "./index.js";
8
- import {
9
- safeReactNativeMetadataFactoryResult
10
- } from "./metadata.js";
4
+ import { SdkError } from "@logbrew/sdk";
5
+ import { safeReactNativeMetadataFactoryResult } from "./metadata.js";
6
+
7
+ /**
8
+ * @import { LogBrewClient, Metadata } from "@logbrew/sdk"
9
+ * @import {
10
+ * ReactNativeTraceContext,
11
+ * ReactNativeTraceContextConfig
12
+ * } from "./index.js"
13
+ * @typedef {(length: number) => Uint8Array} RandomValues
14
+ * @typedef {{
15
+ * readonly OS?: string,
16
+ * readonly Version?: string | number,
17
+ * readonly isPad?: boolean,
18
+ * readonly constants?: { readonly isTesting?: boolean, readonly [key: string]: unknown }
19
+ * }} PlatformLike
20
+ * @typedef {{
21
+ * readonly currentState?: string | null,
22
+ * readonly addEventListener?: (type: "change", listener: (state: string) => void) => { readonly remove: () => void } | (() => void)
23
+ * }} AppStateLike
24
+ * @typedef {{ readonly operationName: string | undefined, readonly operationType: string | undefined }} ApolloOperationDetails
25
+ * @typedef {"ok" | "error"} ApolloSpanStatus
26
+ * @typedef {(this: unknown, ...args: readonly unknown[]) => unknown} Callable
27
+ * @typedef {{
28
+ * readonly durationMs: number | undefined,
29
+ * readonly error: unknown,
30
+ * readonly operationName: string | undefined,
31
+ * readonly operationType: string | undefined,
32
+ * readonly screen: string | undefined,
33
+ * readonly status: ApolloSpanStatus
34
+ * }} ApolloMetadataContext
35
+ * @typedef {{
36
+ * readonly ApolloLink?: unknown,
37
+ * readonly appState?: AppStateLike | undefined,
38
+ * readonly metadata?: Readonly<Metadata> | undefined,
39
+ * readonly metadataFactory?: unknown,
40
+ * readonly now?: (() => string) | undefined,
41
+ * readonly nowMs?: (() => number) | undefined,
42
+ * readonly platform?: PlatformLike | undefined,
43
+ * readonly propagateTraceparent?: boolean | undefined,
44
+ * readonly randomValues?: RandomValues | undefined,
45
+ * readonly screen?: string | undefined,
46
+ * readonly sessionId?: string | undefined,
47
+ * readonly trace?: Readonly<ReactNativeTraceContext> | string | undefined,
48
+ * readonly traceFlags?: string | undefined
49
+ * }} ApolloLinkOptions
50
+ * @typedef {{
51
+ * readonly activeTrace: Readonly<ReactNativeTraceContext>,
52
+ * readonly appState: AppStateLike | undefined,
53
+ * readonly client: LogBrewClient,
54
+ * readonly details: ApolloOperationDetails,
55
+ * readonly metadata: Readonly<Metadata>,
56
+ * readonly metadataFactory: Callable | undefined,
57
+ * readonly now: () => string,
58
+ * readonly nowMs: () => number,
59
+ * readonly platform: PlatformLike | undefined,
60
+ * readonly screen: string | undefined,
61
+ * readonly sessionId: string | undefined,
62
+ * readonly startedAtMs: number,
63
+ * readonly timestamp: string
64
+ * }} ApolloSpanOptions
65
+ * @typedef {Omit<ApolloSpanOptions, "activeTrace" | "details" | "startedAtMs" | "timestamp"> & {
66
+ * readonly propagateTraceparent: boolean,
67
+ * readonly randomValues: RandomValues | undefined,
68
+ * readonly trace: Readonly<ReactNativeTraceContext> | string | undefined,
69
+ * readonly traceFlags: string
70
+ * }} ApolloLinkSettings
71
+ * @typedef {{ readonly durationMs: number | undefined, readonly error?: unknown, readonly graphqlErrorCount?: number, readonly status: ApolloSpanStatus }} ApolloSpanOutcome
72
+ */
11
73
 
12
74
  const MAX_GRAPHQL_OPERATION_NAME_CHARS = 128;
13
75
  const GRAPHQL_OPERATION_NAME_RE = /^[_A-Za-z][_0-9A-Za-z]*$/u;
76
+ /** @type {ReadonlySet<unknown>} */
14
77
  const GRAPHQL_OPERATION_TYPES = new Set(["query", "mutation", "subscription"]);
78
+ const EMPTY_LENGTH = 0;
79
+ const NO_ERRORS = 0;
80
+ const MIN_DURATION_MS = 0;
15
81
 
16
- export function createReactNativeApolloLink(client, {
17
- ApolloLink,
18
- appState,
19
- metadata = {},
20
- metadataFactory,
21
- now = () => new Date().toISOString(),
22
- nowMs = () => Date.now(),
23
- platform,
24
- propagateTraceparent = true,
25
- randomValues,
26
- screen,
27
- sessionId,
28
- trace,
29
- traceFlags = "01"
30
- } = {}) {
31
- if (typeof ApolloLink !== "function") {
32
- throw new SdkError("configuration_error", "createReactNativeApolloLink requires an app-provided ApolloLink constructor");
82
+ /**
83
+ * @param {unknown} value
84
+ * @param {string} key
85
+ * @returns {unknown}
86
+ */
87
+ function field(value, key) {
88
+ return (typeof value === "object" && value !== null) || typeof value === "function" ? Reflect.get(value, key) : undefined;
89
+ }
90
+
91
+ /**
92
+ * @param {unknown} value
93
+ * @returns {value is Callable}
94
+ */
95
+ function isCallable(value) {
96
+ return typeof value === "function";
97
+ }
98
+
99
+ /**
100
+ * @param {unknown} value
101
+ * @returns {string | undefined}
102
+ */
103
+ function safeGraphqlOperationName(value) {
104
+ if (typeof value !== "string") {
105
+ return undefined;
33
106
  }
34
- if (metadataFactory !== undefined && typeof metadataFactory !== "function") {
35
- throw new SdkError("configuration_error", "metadataFactory must be a function");
107
+ const name = value.trim();
108
+ if (
109
+ name.length === EMPTY_LENGTH ||
110
+ name.length > MAX_GRAPHQL_OPERATION_NAME_CHARS ||
111
+ !GRAPHQL_OPERATION_NAME_RE.test(name)
112
+ ) {
113
+ return undefined;
36
114
  }
115
+ return name;
116
+ }
37
117
 
38
- return new ApolloLink((operation, forward) => {
39
- if (typeof forward !== "function") {
40
- throw new SdkError("configuration_error", "createReactNativeApolloLink requires Apollo forward");
41
- }
118
+ /**
119
+ * @param {number} startedAtMs
120
+ * @param {() => number} nowMs
121
+ * @returns {number | undefined}
122
+ */
123
+ function elapsedMs(startedAtMs, nowMs) {
124
+ const durationMs = nowMs() - startedAtMs;
125
+ return Number.isFinite(durationMs) ? Math.max(MIN_DURATION_MS, durationMs) : undefined;
126
+ }
42
127
 
43
- const startedAtMs = nowMs();
44
- const timestamp = now();
45
- const activeTrace = apolloTraceContext({ randomValues, trace, traceFlags });
46
- const details = apolloOperationDetails(operation);
47
- if (propagateTraceparent) {
48
- setOperationTraceparent(operation, activeTrace);
49
- }
128
+ /**
129
+ * @param {unknown} error
130
+ * @returns {string | undefined}
131
+ */
132
+ function errorName(error) {
133
+ if (error instanceof Error && typeof error.name === "string" && error.name.trim() !== "") {
134
+ return error.name;
135
+ }
136
+ const name = field(error, "name");
137
+ if (typeof name === "string" && name.trim() !== "") {
138
+ return name;
139
+ }
140
+ return undefined;
141
+ }
50
142
 
51
- let forwarded;
52
- try {
53
- forwarded = forward(operation);
54
- } catch (error) {
55
- captureApolloSpan(client, {
56
- activeTrace,
57
- appState,
58
- details,
59
- durationMs: elapsedMs(startedAtMs, nowMs),
60
- error,
61
- metadata,
62
- metadataFactory,
63
- now,
64
- platform,
65
- screen,
66
- sessionId,
67
- status: "error",
68
- timestamp
69
- });
70
- throw error;
71
- }
143
+ /**
144
+ * @param {unknown} value
145
+ * @returns {number}
146
+ */
147
+ function graphqlErrorCountFromResult(value) {
148
+ const errors = field(value, "errors");
149
+ return Array.isArray(errors) ? errors.length : NO_ERRORS;
150
+ }
72
151
 
73
- if (!forwarded || typeof forwarded.subscribe !== "function") {
74
- throw new SdkError("configuration_error", "Apollo forward must return an observable-like value");
75
- }
152
+ /**
153
+ * @param {unknown} candidate
154
+ * @returns {boolean}
155
+ */
156
+ function isOperationDefinition(candidate) {
157
+ return field(candidate, "kind") === "OperationDefinition" && GRAPHQL_OPERATION_TYPES.has(field(candidate, "operation"));
158
+ }
76
159
 
77
- return apolloObservable(forwarded, {
78
- activeTrace,
79
- appState,
80
- client,
81
- details,
82
- metadata,
83
- metadataFactory,
84
- now,
85
- nowMs,
86
- platform,
87
- screen,
88
- sessionId,
89
- startedAtMs,
90
- timestamp
91
- });
92
- });
160
+ /**
161
+ * @param {unknown} definitions
162
+ * @returns {unknown}
163
+ */
164
+ function findOperationDefinition(definitions) {
165
+ const find = field(definitions, "find");
166
+ if (isCallable(find)) {
167
+ return find.call(
168
+ definitions,
169
+ /**
170
+ * @param {unknown} candidate
171
+ * @returns {boolean}
172
+ */
173
+ (candidate) => isOperationDefinition(candidate)
174
+ );
175
+ }
176
+ if (find !== undefined && find !== null) {
177
+ throw new TypeError("operation?.query?.definitions?.find is not a function");
178
+ }
179
+ return undefined;
93
180
  }
94
181
 
95
- function apolloObservable(forwarded, options) {
182
+ /**
183
+ * @param {unknown} operation
184
+ * @returns {ApolloOperationDetails}
185
+ */
186
+ function apolloOperationDetails(operation) {
187
+ const definition = findOperationDefinition(field(field(operation, "query"), "definitions"));
188
+ const operationType = field(definition, "operation");
96
189
  return {
97
- subscribe(observerOrNext, onError, onComplete) {
98
- const observer = apolloObserver(observerOrNext, onError, onComplete);
99
- let finished = false;
100
- let graphqlErrorCount = 0;
190
+ operationName: safeGraphqlOperationName(field(operation, "operationName")) ?? safeGraphqlOperationName(field(field(definition, "name"), "value")),
191
+ operationType: typeof operationType === "string" && GRAPHQL_OPERATION_TYPES.has(operationType) ? operationType : undefined
192
+ };
193
+ }
101
194
 
102
- const finish = ({ error, status }) => {
103
- if (finished) {
104
- return;
105
- }
106
- finished = true;
107
- captureApolloSpan(options.client, {
108
- activeTrace: options.activeTrace,
109
- appState: options.appState,
110
- details: options.details,
111
- durationMs: elapsedMs(options.startedAtMs, options.nowMs),
112
- error,
113
- graphqlErrorCount,
114
- metadata: options.metadata,
115
- metadataFactory: options.metadataFactory,
116
- now: options.now,
117
- platform: options.platform,
118
- screen: options.screen,
119
- sessionId: options.sessionId,
120
- status,
121
- timestamp: options.timestamp
122
- });
123
- };
195
+ /**
196
+ * @param {ApolloOperationDetails} details
197
+ * @returns {string}
198
+ */
199
+ function apolloSpanName({ operationName, operationType }) {
200
+ const base = `graphql.${operationType ?? "operation"}`;
201
+ return operationName === undefined || operationName === "" ? base : `${base} ${operationName}`;
202
+ }
124
203
 
125
- try {
126
- return forwarded.subscribe({
127
- next(value) {
128
- graphqlErrorCount += graphqlErrorCountFromResult(value);
129
- observer.next?.(value);
130
- },
131
- error(error) {
132
- finish({ error, status: "error" });
133
- observer.error?.(error);
134
- },
135
- complete() {
136
- finish({ status: graphqlErrorCount > 0 ? "error" : "ok" });
137
- observer.complete?.();
138
- }
139
- });
140
- } catch (error) {
141
- finish({ error, status: "error" });
142
- throw error;
143
- }
144
- }
145
- };
204
+ /**
205
+ * @param {RandomValues | undefined} randomValues
206
+ * @param {string} traceFlags
207
+ * @returns {ReactNativeTraceContextConfig}
208
+ */
209
+ function traceConfig(randomValues, traceFlags) {
210
+ return randomValues === undefined ? { traceFlags } : { randomValues, traceFlags };
146
211
  }
147
212
 
148
- function captureApolloSpan(client, {
149
- activeTrace,
150
- appState,
151
- details,
152
- durationMs,
153
- error,
154
- graphqlErrorCount,
155
- metadata,
156
- metadataFactory,
157
- now,
158
- platform,
159
- screen,
160
- sessionId,
161
- status,
162
- timestamp
163
- }) {
213
+ /**
214
+ * @param {Pick<ApolloLinkSettings, "randomValues" | "trace" | "traceFlags">} settings
215
+ * @returns {Readonly<ReactNativeTraceContext>}
216
+ */
217
+ function apolloTraceContext({ randomValues, trace, traceFlags }) {
218
+ if (typeof trace === "string") {
219
+ return createReactNativeTraceContext({ ...traceConfig(randomValues, traceFlags), traceparent: trace });
220
+ }
221
+ return trace ?? getActiveLogBrewTrace() ?? createReactNativeTraceContext(traceConfig(randomValues, traceFlags));
222
+ }
223
+
224
+ /**
225
+ * @param {unknown} observerOrNext
226
+ * @param {unknown} onError
227
+ * @param {unknown} onComplete
228
+ * @returns {unknown}
229
+ */
230
+ function apolloObserver(observerOrNext, onError, onComplete) {
231
+ if (typeof observerOrNext === "function") {
232
+ return { complete: onComplete, error: onError, next: observerOrNext };
233
+ }
234
+ return observerOrNext !== null && observerOrNext !== undefined && typeof observerOrNext === "object" ? observerOrNext : {};
235
+ }
236
+
237
+ /**
238
+ * @param {unknown} observer
239
+ * @param {"complete" | "error" | "next"} name
240
+ * @param {readonly unknown[]} args
241
+ * @returns {void}
242
+ */
243
+ function callObserver(observer, name, args) {
244
+ const handler = field(observer, name);
245
+ if (isCallable(handler)) {
246
+ handler.call(observer, ...args);
247
+ } else if (handler !== undefined && handler !== null) {
248
+ throw new TypeError(`observer.${name} is not a function`);
249
+ }
250
+ }
251
+
252
+ /**
253
+ * @param {unknown} operation
254
+ * @param {Readonly<ReactNativeTraceContext>} trace
255
+ * @returns {void}
256
+ */
257
+ function setOperationTraceparent(operation, trace) {
258
+ const setContext = field(operation, "setContext");
259
+ if (!isCallable(setContext)) {
260
+ return;
261
+ }
262
+ const { traceparent } = createReactNativeTraceHeaders(trace);
263
+ setContext.call(
264
+ operation,
265
+ /**
266
+ * @param {{ readonly headers?: Readonly<Record<string, string>> }} [previous]
267
+ * @returns {{ headers: Record<string, string> }}
268
+ */
269
+ ({ headers = {} } = {}) => ({ headers: { ...headers, traceparent } })
270
+ );
271
+ }
272
+
273
+ /**
274
+ * @param {ApolloSpanOptions} options
275
+ * @param {ApolloSpanOutcome} outcome
276
+ * @returns {Metadata}
277
+ */
278
+ function apolloSpanMetadata({ details, metadata, metadataFactory, screen }, { durationMs, error, graphqlErrorCount, status }) {
279
+ /** @type {ApolloMetadataContext} */
164
280
  const context = {
165
281
  durationMs,
166
282
  error,
@@ -169,112 +285,213 @@ function captureApolloSpan(client, {
169
285
  screen,
170
286
  status
171
287
  };
288
+ /** @type {Metadata} */
289
+ const spanMetadata = {
290
+ ...metadata,
291
+ ...safeReactNativeMetadataFactoryResult(metadataFactory === undefined ? undefined : metadataFactory(context))
292
+ };
293
+ /** @type {ReadonlyArray<readonly [string, string | number | undefined]>} */
294
+ const apolloValues = [
295
+ ["errorName", errorName(error)],
296
+ ["errorValueType", error === undefined ? undefined : typeof error],
297
+ ["framework", "apollo-client"],
298
+ ["graphqlErrorCount", graphqlErrorCount !== undefined && graphqlErrorCount > NO_ERRORS ? graphqlErrorCount : undefined],
299
+ ["graphqlOperationName", details.operationName],
300
+ ["graphqlOperationType", details.operationType],
301
+ ["source", "react-native.apollo"]
302
+ ];
303
+ for (const [key, value] of apolloValues) {
304
+ if (value === undefined) {
305
+ Reflect.deleteProperty(spanMetadata, key);
306
+ } else {
307
+ spanMetadata[key] = value;
308
+ }
309
+ }
310
+ return spanMetadata;
311
+ }
312
+
313
+ /**
314
+ * @param {ApolloSpanOptions} options
315
+ * @param {ApolloSpanOutcome} outcome
316
+ * @returns {void}
317
+ */
318
+ function captureApolloSpan(options, outcome) {
319
+ const { activeTrace, appState, client, details, now, platform, screen, sessionId, timestamp } = options;
320
+ const { durationMs, status } = outcome;
172
321
  captureReactNativeResourceSpan(client, {
173
- appState,
174
- durationMs,
322
+ ...(appState === undefined ? {} : { appState }),
323
+ ...(durationMs === undefined ? {} : { durationMs }),
175
324
  kind: "graphql",
176
- metadata: {
177
- ...metadata,
178
- ...safeReactNativeMetadataFactoryResult(typeof metadataFactory === "function" ? metadataFactory(context) : undefined),
179
- errorName: errorName(error),
180
- errorValueType: error === undefined ? undefined : typeof error,
181
- framework: "apollo-client",
182
- graphqlErrorCount: graphqlErrorCount && graphqlErrorCount > 0 ? graphqlErrorCount : undefined,
183
- graphqlOperationName: details.operationName,
184
- graphqlOperationType: details.operationType,
185
- source: "react-native.apollo"
186
- },
325
+ metadata: apolloSpanMetadata(options, outcome),
187
326
  name: apolloSpanName(details),
188
327
  now,
189
- platform,
190
- screen,
191
- sessionId,
328
+ ...(platform === undefined ? {} : { platform }),
329
+ ...(screen === undefined ? {} : { screen }),
330
+ ...(sessionId === undefined ? {} : { sessionId }),
192
331
  status,
193
332
  timestamp,
194
333
  trace: activeTrace
195
334
  });
196
335
  }
197
336
 
198
- function setOperationTraceparent(operation, trace) {
199
- if (!operation || typeof operation.setContext !== "function") {
200
- return;
201
- }
202
- const traceparent = createReactNativeTraceHeaders(trace).traceparent;
203
- operation.setContext(({ headers = {} } = {}) => ({
204
- headers: {
205
- ...headers,
206
- traceparent
337
+ /**
338
+ * @param {unknown} forwarded
339
+ * @param {ApolloSpanOptions} options
340
+ * @param {unknown} observer
341
+ * @returns {unknown}
342
+ */
343
+ function subscribeWithSpan(forwarded, options, observer) {
344
+ let finished = false;
345
+ let graphqlErrorCount = NO_ERRORS;
346
+
347
+ /**
348
+ * @param {unknown} error
349
+ * @param {ApolloSpanStatus} status
350
+ * @returns {void}
351
+ */
352
+ function finish(error, status) {
353
+ if (finished) {
354
+ return;
207
355
  }
208
- }));
209
- }
356
+ finished = true;
357
+ captureApolloSpan(options, { durationMs: elapsedMs(options.startedAtMs, options.nowMs), error, graphqlErrorCount, status });
358
+ }
210
359
 
211
- function apolloOperationDetails(operation) {
212
- const definition = operation?.query?.definitions?.find?.((candidate) => (
213
- candidate?.kind === "OperationDefinition" && GRAPHQL_OPERATION_TYPES.has(candidate?.operation)
214
- ));
215
- return {
216
- operationName: safeGraphqlOperationName(operation?.operationName) ?? safeGraphqlOperationName(definition?.name?.value),
217
- operationType: GRAPHQL_OPERATION_TYPES.has(definition?.operation) ? definition.operation : undefined
218
- };
219
- }
360
+ try {
361
+ const subscribe = field(forwarded, "subscribe");
362
+ if (!isCallable(subscribe)) {
363
+ throw new TypeError("forwarded.subscribe is not a function");
364
+ }
365
+ return subscribe.call(forwarded, {
366
+ /** @param {unknown} value */
367
+ next(value) {
368
+ graphqlErrorCount += graphqlErrorCountFromResult(value);
369
+ callObserver(observer, "next", [value]);
370
+ },
220
371
 
221
- function apolloSpanName({ operationName, operationType }) {
222
- const base = `graphql.${operationType ?? "operation"}`;
223
- return operationName ? `${base} ${operationName}` : base;
224
- }
372
+ /** @param {unknown} error */
373
+ error(error) {
374
+ finish(error, "error");
375
+ callObserver(observer, "error", [error]);
376
+ },
225
377
 
226
- function apolloTraceContext({ randomValues, trace, traceFlags }) {
227
- if (typeof trace === "string") {
228
- return createReactNativeTraceContext({ randomValues, traceFlags, traceparent: trace });
378
+ complete() {
379
+ finish(undefined, graphqlErrorCount > NO_ERRORS ? "error" : "ok");
380
+ callObserver(observer, "complete", []);
381
+ }
382
+ });
383
+ } catch (error) {
384
+ finish(error, "error");
385
+ throw error;
229
386
  }
230
- return trace ?? getActiveLogBrewTrace() ?? createReactNativeTraceContext({ randomValues, traceFlags });
231
387
  }
232
388
 
233
- function apolloObserver(observerOrNext, onError, onComplete) {
234
- if (typeof observerOrNext === "function") {
235
- return {
236
- next: observerOrNext,
237
- error: onError,
238
- complete: onComplete
239
- };
389
+ /**
390
+ * @param {unknown} forwarded
391
+ * @param {ApolloSpanOptions} options
392
+ * @returns {{ subscribe: (observerOrNext: unknown, onError: unknown, onComplete: unknown) => unknown }}
393
+ */
394
+ function apolloObservable(forwarded, options) {
395
+ if (!isCallable(field(forwarded, "subscribe"))) {
396
+ throw new SdkError("configuration_error", "Apollo forward must return an observable-like value");
240
397
  }
241
- return observerOrNext && typeof observerOrNext === "object" ? observerOrNext : {};
398
+ return {
399
+ subscribe(observerOrNext, onError, onComplete) {
400
+ return subscribeWithSpan(forwarded, options, apolloObserver(observerOrNext, onError, onComplete));
401
+ }
402
+ };
242
403
  }
243
404
 
244
- function graphqlErrorCountFromResult(value) {
245
- return Array.isArray(value?.errors) ? value.errors.length : 0;
405
+ /**
406
+ * @param {Callable} forward
407
+ * @param {unknown} operation
408
+ * @param {ApolloSpanOptions} options
409
+ * @returns {unknown}
410
+ */
411
+ function forwardOperation(forward, operation, options) {
412
+ try {
413
+ return forward(operation);
414
+ } catch (error) {
415
+ captureApolloSpan(options, { durationMs: elapsedMs(options.startedAtMs, options.nowMs), error, status: "error" });
416
+ throw error;
417
+ }
246
418
  }
247
419
 
248
- function safeGraphqlOperationName(value) {
249
- if (typeof value !== "string") {
250
- return undefined;
420
+ /**
421
+ * @param {ApolloLinkSettings} settings
422
+ * @param {unknown} operation
423
+ * @param {unknown} forward
424
+ * @returns {unknown}
425
+ */
426
+ function handleApolloOperation(settings, operation, forward) {
427
+ if (!isCallable(forward)) {
428
+ throw new SdkError("configuration_error", "createReactNativeApolloLink requires Apollo forward");
251
429
  }
252
- const name = value.trim();
253
- if (
254
- name.length === 0 ||
255
- name.length > MAX_GRAPHQL_OPERATION_NAME_CHARS ||
256
- !GRAPHQL_OPERATION_NAME_RE.test(name)
257
- ) {
258
- return undefined;
430
+ const startedAtMs = settings.nowMs();
431
+ const timestamp = settings.now();
432
+ const activeTrace = apolloTraceContext(settings);
433
+ const details = apolloOperationDetails(operation);
434
+ if (settings.propagateTraceparent) {
435
+ setOperationTraceparent(operation, activeTrace);
259
436
  }
260
- return name;
261
- }
262
-
263
- function elapsedMs(startedAtMs, nowMs) {
264
- const durationMs = nowMs() - startedAtMs;
265
- return Number.isFinite(durationMs) ? Math.max(0, durationMs) : undefined;
437
+ /** @type {ApolloSpanOptions} */
438
+ const options = { ...settings, activeTrace, details, startedAtMs, timestamp };
439
+ return apolloObservable(forwardOperation(forward, operation, options), options);
266
440
  }
267
441
 
268
- function errorName(error) {
269
- if (error instanceof Error && typeof error.name === "string" && error.name.trim() !== "") {
270
- return error.name;
442
+ /**
443
+ * @param {LogBrewClient} client
444
+ * @param {ApolloLinkOptions} [options]
445
+ * @returns {unknown}
446
+ */
447
+ function createReactNativeApolloLink(client, {
448
+ ApolloLink,
449
+ appState,
450
+ metadata = {},
451
+ metadataFactory,
452
+ now = () => new Date().toISOString(),
453
+ nowMs = () => Date.now(),
454
+ platform,
455
+ propagateTraceparent = true,
456
+ randomValues,
457
+ screen,
458
+ sessionId,
459
+ trace,
460
+ traceFlags = "01"
461
+ } = {}) {
462
+ if (typeof ApolloLink !== "function") {
463
+ throw new SdkError("configuration_error", "createReactNativeApolloLink requires an app-provided ApolloLink constructor");
271
464
  }
272
- if (typeof error?.name === "string" && error.name.trim() !== "") {
273
- return error.name;
465
+ if (metadataFactory !== undefined && typeof metadataFactory !== "function") {
466
+ throw new SdkError("configuration_error", "metadataFactory must be a function");
274
467
  }
275
- return undefined;
468
+ /** @type {ApolloLinkSettings} */
469
+ const settings = {
470
+ appState,
471
+ client,
472
+ metadata,
473
+ metadataFactory: isCallable(metadataFactory) ? metadataFactory : undefined,
474
+ now,
475
+ nowMs,
476
+ platform,
477
+ propagateTraceparent,
478
+ randomValues,
479
+ screen,
480
+ sessionId,
481
+ trace,
482
+ traceFlags
483
+ };
484
+ return Reflect.construct(ApolloLink, [
485
+ /**
486
+ * @param {unknown} operation
487
+ * @param {unknown} forward
488
+ * @returns {unknown}
489
+ */
490
+ (operation, forward) => handleApolloOperation(settings, operation, forward)
491
+ ]);
276
492
  }
277
493
 
278
- export default {
279
- createReactNativeApolloLink
280
- };
494
+ const apollo = { createReactNativeApolloLink };
495
+
496
+ export { createReactNativeApolloLink };
497
+ export default apollo;