@logbrew/react-native 0.1.39 → 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 (96) hide show
  1. package/android-native-diagnostics.d.ts +15 -5
  2. package/android-native-diagnostics.js +170 -94
  3. package/apollo.cjs +435 -226
  4. package/apollo.d.cts +2 -70
  5. package/apollo.d.ts +24 -12
  6. package/apollo.js +438 -221
  7. package/apple-native-diagnostics-config.js +176 -0
  8. package/apple-native-diagnostics-context.js +232 -0
  9. package/apple-native-diagnostics-module.js +229 -0
  10. package/apple-native-diagnostics.d.ts +42 -11
  11. package/apple-native-diagnostics.js +60 -389
  12. package/expo.cjs +29 -16
  13. package/expo.d.ts +10 -9
  14. package/expo.js +4 -3
  15. package/fatal-admission.cjs +113 -0
  16. package/fatal-record.cjs +317 -0
  17. package/fatal-replay.cjs +297 -508
  18. package/global-errors-capture.cjs +369 -0
  19. package/global-errors-event.cjs +174 -0
  20. package/global-errors-support.cjs +128 -0
  21. package/global-errors.cjs +75 -351
  22. package/global-errors.d.cts +29 -278
  23. package/global-errors.d.ts +57 -27
  24. package/global-errors.js +7 -2
  25. package/global-errors.native.js +83 -48
  26. package/index-breadcrumbs.cjs +139 -0
  27. package/index-errors.cjs +167 -0
  28. package/index-events.cjs +365 -0
  29. package/index-navigation.cjs +327 -0
  30. package/index-random.cjs +120 -0
  31. package/index-react.cjs +189 -0
  32. package/index-spans.cjs +190 -0
  33. package/index-trace-fetch.cjs +322 -0
  34. package/index-trace.cjs +335 -0
  35. package/index-transport.cjs +201 -0
  36. package/index-values.cjs +232 -0
  37. package/index.cjs +95 -1243
  38. package/index.d.cts +2 -505
  39. package/index.d.ts +130 -469
  40. package/index.native.d.ts +146 -22
  41. package/index.native.js +184 -159
  42. package/instrumentation-fetch.cjs +113 -0
  43. package/instrumentation-install.cjs +241 -0
  44. package/instrumentation-runtime.cjs +65 -0
  45. package/instrumentation-teardown.cjs +93 -0
  46. package/instrumentation-values.cjs +282 -0
  47. package/instrumentation-xhr-request.cjs +298 -0
  48. package/instrumentation-xhr.cjs +233 -0
  49. package/instrumentation.cjs +110 -599
  50. package/instrumentation.d.cts +2 -84
  51. package/instrumentation.d.ts +22 -8
  52. package/ios/AppleDiagnostics/LBRNAppleNativeDiagnostics.swift +1 -1
  53. package/lifecycle.cjs +181 -78
  54. package/lifecycle.d.cts +1 -50
  55. package/lifecycle.d.ts +17 -6
  56. package/metadata.cjs +279 -114
  57. package/metro-debug-id.cjs +296 -0
  58. package/metro-serializer.cjs +219 -0
  59. package/metro.cjs +153 -297
  60. package/metro.d.cts +2 -57
  61. package/metro.d.ts +27 -13
  62. package/metro.js +2 -3
  63. package/native-bridge-async.cjs +165 -0
  64. package/native-bridge-scope.cjs +148 -0
  65. package/native-bridge.cjs +83 -186
  66. package/native-bridge.d.cts +2 -94
  67. package/native-bridge.d.ts +28 -15
  68. package/native-client-bindings.js +230 -0
  69. package/native-diagnostics-values.js +120 -0
  70. package/native-module-lookup.js +31 -0
  71. package/native-null.js +3 -0
  72. package/null-value.cjs +4 -0
  73. package/package.json +43 -1
  74. package/persistent-delivery-store.js +247 -0
  75. package/persistent-delivery.native.js +183 -261
  76. package/promise-rejection-handlers.cjs +368 -0
  77. package/promise-rejections.cjs +169 -361
  78. package/react-native.config.js +3 -1
  79. package/release-artifacts-files.cjs +94 -0
  80. package/release-artifacts-options.cjs +182 -0
  81. package/release-artifacts.cjs +278 -207
  82. package/release-artifacts.d.cts +2 -55
  83. package/release-artifacts.d.ts +18 -7
  84. package/release-artifacts.js +2 -4
  85. package/resource-fetch-graphql.cjs +265 -0
  86. package/resource-fetch-size.cjs +156 -0
  87. package/resource-fetch.cjs +227 -428
  88. package/resource-fetch.d.cts +1 -60
  89. package/resource-fetch.d.ts +17 -6
  90. package/scripts/sync-apple-native-sources.mjs +101 -53
  91. package/types/capture.d.ts +95 -0
  92. package/types/config.d.ts +85 -0
  93. package/types/defaults.d.ts +55 -0
  94. package/types/events.d.ts +203 -0
  95. package/types/provider.d.ts +81 -0
  96. package/types/trace.d.ts +104 -0
