microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
dev/v-peq/remove-ios-relative-project-path

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/sourceMap.ts

248lines · 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 sourceMap = SourceMapUtil.flattenIndexedSourceMap(sourceMap);
79 }
80
81 const sourceMapsCombinator = new SourceMapsCombinator();
82 sourceMap = sourceMapsCombinator.convert(sourceMap);
83
84 if (sourceMap.sources) {
85 sourceMap.sources = sourceMap.sources.map(sourcePath =>
86 IS_REMOTE.test(sourcePath)
87 ? sourcePath
88 : this.updateSourceMapPath(
89 sourcePath,
90 sourcesRootPath,
91 packagerRemoteRoot,
92 packagerLocalRoot,
93 ),
94 );
95 }
96
97 delete sourceMap.sourcesContent;
98 sourceMap.sourceRoot = "";
99 sourceMap.file = scriptPath;
100 return JSON.stringify(sourceMap);
101 } catch (exception) {
102 return sourceMapBody;
103 }
104 }
105
106 public appendSourceMapPaths(scriptBody: string, sourceMappingUrl: string): string {
107 scriptBody += `//# sourceMappingURL=${sourceMappingUrl}`;
108 return scriptBody;
109 }
110
111 /**
112 * Updates source map URLs in the script body.
113 */
114 public updateScriptPaths(scriptBody: string, sourceMappingUrl: IStrictUrl): string {
115 const sourceMapMatch = this.searchSourceMapURL(scriptBody);
116 if (sourceMapMatch) {
117 // Update the body with the new location of the source map on storage.
118 return scriptBody.replace(
119 sourceMapMatch[0],
120 `//# sourceMappingURL=${path.basename(sourceMappingUrl.pathname)}`,
121 );
122 }
123 return scriptBody;
124 }
125
126 /**
127 * Removes sourceURL from the script body since RN 0.61 because it breaks sourcemaps.
128 * Example: //# sourceURL=http://localhost:8081/index.bundle?platform=android&dev=true&minify=false -> ""
129 */
130 public removeSourceURL(scriptBody: string): string {
131 return scriptBody.replace(SourceMapUtil.SourceURLRegex, "");
132 }
133
134 /**
135 * Parses the body of a script searching for a source map URL.
136 * It supports the following source map url styles:
137 *
138 * `//# sourceMappingURL=path/to/source/map`
139 *
140 * `//@ sourceMappingURL=path/to/source/map`
141 *
142 * Returns the last match if found, null otherwise.
143 */
144 public getSourceMapRelativeUrl(body: string): string | null {
145 const sourceMapMatch = this.searchSourceMapURL(body);
146 // If match is null, the body doesn't contain the source map
147 if (sourceMapMatch) {
148 // On React Native macOS 0.62 and RN Windows 0.65 sourceMappingUrl looks like:
149 // # sourceMappingURL=//localhost:8081/index.map?platform=macos&dev=true&minify=false
150 // Add 'http:' protocol to avoid errors in further processing
151 const el = sourceMapMatch[2];
152 const macOsOrWin =
153 (el.includes("platform=macos") || el.includes("platform=window")) &&
154 el.startsWith("//") &&
155 !el.includes("http:");
156
157 return macOsOrWin ? `http:${el}` : el;
158 }
159 return null;
160 }
161
162 private searchSourceMapURL(str: string): RegExpMatchArray | null {
163 const matchesList = str
164 .match(SourceMapUtil.SourceMapURLGlobalRegex)
165 ?.filter(s => !s.includes("\\n"));
166 if (matchesList && matchesList.length) {
167 return matchesList[matchesList.length - 1].match(SourceMapUtil.SourceMapURLRegex);
168 }
169
170 return null;
171 }
172
173 /**
174 * Given an absolute source path, this method does two things:
175 * 1. It changes the path from absolute to be relative to the sourcesRootPath parameter.
176 * 2. It changes the path separators to Unix style.
177 */
178 private updateSourceMapPath(
179 sourcePath: string,
180 sourcesRootPath: string,
181 packagerRemoteRoot?: string,
182 packagerLocalRoot?: string,
183 ) {
184 if (packagerRemoteRoot && packagerLocalRoot) {
185 packagerRemoteRoot = this.makeUnixStylePath(packagerRemoteRoot);
186 packagerLocalRoot = this.makeUnixStylePath(packagerLocalRoot);
187 sourcePath = sourcePath.replace(packagerRemoteRoot, packagerLocalRoot);
188 }
189 const relativeSourcePath = path.relative(sourcesRootPath, sourcePath);
190 return this.makeUnixStylePath(relativeSourcePath);
191 }
192
193 /**
194 * Visual Studio Code source mapping requires Unix style path separators.
195 * This method replaces all back-slash characters in a given string with forward-slash ones.
196 */
197 private makeUnixStylePath(p: string): string {
198 const pathArgs = p.split(path.sep);
199 return path.posix.join.apply(null, pathArgs);
200 }
201
202 private static createEmptySourceMap(): ISourceMap {
203 return {
204 version: 3,
205 sources: [],
206 names: [],
207 mappings: "",
208 file: "",
209 };
210 }
211
212 private static flattenIndexedSourceMap(sourceMap: ISourceMap): ISourceMap {
213 // eslint-disable-next-line @typescript-eslint/no-var-requires
214 const flattenSourceMap = require("flatten-source-map");
215 const meaningfulSections = (sourceMap.sections ?? []).filter(
216 section => section.map && (section.map.sources?.length || section.map.mappings),
217 );
218
219 if (meaningfulSections.length === 1 && meaningfulSections[0].map) {
220 return meaningfulSections[0].map;
221 }
222
223 try {
224 return flattenSourceMap(sourceMap);
225 } catch (error) {
226 if (!meaningfulSections.length) {
227 throw error;
228 }
229
230 const firstOffset = meaningfulSections[0].offset;
231 const rebasedSections = meaningfulSections.map(section => ({
232 ...section,
233 offset: {
234 line: Math.max(0, section.offset.line - firstOffset.line),
235 column:
236 section.offset.line === firstOffset.line
237 ? Math.max(0, section.offset.column - firstOffset.column)
238 : section.offset.column,
239 },
240 }));
241
242 return flattenSourceMap({
243 ...sourceMap,
244 sections: rebasedSections,
245 });
246 }
247 }
248}
249