|
| 1 | +import * as fs from "fs"; |
| 2 | +import MagicString from "magic-string"; |
| 3 | +import * as path from "path"; |
| 4 | +import * as util from "util"; |
| 5 | +import { Logger } from "./sentry/logger"; |
| 6 | +import { stringToUUID } from "./utils"; |
| 7 | + |
| 8 | +// TODO: Find a more elaborate process to generate this. (Maybe with type checking and built-in minification) |
| 9 | +const DEBUG_ID_INJECTOR_SNIPPET = |
| 10 | + ';!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="__SENTRY_DEBUG_ID__",e._sentryDebugIdIdentifier="sentry-dbid-__SENTRY_DEBUG_ID__")}catch(e){}}();'; |
| 11 | + |
| 12 | +export function injectDebugIdSnippetIntoChunk(code: string) { |
| 13 | + const debugId = stringToUUID(code); // generate a deterministic debug ID |
| 14 | + const ms = new MagicString(code); |
| 15 | + |
| 16 | + const codeToInject = DEBUG_ID_INJECTOR_SNIPPET.replace(/__SENTRY_DEBUG_ID__/g, debugId); |
| 17 | + |
| 18 | + // We need to be careful not to inject the snippet before any `"use strict";`s. |
| 19 | + // As an additional complication `"use strict";`s may come after any number of comments. |
| 20 | + const commentUseStrictRegex = |
| 21 | + /^(?:\s*|\/\*(.|\r|\n)*?\*\/|\/\/.*?[\n\r])*(?:"use strict";|'use strict';)?/; |
| 22 | + |
| 23 | + if (code.match(commentUseStrictRegex)?.[0]) { |
| 24 | + // Add injected code after any comments or "use strict" at the beginning of the bundle. |
| 25 | + ms.replace(commentUseStrictRegex, (match) => `${match}${codeToInject}`); |
| 26 | + } else { |
| 27 | + // ms.replace() doesn't work when there is an empty string match (which happens if |
| 28 | + // there is neither, a comment, nor a "use strict" at the top of the chunk) so we |
| 29 | + // need this special case here. |
| 30 | + ms.prepend(codeToInject); |
| 31 | + } |
| 32 | + |
| 33 | + return { |
| 34 | + code: ms.toString(), |
| 35 | + map: ms.generateMap(), |
| 36 | + }; |
| 37 | +} |
| 38 | + |
| 39 | +export async function prepareBundleForDebugIdUpload( |
| 40 | + bundleFilePath: string, |
| 41 | + uploadFolder: string, |
| 42 | + uniqueUploadName: string, |
| 43 | + logger: Logger |
| 44 | +) { |
| 45 | + let bundleContent; |
| 46 | + try { |
| 47 | + bundleContent = await util.promisify(fs.readFile)(bundleFilePath, "utf8"); |
| 48 | + } catch (e) { |
| 49 | + logger.warn(`Could not read bundle to determine debug ID and source map: ${bundleFilePath}`); |
| 50 | + return; |
| 51 | + } |
| 52 | + |
| 53 | + const debugId = determineDebugIdFromBundleSource(bundleContent); |
| 54 | + if (debugId === undefined) { |
| 55 | + logger.warn(`Could not determine debug ID from bundle: ${bundleFilePath}`); |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + bundleContent += `\n//# debugId=${debugId}`; |
| 60 | + const writeSourceFilePromise = util.promisify(fs.writeFile)( |
| 61 | + path.join(uploadFolder, `${uniqueUploadName}.js`), |
| 62 | + bundleContent, |
| 63 | + "utf-8" |
| 64 | + ); |
| 65 | + |
| 66 | + const writeSourceMapFilePromise = determineSourceMapPathFromBundle( |
| 67 | + bundleFilePath, |
| 68 | + bundleContent, |
| 69 | + logger |
| 70 | + ).then(async (sourceMapPath): Promise<void> => { |
| 71 | + if (sourceMapPath) { |
| 72 | + return await prepareSourceMapForDebugIdUpload( |
| 73 | + sourceMapPath, |
| 74 | + path.join(uploadFolder, `${uniqueUploadName}.js.map`), |
| 75 | + debugId, |
| 76 | + logger |
| 77 | + ); |
| 78 | + } |
| 79 | + }); |
| 80 | + |
| 81 | + return Promise.all([writeSourceFilePromise, writeSourceMapFilePromise]); |
| 82 | +} |
| 83 | + |
| 84 | +/** |
| 85 | + * Looks for a particular string pattern (`sdbid-[debug ID]`) in the bundle |
| 86 | + * source and extracts the bundle's debug ID from it. |
| 87 | + * |
| 88 | + * The string pattern is injected via the debug ID injection snipped. |
| 89 | + */ |
| 90 | +function determineDebugIdFromBundleSource(code: string): string | undefined { |
| 91 | + const match = code.match( |
| 92 | + /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})/ |
| 93 | + ); |
| 94 | + |
| 95 | + if (match) { |
| 96 | + return match[1]; |
| 97 | + } else { |
| 98 | + return undefined; |
| 99 | + } |
| 100 | +} |
| 101 | + |
| 102 | +/** |
| 103 | + * Applies a set of heuristics to find the source map for a particular bundle. |
| 104 | + * |
| 105 | + * @returns the path to the bundle's source map or `undefined` if none could be found. |
| 106 | + */ |
| 107 | +async function determineSourceMapPathFromBundle( |
| 108 | + bundlePath: string, |
| 109 | + bundleSource: string, |
| 110 | + logger: Logger |
| 111 | +): Promise<string | undefined> { |
| 112 | + // 1. try to find source map at `sourceMappingURL` location |
| 113 | + const sourceMappingUrlMatch = bundleSource.match(/^\/\/# sourceMappingURL=(.*)$/); |
| 114 | + if (sourceMappingUrlMatch) { |
| 115 | + const sourceMappingUrl = path.normalize(sourceMappingUrlMatch[1] as string); |
| 116 | + if (path.isAbsolute(sourceMappingUrl)) { |
| 117 | + return sourceMappingUrl; |
| 118 | + } else { |
| 119 | + return path.join(path.dirname(bundlePath), sourceMappingUrl); |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + // 2. try to find source map at path adjacent to chunk source, but with `.map` appended |
| 124 | + try { |
| 125 | + const adjacentSourceMapFilePath = bundlePath + ".map"; |
| 126 | + await util.promisify(fs.access)(adjacentSourceMapFilePath); |
| 127 | + return adjacentSourceMapFilePath; |
| 128 | + } catch (e) { |
| 129 | + // noop |
| 130 | + } |
| 131 | + |
| 132 | + logger.warn(`Could not determine source map path for bundle: ${bundlePath}`); |
| 133 | + return undefined; |
| 134 | +} |
| 135 | + |
| 136 | +/** |
| 137 | + * Reads a source map, injects debug ID fields, and writes the source map to the target path. |
| 138 | + */ |
| 139 | +async function prepareSourceMapForDebugIdUpload( |
| 140 | + sourceMapPath: string, |
| 141 | + targetPath: string, |
| 142 | + debugId: string, |
| 143 | + logger: Logger |
| 144 | +): Promise<void> { |
| 145 | + try { |
| 146 | + const sourceMapFileContent = await util.promisify(fs.readFile)(sourceMapPath, { |
| 147 | + encoding: "utf8", |
| 148 | + }); |
| 149 | + |
| 150 | + const map = JSON.parse(sourceMapFileContent) as Record<string, string>; |
| 151 | + |
| 152 | + // For now we write both fields until we know what will become the standard - if ever. |
| 153 | + map["debug_id"] = debugId; |
| 154 | + map["debugId"] = debugId; |
| 155 | + |
| 156 | + await util.promisify(fs.writeFile)(targetPath, JSON.stringify(map), { |
| 157 | + encoding: "utf8", |
| 158 | + }); |
| 159 | + } catch (e) { |
| 160 | + logger.warn(`Failed to prepare source map for debug ID upload: ${sourceMapPath}`); |
| 161 | + } |
| 162 | +} |
0 commit comments