-
-
Notifications
You must be signed in to change notification settings - Fork 360
Expand file tree
/
Copy pathsentryMetroSerializer.test.ts
More file actions
364 lines (302 loc) · 14 KB
/
sentryMetroSerializer.test.ts
File metadata and controls
364 lines (302 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
import type { MixedOutput, Module } from 'metro';
import * as fs from 'fs';
import CountingSet from 'metro/private/lib/CountingSet';
import * as countLines from 'metro/private/lib/countLines';
import { minify } from 'uglify-js';
import { createSentryMetroSerializer } from '../../src/js/tools/sentryMetroSerializer';
import { createDebugIdSnippet, type MetroSerializer, type VirtualJSOutput } from '../../src/js/tools/utils';
describe('Sentry Metro Serializer', () => {
test('debug id minified code snippet is the same as in the original implementation', () => {
const original = fs.readFileSync(`${__dirname}/../../scripts/sentry-debugid-injection-snippet.js`, 'utf8');
const minified = minify(original).code;
const snippet = createDebugIdSnippet('__SENTRY_DEBUG_ID__');
expect(minified).toEqual(snippet);
});
test('generates bundle and source map with deterministic uuidv5 debug id', async () => {
const serializer = createSentryMetroSerializer();
const bundle = await serializer(...mockMinSerializerArgs());
if (typeof bundle === 'string') {
fail('Expected bundle to be an object with a "code" property');
}
expect(bundle.code).toEqual(
'var _sentryDebugIds,_sentryDebugIdIdentifier;void 0===_sentryDebugIds&&(_sentryDebugIds={});try{var stack=(new Error).stack;stack&&(_sentryDebugIds[stack]="c9e276ed-1171-4e26-ac5d-0193a85ed160",_sentryDebugIdIdentifier="sentry-dbid-c9e276ed-1171-4e26-ac5d-0193a85ed160")}catch(e){}\n//# debugId=c9e276ed-1171-4e26-ac5d-0193a85ed160',
);
expect(bundle.map).toEqual(
'{"version":3,"sources":["__debugid__"],"sourcesContent":["var _sentryDebugIds,_sentryDebugIdIdentifier;void 0===_sentryDebugIds&&(_sentryDebugIds={});try{var stack=(new Error).stack;stack&&(_sentryDebugIds[stack]=\\"c9e276ed-1171-4e26-ac5d-0193a85ed160\\",_sentryDebugIdIdentifier=\\"sentry-dbid-c9e276ed-1171-4e26-ac5d-0193a85ed160\\")}catch(e){}"],"names":[],"mappings":"","debug_id":"c9e276ed-1171-4e26-ac5d-0193a85ed160","debugId":"c9e276ed-1171-4e26-ac5d-0193a85ed160"}',
);
});
test('generated debug id is uuid v4 format', async () => {
const serializer = createSentryMetroSerializer();
const bundle = await serializer(...mockMinSerializerArgs());
const debugId = determineDebugIdFromBundleSource(typeof bundle === 'string' ? bundle : bundle.code);
expect(debugId).toEqual('c9e276ed-1171-4e26-ac5d-0193a85ed160');
});
test('adds debug id snipped after prelude module and before ', async () => {
const serializer = createSentryMetroSerializer();
const bundle = await serializer(...mockWithPreludeAndDepsSerializerArgs());
if (typeof bundle === 'string') {
fail('Expected bundle to be an object with a "code" property');
}
expect(bundle.code).toEqual(fs.readFileSync(`${__dirname}/fixtures/bundleWithPrelude.js.fixture`, 'utf8'));
expect(bundle.map).toEqual(fs.readFileSync(`${__dirname}/fixtures/bundleWithPrelude.js.fixture.map`, 'utf8'));
});
test('works when shouldAddToIgnoreList is undefined', async () => {
const serializer = createSentryMetroSerializer();
const args = mockMinSerializerArgs({ shouldAddToIgnoreList: undefined });
const bundle = await serializer(...args);
expect(bundle).toBeDefined();
if (typeof bundle !== 'string') {
expect(bundle.code).toBeDefined();
expect(bundle.map).toBeDefined();
const debugId = determineDebugIdFromBundleSource(bundle.code);
expect(debugId).toMatch(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/);
}
});
test('calculates debug id from bundle code when debug id module is not found', async () => {
// Create a custom serializer that returns bundle code without the debug ID module
const customSerializer: MetroSerializer = async () => {
const bundleCodeWithoutDebugId = 'console.log("test bundle");';
return {
code: bundleCodeWithoutDebugId,
map: '{"version":3,"sources":[],"names":[],"mappings":""}',
};
};
const serializer = createSentryMetroSerializer(customSerializer);
const bundle = await serializer(...mockMinSerializerArgs());
if (typeof bundle === 'string') {
fail('Expected bundle to be an object with a "code" property');
}
// The debug ID should be calculated from the bundle code content
// and added as a comment in the bundle code
expect(bundle.code).toContain('//# debugId=');
// Extract the debug ID from the comment
const debugIdMatch = bundle.code.match(/\/\/# debugId=([0-9a-fA-F-]+)/);
expect(debugIdMatch).toBeTruthy();
const debugId = debugIdMatch?.[1];
// Verify it's a valid UUID format
expect(debugId).toMatch(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/);
// Verify the debug ID is also in the source map
const sourceMap = JSON.parse(bundle.map);
expect(sourceMap.debug_id).toBe(debugId);
expect(sourceMap.debugId).toBe(debugId);
// The calculated debug ID should be deterministic based on the bundle content
// Running the serializer again with the same content should produce the same debug ID
const bundle2 = await serializer(...mockMinSerializerArgs());
if (typeof bundle2 !== 'string') {
const debugIdMatch2 = bundle2.code.match(/\/\/# debugId=([0-9a-fA-F-]+)/);
expect(debugIdMatch2?.[1]).toBe(debugId);
}
});
describe('calculateDebugId', () => {
// We need to access the private function for testing
const crypto = require('crypto');
const { stringToUUID } = require('../../src/js/tools/utils');
function calculateDebugId(bundleCode: string, modules?: Array<[id: number, code: string]>): string {
const hash = crypto.createHash('md5');
hash.update(bundleCode);
if (modules) {
for (const [, code] of modules) {
hash.update(code);
}
}
return stringToUUID(hash.digest('hex'));
}
test('generates a valid UUID v4 format', () => {
const bundleCode = 'console.log("test");';
const debugId = calculateDebugId(bundleCode);
expect(debugId).toMatch(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/);
});
test('generates deterministic debug ID for the same bundle code', () => {
const bundleCode = 'console.log("test");';
const debugId1 = calculateDebugId(bundleCode);
const debugId2 = calculateDebugId(bundleCode);
expect(debugId1).toBe(debugId2);
});
test('generates different debug IDs for different bundle code', () => {
const bundleCode1 = 'console.log("test1");';
const bundleCode2 = 'console.log("test2");';
const debugId1 = calculateDebugId(bundleCode1);
const debugId2 = calculateDebugId(bundleCode2);
expect(debugId1).not.toBe(debugId2);
});
test('handles undefined modules parameter', () => {
const bundleCode = 'console.log("test");';
const debugId = calculateDebugId(bundleCode, undefined);
expect(debugId).toMatch(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/);
});
test('handles empty modules array', () => {
const bundleCode = 'console.log("test");';
const debugId1 = calculateDebugId(bundleCode, []);
const debugId2 = calculateDebugId(bundleCode);
// Should generate the same debug ID as without modules
expect(debugId1).toBe(debugId2);
});
test('includes modules in debug ID calculation', () => {
const bundleCode = 'console.log("test");';
const modules: Array<[id: number, code: string]> = [
[1, 'function foo() { return "bar"; }'],
[2, 'function baz() { return "qux"; }'],
];
const debugIdWithModules = calculateDebugId(bundleCode, modules);
const debugIdWithoutModules = calculateDebugId(bundleCode);
expect(debugIdWithModules).not.toBe(debugIdWithoutModules);
});
test('generates different debug IDs when modules differ', () => {
const bundleCode = 'console.log("test");';
const modules1: Array<[id: number, code: string]> = [[1, 'function foo() { return "bar"; }']];
const modules2: Array<[id: number, code: string]> = [[1, 'function foo() { return "baz"; }']];
const debugId1 = calculateDebugId(bundleCode, modules1);
const debugId2 = calculateDebugId(bundleCode, modules2);
expect(debugId1).not.toBe(debugId2);
});
test('generates same debug ID when modules have same content but different IDs', () => {
const bundleCode = 'console.log("test");';
const modules1: Array<[id: number, code: string]> = [[1, 'function foo() { return "bar"; }']];
const modules2: Array<[id: number, code: string]> = [[2, 'function foo() { return "bar"; }']];
const debugId1 = calculateDebugId(bundleCode, modules1);
const debugId2 = calculateDebugId(bundleCode, modules2);
// Module IDs are not used in the hash calculation, only the code
expect(debugId1).toBe(debugId2);
});
test('generates different debug IDs when module order differs', () => {
const bundleCode = 'console.log("test");';
const modules1: Array<[id: number, code: string]> = [
[1, 'function foo() { return "bar"; }'],
[2, 'function baz() { return "qux"; }'],
];
const modules2: Array<[id: number, code: string]> = [
[2, 'function baz() { return "qux"; }'],
[1, 'function foo() { return "bar"; }'],
];
const debugId1 = calculateDebugId(bundleCode, modules1);
const debugId2 = calculateDebugId(bundleCode, modules2);
// Order matters in hash calculation
expect(debugId1).not.toBe(debugId2);
});
test('handles empty bundle code', () => {
const debugId = calculateDebugId('');
expect(debugId).toMatch(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/);
});
test('handles large bundle code', () => {
const largeBundleCode = 'console.log("test");'.repeat(10000);
const debugId = calculateDebugId(largeBundleCode);
expect(debugId).toMatch(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/);
});
});
test('createDefaultMetroSerializer can be created without Metro internals being loaded at import time', () => {
// This test verifies that the lazy-loading of Metro internals works correctly.
// The createDefaultMetroSerializer function should be callable without triggering
// module-level requires of Metro internals at import time.
// See: https://github.com/getsentry/sentry-react-native/issues/5957
// Import the function
const { createDefaultMetroSerializer: createSerializer } = require('../../src/js/tools/vendor/metro/utils');
// Create the serializer - this should succeed without loading Metro internals
const serializer = createSerializer();
expect(typeof serializer).toBe('function');
// Verify the serializer can be invoked with proper arguments and produces output
const [entryPoint, preModules, graph, options] = mockMinSerializerArgs();
const result = serializer(entryPoint, preModules, graph, options);
expect(result).toHaveProperty('code');
expect(result).toHaveProperty('map');
expect(typeof result.code).toBe('string');
expect(typeof result.map).toBe('string');
// Both code and map should exist (even if minimal for empty bundle)
expect(result.code).toBeDefined();
expect(result.map).toBeDefined();
// }
});
});
function mockMinSerializerArgs(options?: {
shouldAddToIgnoreList?: ((module: Module<MixedOutput>) => boolean) | undefined;
}): Parameters<MetroSerializer> {
let modulesCounter = 0;
const baseOptions: Record<string, any> = {
asyncRequireModulePath: 'asyncRequire',
createModuleId: (_filePath: string): number => modulesCounter++,
dev: false,
getRunModuleStatement: (_moduleId: string | number): string => '',
includeAsyncPaths: false,
modulesOnly: false,
processModuleFilter: (_module: Module<MixedOutput>) => true,
projectRoot: '/project/root',
runBeforeMainModule: [],
runModule: false,
serverRoot: '/server/root',
};
if (options && 'shouldAddToIgnoreList' in options) {
baseOptions.shouldAddToIgnoreList = options.shouldAddToIgnoreList;
} else {
baseOptions.shouldAddToIgnoreList = (_module: Module<MixedOutput>) => false;
}
return [
'index.js',
[],
{
entryPoints: new Set(),
dependencies: new Map(),
transformOptions: {
hot: false,
dev: false,
minify: false,
type: 'script',
unstable_transformProfile: 'hermes-stable',
},
},
baseOptions as any,
];
}
function mockWithPreludeAndDepsSerializerArgs(): Parameters<MetroSerializer> {
const mockPreludeCode = '__mock_prelude__';
const indexJsCode = '__mock_index_js__';
const args = mockMinSerializerArgs();
args[1] = [
{
dependencies: new Map(),
getSource: () => Buffer.from(mockPreludeCode),
inverseDependencies: new CountingSet(),
path: '__prelude__',
output: [
<VirtualJSOutput>{
type: 'js/script/virtual',
data: {
code: mockPreludeCode,
lineCount: countLines(indexJsCode),
map: [],
},
},
],
},
];
// @ts-expect-error - This is a mock
args[2].dependencies = <Parameters<MetroSerializer>[2]['dependencies']>new Map([
[
'index.js',
<Module<VirtualJSOutput>>{
dependencies: new Map(),
getSource: () => Buffer.from(indexJsCode),
inverseDependencies: new CountingSet(),
path: 'index.js',
output: [
{
type: 'js/script/virtual',
data: {
code: indexJsCode,
lineCount: countLines(indexJsCode),
map: [],
},
},
],
},
],
]);
return args;
}
/**
* This function is on purpose not shared with the actual implementation.
*/
function determineDebugIdFromBundleSource(code: string): string | undefined {
const match = code.match(
/sentry-dbid-([0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12})/,
);
return match?.[1];
}