-
-
Notifications
You must be signed in to change notification settings - Fork 359
Expand file tree
/
Copy pathsentryMetroSerializer.ts
More file actions
168 lines (146 loc) · 6.46 KB
/
sentryMetroSerializer.ts
File metadata and controls
168 lines (146 loc) · 6.46 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
import * as crypto from 'crypto';
// eslint-disable-next-line import/no-extraneous-dependencies
import type { MixedOutput, Module, ReadOnlyGraph } from 'metro';
import type { Bundle, MetroSerializer, MetroSerializerOutput, SerializedBundle, VirtualJSOutput } from './utils';
import {
createDebugIdSnippet,
createVirtualJSModule,
determineDebugIdFromBundleSource,
prependModule,
stringToUUID,
} from './utils';
import { createDefaultMetroSerializer } from './vendor/metro/utils';
type SourceMap = Record<string, unknown>;
const DEBUG_ID_PLACE_HOLDER = '__debug_id_place_holder__';
const DEBUG_ID_MODULE_PATH = '__debugid__';
const SOURCE_MAP_COMMENT = '//# sourceMappingURL=';
const DEBUG_ID_COMMENT = '//# debugId=';
/**
* Adds Sentry Debug ID polyfill module to the bundle.
*/
export function unstableBeforeAssetSerializationDebugIdPlugin({
premodules,
debugId,
}: {
graph: ReadOnlyGraph<MixedOutput>;
premodules: Module[];
debugId?: string;
}): Module[] {
if (!debugId) {
return premodules;
}
const debugIdModuleExists = premodules.findIndex(module => module.path === DEBUG_ID_MODULE_PATH) != -1;
if (debugIdModuleExists) {
// eslint-disable-next-line no-console
console.warn('\n\nDebug ID module found. Skipping Sentry Debug ID module...\n\n');
return premodules;
}
const debugIdModule = createDebugIdModule(debugId);
return prependModule(premodules, debugIdModule);
}
/**
* Creates a Metro serializer that adds Debug ID module to the plain bundle.
* The Debug ID module is a virtual module that provides a debug ID in runtime.
*
* RAM Bundles do not support custom serializers.
*/
export const createSentryMetroSerializer = (customSerializer?: MetroSerializer): MetroSerializer => {
const serializer = customSerializer || createDefaultMetroSerializer();
return async function (entryPoint, preModules, graph, options) {
if (graph.transformOptions.hot) {
return serializer(entryPoint, preModules, graph, options);
}
const debugIdModuleExists = preModules.findIndex(module => module.path === DEBUG_ID_MODULE_PATH) != -1;
if (debugIdModuleExists) {
// eslint-disable-next-line no-console
console.warn('Debug ID module found. Skipping Sentry Debug ID module...');
return serializer(entryPoint, preModules, graph, options);
}
const debugIdModule = createDebugIdModule(DEBUG_ID_PLACE_HOLDER);
options.sentryBundleCallback = createSentryBundleCallback(debugIdModule);
const modifiedPreModules = prependModule(preModules, debugIdModule);
// Run wrapped serializer
const serializerResult = serializer(entryPoint, modifiedPreModules, graph, options);
const { code: bundleCode, map: bundleMapString } = await extractSerializerResult(serializerResult);
// Add debug id comment to the bundle
let debugId = determineDebugIdFromBundleSource(bundleCode);
if (!debugId) {
// For lazy-loaded chunks or bundles without the debug ID module,
// calculate the debug ID from the bundle content.
// This ensures Metro 0.83.2+ code-split bundles get debug IDs.
// That needs to be done because when Metro 0.83.2 stopped importing `BabelSourceMapSegment`
// from `@babel/generator` and defined it locally, it subtly changed the source map output format.
// https://github.com/facebook/metro/blob/main/packages/metro-source-map/src/source-map.js#L47
debugId = calculateDebugId(bundleCode);
// eslint-disable-next-line no-console
console.log('info ' + `Bundle Debug ID (calculated): ${debugId}`);
}
// Only print debug id for command line builds => not hot reload from dev server
// eslint-disable-next-line no-console
console.log('info ' + `Bundle Debug ID: ${debugId}`);
const debugIdComment = `${DEBUG_ID_COMMENT}${debugId}`;
const indexOfSourceMapComment = bundleCode.lastIndexOf(SOURCE_MAP_COMMENT);
const bundleCodeWithDebugId =
indexOfSourceMapComment === -1
? // If source map comment is missing lets just add the debug id comment
`${bundleCode}\n${debugIdComment}`
: // If source map comment is present lets add the debug id comment before it
`${bundleCode.substring(0, indexOfSourceMapComment) + debugIdComment}\n${bundleCode.substring(
indexOfSourceMapComment,
)}`;
const bundleMap: SourceMap = JSON.parse(bundleMapString);
// For now we write both fields until we know what will become the standard - if ever.
bundleMap['debug_id'] = debugId;
bundleMap['debugId'] = debugId;
return {
code: bundleCodeWithDebugId,
map: JSON.stringify(bundleMap),
};
};
};
/**
* This function is expected to be called after serializer creates the final bundle object
* and before the source maps are generated.
*
* It injects a debug ID into the bundle and returns the modified bundle.
*
* Access it via `options.sentryBundleCallback` in your custom serializer.
*/
function createSentryBundleCallback(debugIdModule: Module<VirtualJSOutput> & { setSource: (code: string) => void }) {
return (bundle: Bundle) => {
const debugId = calculateDebugId(bundle.pre, bundle.modules);
debugIdModule.setSource(injectDebugId(debugIdModule.getSource().toString(), debugId));
bundle.pre = injectDebugId(bundle.pre, debugId);
return bundle;
};
}
async function extractSerializerResult(serializerResult: MetroSerializerOutput): Promise<SerializedBundle> {
if (typeof serializerResult === 'string') {
return { code: serializerResult, map: '{}' };
}
if ('map' in serializerResult) {
return { code: serializerResult.code, map: serializerResult.map };
}
const awaitedResult = await serializerResult;
if (typeof awaitedResult === 'string') {
return { code: awaitedResult, map: '{}' };
}
return { code: awaitedResult.code, map: awaitedResult.map };
}
function createDebugIdModule(debugId: string): Module<VirtualJSOutput> & { setSource: (code: string) => void } {
return createVirtualJSModule(DEBUG_ID_MODULE_PATH, createDebugIdSnippet(debugId));
}
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'));
}
function injectDebugId(code: string, debugId: string): string {
// eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor
return code.replace(new RegExp(DEBUG_ID_PLACE_HOLDER, 'g'), debugId);
}