package/metro.cjs CHANGED
@@ -1,225 +1,148 @@
1
1
  "use strict";
2
2
 
3
- const crypto = require("node:crypto");
4
- const { Buffer } = require("node:buffer");
5
3
  const { createRequire } = require("node:module");
6
4
  const path = require("node:path");
5
+ const {
6
+ configurationError,
7
+ field,
8
+ isCallable,
9
+ isDevelopmentGraph,
10
+ isRecord,
11
+ prependDebugIdModule,
12
+ productionResult
13
+ } = require("./metro-debug-id.cjs");
14
+ const { createDefaultMetroSerializer } = require("./metro-serializer.cjs");
15
+
16
+ /**
17
+ * @typedef {(this: unknown, ...args: readonly unknown[]) => unknown} Callable
18
+ * @typedef {(entryPoint: unknown, preModules: unknown, graph: unknown, options: unknown) => Promise<unknown>} MetroSerializer
19
+ * @typedef {Readonly<Record<string, unknown>> & { readonly enabled?: boolean }} LogBrewMetroOptions
20
+ * @typedef {LogBrewMetroOptions & {
21
+ * readonly getDefaultConfig?: Callable,
22
+ * readonly unstable_beforeAssetSerializationPlugins?: readonly Callable[]
23
+ * }} LogBrewExpoOptions
24
+ */
7
25
 
