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