@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
@@ -0,0 +1,176 @@
1
+ import { hasControlCharacter, hasOwnKey, isRecord, utf8Length } from "./native-diagnostics-values.js";
2
+ import { SdkError } from "@logbrew/sdk";
3
+
4
+ /**
5
+ * @typedef {{
6
+ * apiKey: string,
7
+ * endpoint?: string,
8
+ * environment: string,
9
+ * fatalHandlerOwnership: "logbrew",
10
+ * hangThresholdSeconds?: number,
11
+ * projectId: string,
12
+ * release: string,
13
+ * service: string
14
+ * }} AppleInstallPayload
15
+ */
16
+
17
+ const ALLOWED_KEYS = new Set([
18
+ "apiKey",
19
+ "clientKey",
20
+ "endpoint",
21
+ "environment",
22
+ "fatalHandlerOwnership",
23
+ "hangThresholdSeconds",
24
+ "projectId",
25
+ "release",
26
+ "service"
27
+ ]);
28
+ const PROJECT_ID_PATTERN = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/u;
29
+ const DEFAULT_MAX_BYTES = 256;
30
+ const AUTH_KEY_BYTES = 4096;
31
+ const PROJECT_ID_BYTES = 64;
32
+ const ENDPOINT_BYTES = 2048;
33
+ const MIN_HANG_THRESHOLD_SECONDS = 1;
34
+ const MAX_HANG_THRESHOLD_SECONDS = 30;
35
+ const EMPTY_LENGTH = 0;
36
+
37
+ /**
38
+ * @param {string} message
39
+ * @returns {SdkError}
40
+ */
41
+ function configurationError(message) {
42
+ return new SdkError("configuration_error", `LogBrew Apple native diagnostics ${message}`);
43
+ }
44
+
45
+ /**
46
+ * @param {string} name
47
+ * @param {unknown} value
48
+ * @param {number} [maxBytes]
49
+ * @returns {string}
50
+ */
51
+ function exactString(name, value, maxBytes = DEFAULT_MAX_BYTES) {
52
+ if (typeof value !== "string"
53
+ || value.length === EMPTY_LENGTH
54
+ || value.trim() !== value
55
+ || hasControlCharacter(value)
56
+ || utf8Length(value) > maxBytes) {
57
+ throw configurationError(`${name} must be a non-empty bounded string without surrounding whitespace or control characters`);
58
+ }
59
+ return value;
60
+ }
61
+
62
+ /**
63
+ * @param {string} endpoint
64
+ * @returns {URL}
65
+ */
66
+ function parseEndpoint(endpoint) {
67
+ try {
68
+ return new URL(endpoint);
69
+ } catch {
70
+ throw configurationError("endpoint must be an absolute HTTPS URL");
71
+ }
72
+ }
73
+
74
+ /**
75
+ * @param {unknown} value
76
+ * @returns {string}
77
+ */
78
+ function exactDeliveryEndpoint(value) {
79
+ const endpoint = exactString("endpoint", value, ENDPOINT_BYTES);
80
+ const parsed = parseEndpoint(endpoint);
81
+ if (parsed.protocol !== "https:") {
82
+ throw configurationError("endpoint must use HTTPS");
83
+ }
84
+ if (parsed.username !== ""
85
+ || parsed.password !== ""
86
+ || parsed.search !== ""
87
+ || parsed.hash !== ""
88
+ || endpoint !== `${parsed.origin}${parsed.pathname}`) {
89
+ throw configurationError("endpoint must be a plain HTTPS path without embedded auth, query, or fragment values");
90
+ }
91
+ return endpoint;
92
+ }
93
+
94
+ /**
95
+ * @param {unknown} threshold
96
+ * @returns {number}
97
+ */
98
+ function hangThreshold(threshold) {
99
+ if (typeof threshold !== "number"
100
+ || !Number.isFinite(threshold)
101
+ || threshold < MIN_HANG_THRESHOLD_SECONDS
102
+ || threshold > MAX_HANG_THRESHOLD_SECONDS) {
103
+ throw configurationError("hangThresholdSeconds must be a finite number from 1 through 30");
104
+ }
105
+ return threshold;
106
+ }
107
+
108
+ /**
109
+ * @param {unknown} configuration
110
+ * @returns {Readonly<Record<string, unknown>>}
111
+ */
112
+ function knownConfiguration(configuration) {
113
+ if (!isRecord(configuration)) {
114
+ throw configurationError("configuration must be an object");
115
+ }
116
+ for (const key of Object.keys(configuration)) {
117
+ if (!ALLOWED_KEYS.has(key)) {
118
+ throw configurationError(`configuration contains unsupported key ${JSON.stringify(key)}`);
119
+ }
120
+ }
121
+ if (hasOwnKey(configuration, "apiKey") && hasOwnKey(configuration, "clientKey")) {
122
+ throw configurationError("apiKey and clientKey are mutually exclusive");
123
+ }
124
+ return configuration;
125
+ }
126
+
127
+ /**
128
+ * @param {Readonly<Record<string, unknown>>} configuration
129
+ * @returns {string}
130
+ */
131
+ function exactProjectId(configuration) {
132
+ const projectId = exactString("projectId", configuration["projectId"], PROJECT_ID_BYTES);
133
+ if (!PROJECT_ID_PATTERN.test(projectId)) {
134
+ throw configurationError("projectId must be a lowercase UUID");
135
+ }
136
+ return projectId;
137
+ }
138
+
139
+ /**
140
+ * @param {Readonly<Record<string, unknown>>} configuration
141
+ * @returns {{ endpoint?: string, hangThresholdSeconds?: number }}
142
+ */
143
+ function optionalSettings(configuration) {
144
+ const { endpoint, hangThresholdSeconds } = configuration;
145
+ return {
146
+ ...(endpoint === undefined ? {} : { endpoint: exactDeliveryEndpoint(endpoint) }),
147
+ ...(hangThresholdSeconds === undefined ? {} : { hangThresholdSeconds: hangThreshold(hangThresholdSeconds) })
148
+ };
149
+ }
150
+
151
+ /**
152
+ * @param {unknown} input
153
+ * @returns {AppleInstallPayload}
154
+ */
155
+ function normalizeConfiguration(input) {
156
+ const configuration = knownConfiguration(input);
157
+ const authKey = exactString("apiKey or clientKey", configuration["clientKey"] ?? configuration["apiKey"], AUTH_KEY_BYTES);
158
+ const projectId = exactProjectId(configuration);
159
+ if (configuration["fatalHandlerOwnership"] !== "logbrew") {
160
+ throw configurationError(
161
+ "fatalHandlerOwnership must be the exact string logbrew after confirming no other native fatal handler is installed"
162
+ );
163
+ }
164
+
165
+ return {
166
+ apiKey: authKey,
167
+ environment: exactString("environment", configuration["environment"]),
168
+ fatalHandlerOwnership: "logbrew",
169
+ projectId,
170
+ release: exactString("release", configuration["release"]),
171
+ service: exactString("service", configuration["service"]),
172
+ ...optionalSettings(configuration)
173
+ };
174
+ }
175
+
176
+ export { configurationError, normalizeConfiguration };
@@ -0,0 +1,232 @@
1
+ import { hasControlCharacter, isRecord } from "./native-diagnostics-values.js";
2
+ import { configurationError } from "./apple-native-diagnostics-config.js";
3
+
4
+ /**
5
+ * @typedef {{ traceId: string, spanId?: string, parentSpanId?: string, sampled?: boolean }} AppleTrace
6
+ * @typedef {{ id: string, previousId?: string }} AppleSession
7
+ * @typedef {{ id: string, kind: "anonymous" | "user" }} AppleSubject
8
+ * @typedef {{ failedAction: string, userVisibleOutcome?: string }} AppleImpact
9
+ * @typedef {{
10
+ * schemaVersion: 1,
11
+ * trace?: AppleTrace,
12
+ * session?: AppleSession,
13
+ * subject?: AppleSubject,
14
+ * impact?: AppleImpact
15
+ * }} AppleCorrelationContext
16
+ * @typedef {Readonly<{ maximum: number, name: string, rejectLocationText: boolean }>} DiagnosticTextRule
17
+ */
18
+
19
+ const SCHEMA_VERSION = 1;
20
+ const ONLY_SCHEMA_VERSION = 1;
21
+ const TRACE_ID_WIDTH = 32;
22
+ const SPAN_ID_WIDTH = 16;
23
+ const NO_UNKNOWN_FIELDS = 0;
24
+ const EMPTY_LENGTH = 0;
25
+ const FAILED_ACTION_LIMIT = 256;
26
+ const USER_VISIBLE_OUTCOME_LIMIT = 512;
27
+ const CONTEXT_KEYS = ["impact", "schemaVersion", "session", "subject", "trace"];
28
+ const TRACE_KEYS = ["parentSpanId", "sampled", "spanId", "traceId"];
29
+ const SESSION_KEYS = ["id", "previousId"];
30
+ const SUBJECT_KEYS = ["id", "kind"];
31
+ const IMPACT_KEYS = ["failedAction", "userVisibleOutcome"];
32
+ /** @type {readonly ["spanId", "parentSpanId"]} */
33
+ const OPTIONAL_SPAN_IDS = ["spanId", "parentSpanId"];
34
+ const ZERO_ID_PATTERN = /^0+$/u;
35
+ const OPAQUE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,199}$/u;
36
+ const LOCATION_TEXT_PATTERN = /[?#]/u;
37
+
38
+ /**
39
+ * @param {unknown} value
40
+ * @param {readonly string[]} allowedKeys
41
+ * @param {string} name
42
+ * @returns {Readonly<Record<string, unknown>>}
43
+ */
44
+ function exactObject(value, allowedKeys, name) {
45
+ if (!isRecord(value)) {
46
+ throw configurationError(`${name} must be an object`);
47
+ }
48
+ const unknownKeys = Object.keys(value).filter(key => !allowedKeys.includes(key));
49
+ if (unknownKeys.length > NO_UNKNOWN_FIELDS) {
50
+ throw configurationError(`${name} contains unsupported fields`);
51
+ }
52
+ return value;
53
+ }
54
+
55
+ /**
56
+ * @param {unknown} value
57
+ * @param {number} width
58
+ * @param {string} name
59
+ * @returns {string}
60
+ */
61
+ function correlationHexId(value, width, name) {
62
+ if (typeof value !== "string"
63
+ || !new RegExp(`^[0-9a-f]{${width}}$`, "iu").test(value)
64
+ || ZERO_ID_PATTERN.test(value)) {
65
+ throw configurationError(`context trace ${name} must be a non-zero ${width}-character hex value`);
66
+ }
67
+ return value.toLowerCase();
68
+ }
69
+
70
+ /**
71
+ * @param {unknown} value
72
+ * @param {string} name
73
+ * @returns {string}
74
+ */
75
+ function opaqueCorrelationId(value, name) {
76
+ if (typeof value !== "string" || !OPAQUE_ID_PATTERN.test(value)) {
77
+ throw configurationError(`context ${name} must be an opaque app-owned identifier`);
78
+ }
79
+ return value;
80
+ }
81
+
82
+ /**
83
+ * @param {unknown} value
84
+ * @param {DiagnosticTextRule} rule
85
+ * @returns {string}
86
+ */
87
+ function diagnosticText(value, rule) {
88
+ const normalized = typeof value === "string" ? value.trim() : "";
89
+ if (normalized.length === EMPTY_LENGTH
90
+ || [...normalized].length > rule.maximum
91
+ || hasControlCharacter(normalized)
92
+ || (rule.rejectLocationText && LOCATION_TEXT_PATTERN.test(normalized))) {
93
+ throw configurationError(`context impact ${rule.name} is invalid`);
94
+ }
95
+ return normalized;
96
+ }
97
+
98
+ /**
99
+ * @param {Readonly<Record<string, unknown>>} trace
100
+ * @returns {{ spanId?: string, parentSpanId?: string }}
101
+ */
102
+ function optionalSpanIds(trace) {
103
+ /** @type {{ spanId?: string, parentSpanId?: string }} */
104
+ const output = {};
105
+ for (const key of OPTIONAL_SPAN_IDS) {
106
+ if (trace[key] !== undefined) {
107
+ output[key] = correlationHexId(trace[key], SPAN_ID_WIDTH, key);
108
+ }
109
+ }
110
+ return output;
111
+ }
112
+
113
+ /**
114
+ * @param {unknown} sampled
115
+ * @returns {{ sampled?: boolean }}
116
+ */
117
+ function optionalSampled(sampled) {
118
+ if (sampled === undefined) {
119
+ return {};
120
+ }
121
+ if (typeof sampled !== "boolean") {
122
+ throw configurationError("context trace sampled must be a boolean");
123
+ }
124
+ return { sampled };
125
+ }
126
+
127
+ /**
128
+ * @param {unknown} value
129
+ * @returns {AppleTrace}
130
+ */
131
+ function normalizeTrace(value) {
132
+ const trace = exactObject(value, TRACE_KEYS, "context trace");
133
+ const traceId = correlationHexId(trace["traceId"], TRACE_ID_WIDTH, "traceId");
134
+ return { traceId, ...optionalSpanIds(trace), ...optionalSampled(trace["sampled"]) };
135
+ }
136
+
137
+ /**
138
+ * @param {unknown} value
139
+ * @returns {AppleSession}
140
+ */
141
+ function normalizeSession(value) {
142
+ const session = exactObject(value, SESSION_KEYS, "context session");
143
+ /** @type {AppleSession} */
144
+ const output = { id: opaqueCorrelationId(session["id"], "session id") };
145
+ if (session["previousId"] !== undefined) {
146
+ output.previousId = opaqueCorrelationId(session["previousId"], "session previousId");
147
+ if (output.previousId === output.id) {
148
+ throw configurationError("context session previousId must differ from id");
149
+ }
150
+ }
151
+ return output;
152
+ }
153
+
154
+ /**
155
+ * @param {unknown} value
156
+ * @returns {AppleSubject}
157
+ */
158
+ function normalizeSubject(value) {
159
+ const subject = exactObject(value, SUBJECT_KEYS, "context subject");
160
+ const { kind } = subject;
161
+ if (kind !== "anonymous" && kind !== "user") {
162
+ throw configurationError("context subject kind must be anonymous or user");
163
+ }
164
+ return { id: opaqueCorrelationId(subject["id"], "subject id"), kind };
165
+ }
166
+
167
+ /**
168
+ * @param {unknown} value
169
+ * @returns {AppleImpact}
170
+ */
171
+ function normalizeImpact(value) {
172
+ const impact = exactObject(value, IMPACT_KEYS, "context impact");
173
+ /** @type {AppleImpact} */
174
+ const output = {
175
+ failedAction: diagnosticText(impact["failedAction"], { maximum: FAILED_ACTION_LIMIT, name: "failedAction", rejectLocationText: true })
176
+ };
177
+ if (impact["userVisibleOutcome"] !== undefined) {
178
+ output.userVisibleOutcome = diagnosticText(
179
+ impact["userVisibleOutcome"],
180
+ { maximum: USER_VISIBLE_OUTCOME_LIMIT, name: "userVisibleOutcome", rejectLocationText: false }
181
+ );
182
+ }
183
+ return output;
184
+ }
185
+
186
+ /**
187
+ * @template T
188
+ * @param {unknown} value
189
+ * @param {(input: unknown) => T} normalize
190
+ * @returns {T | undefined}
191
+ */
192
+ function section(value, normalize) {
193
+ return value === undefined ? undefined : normalize(value);
194
+ }
195
+
196
+ /**
197
+ * @param {unknown} context
198
+ * @returns {Readonly<Record<string, unknown>>}
199
+ */
200
+ function correlationSource(context) {
201
+ const source = exactObject(context, CONTEXT_KEYS, "context");
202
+ if (source["schemaVersion"] !== SCHEMA_VERSION) {
203
+ throw configurationError("context schemaVersion must be 1");
204
+ }
205
+ return source;
206
+ }
207
+
208
+ /**
209
+ * @param {unknown} context
210
+ * @returns {AppleCorrelationContext}
211
+ */
212
+ function normalizeCorrelationContext(context) {
213
+ const source = correlationSource(context);
214
+ const trace = section(source["trace"], normalizeTrace);
215
+ const session = section(source["session"], normalizeSession);
216
+ const subject = section(source["subject"], normalizeSubject);
217
+ const impact = section(source["impact"], normalizeImpact);
218
+ /** @type {AppleCorrelationContext} */
219
+ const output = {
220
+ schemaVersion: SCHEMA_VERSION,
221
+ ...(trace === undefined ? {} : { trace }),
222
+ ...(session === undefined ? {} : { session }),
223
+ ...(subject === undefined ? {} : { subject }),
224
+ ...(impact === undefined ? {} : { impact })
225
+ };
226
+ if (Object.keys(output).length === ONLY_SCHEMA_VERSION) {
227
+ throw configurationError("context must include trace, session, subject, or impact");
228
+ }
229
+ return output;
230
+ }
231
+
232
+ export { normalizeCorrelationContext };
@@ -0,0 +1,229 @@
1
+ import { isCount, isRecord, nativeMethod } from "./native-diagnostics-values.js";
2
+ import { lookupNativeModule, platformOS } from "./native-module-lookup.js";
3
+ import { SdkError } from "@logbrew/sdk";
4
+
5
+ /**
6
+ * @import {
7
+ * LogBrewAppleNativeCrashContextResult,
8
+ * LogBrewAppleNativeDiagnosticsReplayResult,
9
+ * LogBrewAppleNativeDiagnosticsStatus
10
+ * } from "./apple-native-diagnostics.js"
11
+ * @typedef {LogBrewAppleNativeDiagnosticsStatus["status"]} AppleStatus
12
+ * @typedef {LogBrewAppleNativeDiagnosticsStatus["lifecycle"]} AppleLifecycle
13
+ * @typedef {Readonly<{ method: string, label: string }>} SnapshotTarget
14
+ */
15
+
16
+ /** @type {ReadonlySet<string>} */
17
+ const LIFECYCLE_STATUSES = new Set([
18
+ "failed",
19
+ "idle",
20
+ "installed",
21
+ "replaying",
22
+ "stopped",
23
+ "unknown"
24
+ ]);
25
+ const ERROR_CODE_PATTERN = /^[a-z0-9_]{1,128}$/u;
26
+ const SNAPSHOT_RESULT_KEYS = 1;
27
+
28
+ function requireApplePlatform() {
29
+ if (platformOS() !== "ios") {
30
+ throw new SdkError(
31
+ "unsupported_platform",
32
+ "LogBrew Apple native diagnostics are available only in an iOS native build"
33
+ );
34
+ }
35
+ }
36
+
37
+ /**
38
+ * @returns {unknown}
39
+ */
40
+ function appleDiagnosticsModule() {
41
+ try {
42
+ return lookupNativeModule("LogBrewAppleDiagnostics");
43
+ } catch {
44
+ return undefined;
45
+ }
46
+ }
47
+
48
+ /**
49
+ * @param {unknown} value
50
+ * @returns {boolean}
51
+ */
52
+ function isFalsy(value) {
53
+ const present = Boolean(value);
54
+ return !present;
55
+ }
56
+
57
+ /**
58
+ * @returns {unknown}
59
+ */
60
+ function requireNativeModule() {
61
+ const nativeModule = appleDiagnosticsModule();
62
+ if (isFalsy(nativeModule)) {
63
+ throw new SdkError(
64
+ "native_diagnostics_unavailable",
65
+ "LogBrew Apple native diagnostics require the AppleDiagnostics CocoaPods subspec; Expo projects can add @logbrew/react-native/expo"
66
+ );
67
+ }
68
+ return nativeModule;
69
+ }
70
+
71
+ /**
72
+ * @param {unknown} nativeModule
73
+ * @param {string} method
74
+ * @param {readonly unknown[]} args
75
+ * @returns {unknown}
76
+ */
77
+ function callNative(nativeModule, method, ...args) {
78
+ const native = nativeMethod(nativeModule, method, args);
79
+ if (!native.found) {
80
+ throw new SdkError(
81
+ "native_diagnostics_unavailable",
82
+ `linked LogBrew Apple diagnostics do not implement ${method}`
83
+ );
84
+ }
85
+ try {
86
+ return native.call();
87
+ } catch {
88
+ throw new SdkError(
89
+ "native_diagnostics_failed",
90
+ `LogBrew Apple native diagnostics ${method} failed`
91
+ );
92
+ }
93
+ }
94
+
95
+ /**
96
+ * @param {unknown} result
97
+ * @returns {string | undefined}
98
+ */
99
+ function errorResultCode(result) {
100
+ const code = isRecord(result) && result["status"] === "error" ? result["code"] : undefined;
101
+ return typeof code === "string" && ERROR_CODE_PATTERN.test(code) ? code : undefined;
102
+ }
103
+
104
+ /**
105
+ * @param {unknown} nativeModule
106
+ * @param {unknown} payload
107
+ * @param {SnapshotTarget} target
108
+ * @returns {LogBrewAppleNativeCrashContextResult}
109
+ */
110
+ function updateNativeSnapshot(nativeModule, payload, target) {
111
+ const result = callNative(nativeModule, target.method, payload);
112
+ const expectedStatus = payload === null ? "cleared" : "updated";
113
+ const code = errorResultCode(result);
114
+ if (code !== undefined) {
115
+ throw new SdkError(code, `LogBrew Apple native diagnostics ${target.label} failed with ${code}`);
116
+ }
117
+ if (!isRecord(result)
118
+ || Object.keys(result).length !== SNAPSHOT_RESULT_KEYS
119
+ || result["status"] !== expectedStatus) {
120
+ throw new SdkError(
121
+ "native_diagnostics_invalid_response",
122
+ `LogBrew Apple native diagnostics ${target.label} returned an invalid response`
123
+ );
124
+ }
125
+ return Object.freeze({ status: expectedStatus });
126
+ }
127
+
128
+ /**
129
+ * @param {unknown} snapshot
130
+ * @returns {LogBrewAppleNativeCrashContextResult}
131
+ */
132
+ function syncLogBrewAppleNativeCrashBreadcrumbs(snapshot) {
133
+ requireApplePlatform();
134
+ return updateNativeSnapshot(
135
+ requireNativeModule(),
136
+ snapshot,
137
+ { label: "breadcrumbs", method: "setNativeDiagnosticsBreadcrumbs" }
138
+ );
139
+ }
140
+
141
+ /**
142
+ * @param {unknown} value
143
+ * @param {Readonly<ReadonlySet<string>>} allowed
144
+ * @returns {value is AppleStatus}
145
+ */
146
+ function isAllowedStatus(value, allowed) {
147
+ return typeof value === "string" && allowed.has(value);
148
+ }
149
+
150
+ /**
151
+ * @param {unknown} value
152
+ * @returns {value is AppleLifecycle}
153
+ */
154
+ function isLifecycle(value) {
155
+ return typeof value === "string" && LIFECYCLE_STATUSES.has(value);
156
+ }
157
+
158
+ /**
159
+ * @param {string} operation
160
+ * @param {unknown} result
161
+ * @param {Readonly<ReadonlySet<string>>} allowedStatuses
162
+ * @returns {LogBrewAppleNativeDiagnosticsStatus}
163
+ */
164
+ function requireStatusResult(operation, result, allowedStatuses) {
165
+ const code = errorResultCode(result);
166
+ if (code !== undefined) {
167
+ throw new SdkError(code, `LogBrew Apple native diagnostics ${operation} failed with ${code}`);
168
+ }
169
+ const status = isRecord(result) ? result["status"] : undefined;
170
+ const lifecycle = isRecord(result) ? result["lifecycle"] : undefined;
171
+ if (!isRecord(result)
172
+ || !isAllowedStatus(status, allowedStatuses)
173
+ || !isLifecycle(lifecycle)
174
+ || !isCount(result["pending"])
175
+ || !isCount(result["acknowledged"])
176
+ || !isCount(result["discarded"])) {
177
+ throw new SdkError(
178
+ "native_diagnostics_invalid_response",
179
+ `LogBrew Apple native diagnostics ${operation} returned an invalid response`
180
+ );
181
+ }
182
+ return Object.freeze({
183
+ acknowledged: result["acknowledged"],
184
+ discarded: result["discarded"],
185
+ lifecycle,
186
+ pending: result["pending"],
187
+ status
188
+ });
189
+ }
190
+
191
+ /**
192
+ * @param {unknown} result
193
+ * @returns {LogBrewAppleNativeDiagnosticsReplayResult}
194
+ */
195
+ function requireReplayResult(result) {
196
+ const code = errorResultCode(result);
197
+ if (code !== undefined) {
198
+ throw new SdkError(code, `LogBrew Apple native diagnostics replay failed with ${code}`);
199
+ }
200
+ if (!isRecord(result)
201
+ || result["status"] !== "replayed"
202
+ || !isCount(result["attempted"])
203
+ || !isCount(result["acknowledged"])
204
+ || !isCount(result["discarded"])
205
+ || !isCount(result["pending"])
206
+ || result["acknowledged"] + result["discarded"] > result["attempted"]) {
207
+ throw new SdkError(
208
+ "native_diagnostics_invalid_response",
209
+ "LogBrew Apple native diagnostics replay returned an invalid response"
210
+ );
211
+ }
212
+ return Object.freeze({
213
+ acknowledged: result["acknowledged"],
214
+ attempted: result["attempted"],
215
+ discarded: result["discarded"],
216
+ pending: result["pending"],
217
+ status: result["status"]
218
+ });
219
+ }
220
+
221
+ export {
222
+ callNative,
223
+ requireApplePlatform,
224
+ requireNativeModule,
225
+ requireReplayResult,
226
+ requireStatusResult,
227
+ syncLogBrewAppleNativeCrashBreadcrumbs,
228
+ updateNativeSnapshot
229
+ };