8
- const DEBUG_ID_PLACEHOLDER = "__LOGBREW_REACT_NATIVE_DEBUG_ID__";
9
- const DEBUG_ID_MODULE_PATH = "__logbrew_debug_id__";
10
- const DEBUG_ID_REGISTRY_NAME = "@logbrew/react-native/debug-ids";
11
- const RUNTIME_DEBUG_ID_MARKER = "/*logbrew-runtime-debug-id*/";
12
- const DEBUG_ID_KEYS = ["debug_id", "debugId", "debugID", "x_debug_id"];
13
- const DEBUG_ID_COMMENT_RE = /(?:\/\/[#@]|\/\*[#@])\s*debugId=[^\r\n]*/iu;
14
26
  const DEBUG_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
15
- const SOURCE_MAPPING_COMMENT_RE = /(?:\/\/[#@]|\/\*[#@])\s*sourceMappingURL=[^\r\n]*/giu;
16
27
  const WRAPPED_SERIALIZER = Symbol.for("@logbrew/react-native/metro-serializer");
17
28
 
18
- function configurationError(message, options) {
19
- const error = new Error(message, options);
20
- error.code = "configuration_error";
21
- return error;
22
- }
23
-
29
+ /**
30
+ * @param {unknown} options
31
+ * @returns {asserts options is LogBrewMetroOptions}
32
+ */
24
33
  function requireOptions(options) {
25
- if (!options || Array.isArray(options) || typeof options !== "object") {
34
+ if (!isRecord(options) || Array.isArray(options)) {
26
35
  throw configurationError("LogBrew Metro options must be an object");
27
36
  }
28
- if (options.enabled !== undefined && typeof options.enabled !== "boolean") {
37
+ if (options["enabled"] !== undefined && typeof options["enabled"] !== "boolean") {
29
38
  throw configurationError("LogBrew Metro option enabled must be a boolean");
30
39
  }
31
- return options;
32
- }
33
-
34
- function runtimeDebugIdSnippet(debugId) {
35
- const embedded = `${RUNTIME_DEBUG_ID_MARKER}//# debugId=${debugId}`;
36
- return `;(()=>{try{const d=${JSON.stringify(embedded)}.slice(-36),k=Symbol.for(${JSON.stringify(DEBUG_ID_REGISTRY_NAME)}),g=globalThis,r=g[k]||(g[k]=Object.create(null)),s=(new Error).stack;if(s){r[s]=d;const e=Object.keys(r);if(e.length>64)delete r[e[0]]}}catch{}})();`;
37
- }
38
-
39
- function countLines(source) {
40
- return source === "" ? 0 : source.split("\n").length;
41
40
  }
42
41
 
43
- function createDebugIdModule(debugId = DEBUG_ID_PLACEHOLDER) {
44
- const code = runtimeDebugIdSnippet(debugId);
45
- return {
46
- dependencies: new Map(),
47
- getSource: () => Buffer.from(code),
48
- inverseDependencies: new Set(),
49
- path: DEBUG_ID_MODULE_PATH,
50
- output: [
51
- {
52
- type: "js/script/virtual",
53
- data: {
54
- code,
55
- lineCount: countLines(code),
56
- map: [],
57
- },
58
- },
59
- ],
60
- };
42
+ /**
43
+ * @param {unknown} value
44
+ * @returns {value is readonly unknown[]}
45
+ */
46
+ function isArray(value) {
47
+ return Array.isArray(value);
61
48
  }
62
49
 
63
- function prependDebugIdModule(preModules, debugId = DEBUG_ID_PLACEHOLDER) {
64
- if (!Array.isArray(preModules)) {
65
- throw configurationError("LogBrew Metro serializer expected preModules to be an array");
66
- }
67
- if (preModules.some((module) => module?.path === DEBUG_ID_MODULE_PATH)) {
68
- return preModules;
69
- }
70
- const debugIdModule = createDebugIdModule(debugId);
71
- if (preModules[0]?.path === "__prelude__") {
72
- return [preModules[0], debugIdModule, ...preModules.slice(1)];
73
- }
74
- return [debugIdModule, ...preModules];
75
- }
76
-
77
- function isDevelopmentGraph(graph) {
78
- const transformOptions = graph?.transformOptions;
79
- return transformOptions?.hot === true || transformOptions?.dev === true;
80
- }
81
-
82
- function parseSourceMap(value) {
83
- if (typeof value !== "string" || value.trim() === "") {
84
- throw configurationError("LogBrew Metro production serializer must return a non-empty source map string");
85
- }
86
- let sourceMap;
87
- try {
88
- sourceMap = JSON.parse(value);
89
- } catch (error) {
90
- throw configurationError(`LogBrew Metro production serializer returned invalid source map JSON: ${error.message}`);
91
- }
92
- if (!sourceMap || Array.isArray(sourceMap) || typeof sourceMap !== "object") {
93
- throw configurationError("LogBrew Metro production serializer source map must be an object");
94
- }
95
- return sourceMap;
96
- }
97
-
98
- function canonicalSourceMap(sourceMap) {
99
- const copy = { ...sourceMap };
100
- for (const key of DEBUG_ID_KEYS) {
101
- delete copy[key];
102
- }
103
- return JSON.stringify(copy);
104
- }
105
-
106
- function formatDebugId(bytes) {
107
- const value = Buffer.from(bytes.subarray(0, 16));
108
- value[6] = (value[6] & 0x0f) | 0x50;
109
- value[8] = (value[8] & 0x3f) | 0x80;
110
- const hex = value.toString("hex");
111
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
112
- }
113
-
114
- function createDebugId(code, sourceMap) {
115
- const digest = crypto
116
- .createHash("sha256")
117
- .update(code.split(DEBUG_ID_PLACEHOLDER).join(""))
118
- .update("\0")
119
- .update(canonicalSourceMap(sourceMap))
120
- .digest();
121
- return formatDebugId(digest);
122
- }
123
-
124
- function sourceWithDebugId(source, debugId) {
125
- const replaced = source.split(DEBUG_ID_PLACEHOLDER).join(debugId);
126
- const debugLine = `//# debugId=${debugId}\n`;
127
- const matches = [...replaced.matchAll(SOURCE_MAPPING_COMMENT_RE)];
128
- if (matches.length === 0) {
129
- return `${replaced}${replaced.endsWith("\n") ? "" : "\n"}${debugLine}`;
130
- }
131
- const last = matches.at(-1);
132
- const prefix = replaced.slice(0, last.index);
133
- const separator = prefix.endsWith("\n") || prefix.endsWith("\r") ? "" : "\n";
134
- return `${prefix}${separator}${debugLine}${replaced.slice(last.index)}`;
135
- }
136
-
137
- function productionResult(result) {
138
- if (Array.isArray(result)) {
139
- throw configurationError(
140
- "LogBrew Metro received Expo static assets; use getLogBrewExpoConfig instead of withLogBrewMetroConfig for Expo projects",
141
- );
142
- }
143
- if (!result || typeof result !== "object") {
144
- throw configurationError("LogBrew Metro production serializer must return { code, map }");
145
- }
146
- if (typeof result.code !== "string") {
147
- throw configurationError("LogBrew Metro production serializer code must be a string");
148
- }
149
- if (result.code.split(DEBUG_ID_PLACEHOLDER).length !== 2) {
150
- throw configurationError("LogBrew Metro production serializer must include the injected Debug ID module exactly once");
151
- }
152
- if (DEBUG_ID_COMMENT_RE.test(result.code.replace(`${RUNTIME_DEBUG_ID_MARKER}//# debugId=${DEBUG_ID_PLACEHOLDER}`, ""))) {
153
- throw configurationError("LogBrew Metro production serializer already contains Debug ID metadata");
154
- }
155
- const sourceMap = parseSourceMap(result.map);
156
- if (DEBUG_ID_KEYS.some((key) => Object.prototype.hasOwnProperty.call(sourceMap, key))) {
157
- throw configurationError("LogBrew Metro production serializer already contains Debug ID metadata");
158
- }
159
- const debugId = createDebugId(result.code, sourceMap);
160
- sourceMap.debug_id = debugId;
161
- sourceMap.debugId = debugId;
162
- return {
163
- ...result,
164
- code: sourceWithDebugId(result.code, debugId),
165
- map: JSON.stringify(sourceMap),
166
- };
50
+ /**
51
+ * @param {unknown} value
52
+ * @returns {boolean}
53
+ */
54
+ function isFunctionArray(value) {
55
+ return Array.isArray(value) && value.every((plugin) => typeof plugin === "function");
167
56
  }
168
57
 
58
+ /**
59
+ * @param {unknown} options
60
+ * @returns {asserts options is LogBrewExpoOptions}
61
+ */
169
62
  function requireExpoPluginOptions(options) {
170
63
  requireOptions(options);
171
64
  if (
172
- options.unstable_beforeAssetSerializationPlugins !== undefined &&
173
- (!Array.isArray(options.unstable_beforeAssetSerializationPlugins) ||
174
- options.unstable_beforeAssetSerializationPlugins.some((plugin) => typeof plugin !== "function"))
65
+ options["unstable_beforeAssetSerializationPlugins"] !== undefined &&
66
+ !isFunctionArray(options["unstable_beforeAssetSerializationPlugins"])
175
67
  ) {
176
68
  throw configurationError(
177
- "LogBrew Expo option unstable_beforeAssetSerializationPlugins must be an array of functions",
69
+ "LogBrew Expo option unstable_beforeAssetSerializationPlugins must be an array of functions"
178
70
  );
179
71
  }
180
- if (options.getDefaultConfig !== undefined && typeof options.getDefaultConfig !== "function") {
72
+ if (options["getDefaultConfig"] !== undefined && typeof options["getDefaultConfig"] !== "function") {
181
73
  throw configurationError("LogBrew Expo option getDefaultConfig must be a function");
182
74
  }
183
- return options;
184
75
  }
185
76
 
77
+ /**
78
+ * @param {unknown} input
79
+ * @returns {readonly unknown[]}
80
+ */
81
+ function expoPreModules(input) {
82
+ if (!isRecord(input) || Array.isArray(input)) {
83
+ throw configurationError("LogBrew Expo Debug ID plugin requires a serialization input object");
84
+ }
85
+ const preModules = input["premodules"];
86
+ if (!isArray(preModules)) {
87
+ throw configurationError("LogBrew Expo Debug ID plugin expected premodules to be an array");
88
+ }
89
+ return preModules;
90
+ }
91
+
92
+ /**
93
+ * @param {unknown} [options]
94
+ * @returns {(input: unknown) => unknown}
95
+ */
186
96
  function createLogBrewExpoDebugIdPlugin(options = {}) {
187
97
  requireOptions(options);
188
98
  return (input) => {
189
- if (!input || Array.isArray(input) || typeof input !== "object") {
190
- throw configurationError("LogBrew Expo Debug ID plugin requires a serialization input object");
191
- }
192
- const preModules = input.premodules;
193
- if (!Array.isArray(preModules)) {
194
- throw configurationError("LogBrew Expo Debug ID plugin expected premodules to be an array");
195
- }
196
- if (options.enabled === false || input.debugId === undefined || input.debugId === null) {
99
+ const preModules = expoPreModules(input);
100
+ const debugId = field(input, "debugId");
101
+ if (options.enabled === false || debugId === undefined || debugId === null) {
197
102
  return preModules;
198
103
  }
199
- if (typeof input.debugId !== "string" || !DEBUG_ID_RE.test(input.debugId)) {
104
+ if (typeof debugId !== "string" || !DEBUG_ID_RE.test(debugId)) {
200
105
  throw configurationError("LogBrew Expo Debug ID plugin requires a valid Expo Debug ID");
201
106
  }
202
- return prependDebugIdModule(preModules, input.debugId.toLowerCase());
107
+ return prependDebugIdModule(preModules, debugId.toLowerCase());
203
108
  };
204
109
  }
205
110
 
206
- function loadExpoGetDefaultConfig(projectRoot) {
207
- let expoMetroConfig;
111
+ /**
112
+ * @param {string} projectRoot
113
+ * @returns {unknown}
114
+ */
115
+ function requireExpoMetroConfig(projectRoot) {
208
116
  try {
209
117
  const projectRequire = createRequire(path.join(projectRoot, "package.json"));
210
- expoMetroConfig = projectRequire("expo/metro-config");
118
+ /** @type {unknown} */
119
+ const expoMetroConfig = projectRequire("expo/metro-config");
120
+ return expoMetroConfig;
211
121
  } catch (error) {
212
122
  throw configurationError(
213
123
  "LogBrew could not load expo/metro-config from the app; install a supported Expo SDK or pass getDefaultConfig",
214
- { cause: error },
124
+ { cause: error }
215
125
  );
216
126
  }
217
- if (typeof expoMetroConfig?.getDefaultConfig !== "function") {
127
+ }
128
+
129
+ /**
130
+ * @param {string} projectRoot
131
+ * @returns {Callable}
132
+ */
133
+ function loadExpoGetDefaultConfig(projectRoot) {
134
+ const getDefaultConfig = field(requireExpoMetroConfig(projectRoot), "getDefaultConfig");
135
+ if (!isCallable(getDefaultConfig)) {
218
136
  throw configurationError("LogBrew could not resolve getDefaultConfig from expo/metro-config");
219
137
  }
220
- return expoMetroConfig.getDefaultConfig;
138
+ return getDefaultConfig;
221
139
  }
222
140
 
141
+ /**
142
+ * @param {unknown} projectRoot
143
+ * @param {unknown} [options]
144
+ * @returns {unknown}
145
+ */
223
146
  function getLogBrewExpoConfig(projectRoot, options = {}) {
224
147
  if (typeof projectRoot !== "string" || projectRoot.trim() === "") {
225
148
  throw configurationError("getLogBrewExpoConfig requires a non-empty Expo project root");
@@ -237,128 +160,52 @@ function getLogBrewExpoConfig(projectRoot, options = {}) {
237
160
  : [...unstable_beforeAssetSerializationPlugins];
238
161
  return getDefaultConfig(root, {
239
162
  ...expoOptions,
240
- unstable_beforeAssetSerializationPlugins: plugins,
163
+ unstable_beforeAssetSerializationPlugins: plugins
241
164
  });
242
165
  }
243
166
 
244
- function requireMetroModule(privatePath, sourcePath) {
245
- try {
246
- return require(privatePath);
247
- } catch (privateError) {
248
- try {
249
- return require(sourcePath);
250
- } catch {
251
- throw configurationError(
252
- `LogBrew Metro could not load ${privatePath}; install a supported React Native Metro package`,
253
- { cause: privateError },
254
- );
255
- }
256
- }
257
- }
258
-
259
- function moduleFunction(moduleValue, names, label) {
260
- if (typeof moduleValue === "function") {
261
- return moduleValue;
262
- }
263
- for (const name of names) {
264
- if (typeof moduleValue?.[name] === "function") {
265
- return moduleValue[name];
266
- }
267
- }
268
- throw configurationError(`LogBrew Metro could not resolve ${label} from the installed Metro package`);
269
- }
270
-
271
- function sortedModules(graph, options) {
272
- const modules = [...(graph?.dependencies?.values?.() ?? [])];
273
- if (typeof options?.createModuleId !== "function") {
274
- return modules;
167
+ /**
168
+ * @param {unknown} result
169
+ * @param {MetroSerializer} fallbackSerializer
170
+ * @param {readonly [unknown, unknown, unknown, unknown]} args
171
+ * @returns {Promise<Record<string, unknown>>}
172
+ */
173
+ async function stringSerializerResult(result, fallbackSerializer, args) {
174
+ const fallbackResult = await fallbackSerializer(...args);
175
+ if (typeof fallbackResult === "string" || field(fallbackResult, "code") !== result) {
176
+ throw configurationError(
177
+ "LogBrew Metro string-returning custom serializer changed bundle code; return { code, map } to preserve source-map accuracy"
178
+ );
275
179
  }
276
- return modules.sort((left, right) => options.createModuleId(left.path) - options.createModuleId(right.path));
277
- }
278
-
279
- function createMetroSourceMapSerializer() {
280
- const getSourceMapInfo = moduleFunction(
281
- requireMetroModule(
282
- "metro/private/DeltaBundler/Serializers/helpers/getSourceMapInfo",
283
- "metro/src/DeltaBundler/Serializers/helpers/getSourceMapInfo",
284
- ),
285
- ["default"],
286
- "getSourceMapInfo",
287
- );
288
- const isJsModule = moduleFunction(
289
- requireMetroModule(
290
- "metro/private/DeltaBundler/Serializers/helpers/js",
291
- "metro/src/DeltaBundler/Serializers/helpers/js",
292
- ),
293
- ["isJsModule"],
294
- "isJsModule",
295
- );
296
- const metroRequire = createRequire(require.resolve("metro/package.json"));
297
- const fromRawMappings = moduleFunction(
298
- metroRequire("metro-source-map"),
299
- ["fromRawMappings"],
300
- "fromRawMappings",
301
- );
302
-
303
- return (preModules, graph, options) => {
304
- const sourceMapOptions = {
305
- excludeSource: options?.excludeSource === true,
306
- getSourceUrl: typeof options?.getSourceUrl === "function" ? options.getSourceUrl : null,
307
- processModuleFilter: typeof options?.processModuleFilter === "function" ? options.processModuleFilter : () => true,
308
- shouldAddToIgnoreList:
309
- typeof options?.shouldAddToIgnoreList === "function" ? options.shouldAddToIgnoreList : () => false,
310
- };
311
- const modules = [...preModules, ...sortedModules(graph, options)]
312
- .filter(isJsModule)
313
- .filter(sourceMapOptions.processModuleFilter)
314
- .map((module) => getSourceMapInfo(module, sourceMapOptions));
315
- return fromRawMappings(modules).toString(undefined, sourceMapOptions);
316
- };
317
- }
318
-
319
- function createDefaultMetroSerializer() {
320
- const baseJSBundle = moduleFunction(
321
- requireMetroModule(
322
- "metro/private/DeltaBundler/Serializers/baseJSBundle",
323
- "metro/src/DeltaBundler/Serializers/baseJSBundle",
324
- ),
325
- ["baseJSBundle", "default"],
326
- "baseJSBundle",
327
- );
328
- const bundleToString = moduleFunction(
329
- requireMetroModule("metro/private/lib/bundleToString", "metro/src/lib/bundleToString"),
330
- ["bundleToString", "default"],
331
- "bundleToString",
332
- );
333
- const serializeSourceMap = createMetroSourceMapSerializer();
334
-
335
- return async (entryPoint, preModules, graph, options) => {
336
- const code = bundleToString(baseJSBundle(entryPoint, preModules, graph, options)).code;
337
- if (isDevelopmentGraph(graph)) {
338
- return code;
339
- }
340
- const map = await serializeSourceMap(preModules, graph, options);
341
- return { code, map };
342
- };
180
+ return productionResult(fallbackResult);
343
181
  }
344
182
 
183
+ /**
184
+ * @param {unknown} customSerializer
185
+ * @returns {Callable}
186
+ */
345
187
  function createLogBrewMetroSerializer(customSerializer) {
346
- if (customSerializer !== undefined && customSerializer !== null && typeof customSerializer !== "function") {
188
+ if (customSerializer !== undefined && customSerializer !== null && !isCallable(customSerializer)) {
347
189
  throw configurationError("LogBrew Metro custom serializer must be a function");
348
190
  }
349
- if (customSerializer?.[WRAPPED_SERIALIZER] === true) {
191
+ if (isCallable(customSerializer) && field(customSerializer, WRAPPED_SERIALIZER) === true) {
350
192
  return customSerializer;
351
193
  }
352
-
194
+ /** @type {Callable | undefined} */
353
195
  let serializerSource = customSerializer ?? undefined;
354
- let fallbackSerializer;
355
- const resolveSerializer = () => {
356
- serializerSource ??= createDefaultMetroSerializer();
357
- return serializerSource;
358
- };
196
+ /** @type {MetroSerializer | undefined} */
197
+ let fallbackSerializer = undefined;
359
198
 
360
- const serializer = async (entryPoint, preModules, graph, options) => {
361
- const source = resolveSerializer();
199
+ /**
200
+ * @param {unknown} entryPoint
201
+ * @param {unknown} preModules
202
+ * @param {unknown} graph
203
+ * @param {unknown} options
204
+ * @returns {Promise<unknown>}
205
+ */
206
+ async function serializer(entryPoint, preModules, graph, options) {
207
+ serializerSource ??= createDefaultMetroSerializer();
208
+ const source = serializerSource;
362
209
  if (isDevelopmentGraph(graph)) {
363
210
  return source(entryPoint, preModules, graph, options);
364
211
  }
@@ -366,41 +213,49 @@ function createLogBrewMetroSerializer(customSerializer) {
366
213
  const result = await source(entryPoint, releaseModules, graph, options);
367
214
  if (typeof result === "string") {
368
215
  fallbackSerializer ??= createDefaultMetroSerializer();
369
- const fallbackResult = await fallbackSerializer(entryPoint, releaseModules, graph, options);
370
- if (typeof fallbackResult === "string" || fallbackResult.code !== result) {
371
- throw configurationError(
372
- "LogBrew Metro string-returning custom serializer changed bundle code; return { code, map } to preserve source-map accuracy",
373
- );
374
- }
375
- return productionResult(fallbackResult);
216
+ return stringSerializerResult(result, fallbackSerializer, [entryPoint, releaseModules, graph, options]);
376
217
  }
377
218
  return productionResult(result);
378
- };
219
+ }
379
220
  Object.defineProperty(serializer, WRAPPED_SERIALIZER, { value: true });
380
221
  return serializer;
381
222
  }
382
223
 
224
+ /**
225
+ * @param {Readonly<Record<string, unknown>>} config
226
+ * @returns {Readonly<Record<string, unknown>>}
227
+ */
228
+ function requireSerializerConfig(config) {
229
+ const serializerConfig = config["serializer"] ?? {};
230
+ if (!isRecord(serializerConfig) || Array.isArray(serializerConfig)) {
231
+ throw configurationError("withLogBrewMetroConfig requires config.serializer to be an object");
232
+ }
233
+ return serializerConfig;
234
+ }
235
+
236
+ /**
237
+ * @param {unknown} config
238
+ * @param {unknown} [options]
239
+ * @returns {unknown}
240
+ */
383
241
  function withLogBrewMetroConfig(config, options = {}) {
384
242
  requireOptions(options);
385
- if (!config || Array.isArray(config) || typeof config !== "object") {
243
+ if (!isRecord(config) || Array.isArray(config)) {
386
244
  throw configurationError("withLogBrewMetroConfig requires a Metro config object");
387
245
  }
388
246
  if (options.enabled === false) {
389
247
  return config;
390
248
  }
391
- const serializerConfig = config.serializer ?? {};
392
- if (!serializerConfig || Array.isArray(serializerConfig) || typeof serializerConfig !== "object") {
393
- throw configurationError("withLogBrewMetroConfig requires config.serializer to be an object");
394
- }
395
- if (serializerConfig.customSerializer?.[WRAPPED_SERIALIZER] === true) {
249
+ const serializerConfig = requireSerializerConfig(config);
250
+ if (field(serializerConfig["customSerializer"], WRAPPED_SERIALIZER) === true) {
396
251
  return config;
397
252
  }
398
253
  return {
399
254
  ...config,
400
255
  serializer: {
401
256
  ...serializerConfig,
402
- customSerializer: createLogBrewMetroSerializer(serializerConfig.customSerializer),
403
- },
257
+ customSerializer: createLogBrewMetroSerializer(serializerConfig["customSerializer"])
258
+ }
404
259
  };
405
260
  }
406
261
 
@@ -408,5 +263,6 @@ module.exports = {
408
263
  createLogBrewMetroSerializer,
409
264
  getLogBrewExpoConfig,
410
265
  withLogBrewMetroConfig,
411
- default: withLogBrewMetroConfig,
266
+
267
+ default: withLogBrewMetroConfig
412
268
  };
package/metro.d.cts CHANGED
@@ -1,57 +1,2 @@
1
- export type LogBrewMetroSerializerResult = string | {
2
- code: string;
3
- map: string;
4
- [key: string]: unknown;
5
- };
6
-
7
- export type LogBrewMetroSerializer<TModule = unknown, TGraph = unknown, TOptions = unknown> = (
8
- entryPoint: string,
9
- preModules: readonly TModule[],
10
- graph: TGraph,
11
- options: TOptions,
12
- ) => LogBrewMetroSerializerResult | Promise<LogBrewMetroSerializerResult>;
13
-
14
- export type LogBrewMetroConfig = {
15
- serializer?: {
16
- customSerializer?: unknown;
17
- } | Record<string, unknown>;
18
- } | Record<string, unknown>;
19
-
20
- export type LogBrewMetroConfigOptions = {
21
- enabled?: boolean;
22
- };
23
-
24
- export type LogBrewExpoSerializationInput<TModule = unknown, TGraph = unknown> = {
25
- debugId?: string;
26
- graph: TGraph;
27
- premodules: TModule[];
28
- };
29
-
30
- export type LogBrewExpoDebugIdPlugin<TModule = unknown, TGraph = unknown> = (
31
- input: LogBrewExpoSerializationInput<TModule, TGraph>,
32
- ) => TModule[];
33
-
34
- export type LogBrewExpoConfigOptions<TConfig extends LogBrewMetroConfig = LogBrewMetroConfig> = {
35
- enabled?: boolean;
36
- getDefaultConfig?: (...args: never[]) => TConfig;
37
- unstable_beforeAssetSerializationPlugins?: LogBrewExpoDebugIdPlugin[];
38
- [key: string]: unknown;
39
- };
40
-
41
- export declare function createLogBrewMetroSerializer<TModule, TGraph, TOptions>(
42
- customSerializer: LogBrewMetroSerializer<TModule, TGraph, TOptions>,
43
- ): LogBrewMetroSerializer<TModule, TGraph, TOptions>;
44
-
45
- export declare function createLogBrewMetroSerializer(customSerializer?: null): LogBrewMetroSerializer;
46
-
47
- export declare function getLogBrewExpoConfig<TConfig extends LogBrewMetroConfig = LogBrewMetroConfig>(
48
- projectRoot: string,
49
- options?: LogBrewExpoConfigOptions<TConfig>,
50
- ): TConfig;
51
-
52
- export declare function withLogBrewMetroConfig<T extends LogBrewMetroConfig>(
53
- config: T,
54
- options?: LogBrewMetroConfigOptions,
55
- ): T;
56
-
57
- export default withLogBrewMetroConfig;
1
+ export * from "./metro.js";
2
+ export { default } from "./metro.js";