microsoft/vscode-react-native

Public

mirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
dev/v-zhenyuan/update-parameters

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/debugger/sourceMap.ts

212lines · modecode

1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for details.
3
4import * as url from "url";
5import * as path from "path";
6import { RawSourceMap } from "source-map";
7import { SourceMapsCombinator } from "./sourceMapsCombinator";
8
9const IS_REMOTE = /^[A-Za-z]{2,}:\/\//; // Detection remote sources or specific protocols (like "webpack:///")
10
11interface ISourceMap extends RawSourceMap {
12 sections?: ISourceMapSection[];
13}
14interface ISourceMapSection {
15 map: ISourceMap | null;
16 offset: { column: number; line: number };
17}
18
19export interface IStrictUrl extends url.Url {
20 pathname: string;
21 href: string;
22}
23
24export class SourceMapUtil {
25 private static SourceMapURLGlobalRegex: RegExp =
26 /\/\/(#|@) sourceMappingURL=((?!data:)[^ ]+?)\s*$/gm;
27 private static SourceMapURLRegex: RegExp = /\/\/(#|@) sourceMappingURL=((?!data:)[^ ]+?)\s*$/m;
28 private static SourceURLRegex: RegExp = /^\/\/[#@] ?sourceURL=(.+)$/m;
29
30 /**
31 * Given a script body and URL, this method parses the body and finds the corresponding source map URL.
32 * If the source map URL is not found in the body in the expected form, null is returned.
33 */
34 public getSourceMapURL(scriptUrl: url.Url, scriptBody: string): IStrictUrl | null {
35 let result: IStrictUrl | null = null;
36
37 // scriptUrl = "http://localhost:8081/index.ios.bundle?platform=ios&dev=true"
38 const sourceMappingRelativeUrl = this.getSourceMapRelativeUrl(scriptBody); // sourceMappingRelativeUrl = "/index.ios.map?platform=ios&dev=true"
39 if (sourceMappingRelativeUrl) {
40 const sourceMappingUrl = url.parse(sourceMappingRelativeUrl);
41 sourceMappingUrl.protocol = scriptUrl.protocol;
42 sourceMappingUrl.host = scriptUrl.host;
43 // parse() repopulates all the properties of the URL
44 result = <IStrictUrl>url.parse(url.format(sourceMappingUrl));
45 }
46
47 return result;
48 }
49
50 /**
51 * Updates the contents of a source map file to be VS Code friendly:
52 * - makes source paths unix style and relative to the sources root path
53 * - updates the url of the script file
54 * - deletes the script content from the source map
55 *
56 * @parameter sourceMapBody - body of the source map as generated by the RN Packager.
57 * @parameter scriptPath - path of the script file asssociated with this source map.
58 * @parameter sourcesRootPath - root path of sources
59 *
60 */
61 public updateSourceMapFile(
62 sourceMapBody: string,
63 scriptPath: string,
64 sourcesRootPath: string,
65 packagerRemoteRoot?: string,
66 packagerLocalRoot?: string,
67 ): string {
68 try {
69 let sourceMap = <ISourceMap>JSON.parse(sourceMapBody);
70
71 if (sourceMap.sections) {
72 // Preserve indexed sourcemap offsets even when Metro emits a null section map.
73 sourceMap.sections = sourceMap.sections.map(section => ({
74 ...section,
75 map: section.map ?? SourceMapUtil.createEmptySourceMap(),
76 }));
77
78 // eslint-disable-next-line @typescript-eslint/no-var-requires
79 sourceMap = require("flatten-source-map")(sourceMap);
80 }
81
82 const sourceMapsCombinator = new SourceMapsCombinator();
83 sourceMap = sourceMapsCombinator.convert(sourceMap);
84
85 if (sourceMap.sources) {
86 sourceMap.sources = sourceMap.sources.map(sourcePath =>
87 IS_REMOTE.test(sourcePath)
88 ? sourcePath
89 : this.updateSourceMapPath(
90 sourcePath,
91 sourcesRootPath,
92 packagerRemoteRoot,
93 packagerLocalRoot,
94 ),
95 );
96 }
97
98 delete sourceMap.sourcesContent;
99 sourceMap.sourceRoot = "";
100 sourceMap.file = scriptPath;
101 return JSON.stringify(sourceMap);
102 } catch (exception) {
103 return sourceMapBody;
104 }
105 }
106
107 public appendSourceMapPaths(scriptBody: string, sourceMappingUrl: string): string {
108 scriptBody += `//# sourceMappingURL=${sourceMappingUrl}`;
109 return scriptBody;
110 }
111
112 /**
113 * Updates source map URLs in the script body.
114 */
115 public updateScriptPaths(scriptBody: string, sourceMappingUrl: IStrictUrl): string {
116 const sourceMapMatch = this.searchSourceMapURL(scriptBody);
117 if (sourceMapMatch) {
118 // Update the body with the new location of the source map on storage.
119 return scriptBody.replace(
120 sourceMapMatch[0],
121 `//# sourceMappingURL=${path.basename(sourceMappingUrl.pathname)}`,
122 );
123 }
124 return scriptBody;
125 }
126
127 /**
128 * Removes sourceURL from the script body since RN 0.61 because it breaks sourcemaps.
129 * Example: //# sourceURL=http://localhost:8081/index.bundle?platform=android&dev=true&minify=false -> ""
130 */
131 public removeSourceURL(scriptBody: string): string {
132 return scriptBody.replace(SourceMapUtil.SourceURLRegex, "");
133 }
134
135 /**
136 * Parses the body of a script searching for a source map URL.
137 * It supports the following source map url styles:
138 *
139 * `//# sourceMappingURL=path/to/source/map`
140 *
141 * `//@ sourceMappingURL=path/to/source/map`
142 *
143 * Returns the last match if found, null otherwise.
144 */
145 public getSourceMapRelativeUrl(body: string): string | null {
146 const sourceMapMatch = this.searchSourceMapURL(body);
147 // If match is null, the body doesn't contain the source map
148 if (sourceMapMatch) {
149 // On React Native macOS 0.62 and RN Windows 0.65 sourceMappingUrl looks like:
150 // # sourceMappingURL=//localhost:8081/index.map?platform=macos&dev=true&minify=false
151 // Add 'http:' protocol to avoid errors in further processing
152 const el = sourceMapMatch[2];
153 const macOsOrWin =
154 (el.includes("platform=macos") || el.includes("platform=window")) &&
155 el.startsWith("//") &&
156 !el.includes("http:");
157
158 return macOsOrWin ? `http:${el}` : el;
159 }
160 return null;
161 }
162
163 private searchSourceMapURL(str: string): RegExpMatchArray | null {
164 const matchesList = str
165 .match(SourceMapUtil.SourceMapURLGlobalRegex)
166 ?.filter(s => !s.includes("\\n"));
167 if (matchesList && matchesList.length) {
168 return matchesList[matchesList.length - 1].match(SourceMapUtil.SourceMapURLRegex);
169 }
170
171 return null;
172 }
173
174 /**
175 * Given an absolute source path, this method does two things:
176 * 1. It changes the path from absolute to be relative to the sourcesRootPath parameter.
177 * 2. It changes the path separators to Unix style.
178 */
179 private updateSourceMapPath(
180 sourcePath: string,
181 sourcesRootPath: string,
182 packagerRemoteRoot?: string,
183 packagerLocalRoot?: string,
184 ) {
185 if (packagerRemoteRoot && packagerLocalRoot) {
186 packagerRemoteRoot = this.makeUnixStylePath(packagerRemoteRoot);
187 packagerLocalRoot = this.makeUnixStylePath(packagerLocalRoot);
188 sourcePath = sourcePath.replace(packagerRemoteRoot, packagerLocalRoot);
189 }
190 const relativeSourcePath = path.relative(sourcesRootPath, sourcePath);
191 return this.makeUnixStylePath(relativeSourcePath);
192 }
193
194 /**
195 * Visual Studio Code source mapping requires Unix style path separators.
196 * This method replaces all back-slash characters in a given string with forward-slash ones.
197 */
198 private makeUnixStylePath(p: string): string {
199 const pathArgs = p.split(path.sep);
200 return path.posix.join.apply(null, pathArgs);
201 }
202
203 private static createEmptySourceMap(): ISourceMap {
204 return {
205 version: 3,
206 sources: [],
207 names: [],
208 mappings: "",
209 file: "",
210 };
211 }
212}
213