microsoft/vscode-react-native

Public

mirrored from https://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
indexed-sourcemap-null-section-issue

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/sourceMap.ts

248lines · modeblame

9f036952Nisheet Jain10 years ago1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for details.
3
ce5e88eeYuri Skorokhodov5 years ago4import * as url from "url";
5import * as path from "path";
70bb7c83Vladimir Kotikov9 years ago6import { RawSourceMap } from "source-map";
09f6024fHeniker4 years ago7import { SourceMapsCombinator } from "./sourceMapsCombinator";
876df2a0dlebu10 years ago8
f68a3466EmmaYuan10152 months ago9const IS_REMOTE = /^[A-Za-z]{2,}:\/\//; // Detection remote sources or specific protocols (like "webpack:///")
66b52ec9Artem Egorov8 years ago10
70bb7c83Vladimir Kotikov9 years ago11interface ISourceMap extends RawSourceMap {
f16656e9frogcjn9 years ago12sections?: ISourceMapSection[];
13}
14interface ISourceMapSection {
57fc50d2EmmaYuan10152 months ago15map: ISourceMap | null;
34472878RedMickey5 years ago16offset: { column: number; line: number };
876df2a0dlebu10 years ago17}
18
5c8365a6Artem Egorov8 years ago19export interface IStrictUrl extends url.Url {
20pathname: string;
21href: string;
22}
23
876df2a0dlebu10 years ago24export class SourceMapUtil {
09f6024fHeniker4 years ago25private static SourceMapURLGlobalRegex: RegExp =
716c1b85RedMickey4 years ago26/\/\/(#|@) sourceMappingURL=((?!data:)[^ ]+?)\s*$/gm;
27private static SourceMapURLRegex: RegExp = /\/\/(#|@) sourceMappingURL=((?!data:)[^ ]+?)\s*$/m;
32558f9eYuri Skorokhodov6 years ago28private static SourceURLRegex: RegExp = /^\/\/[#@] ?sourceURL=(.+)$/m;
4e7a6f0edlebu10 years ago29
876df2a0dlebu10 years ago30/**
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*/
5c8365a6Artem Egorov8 years ago34public getSourceMapURL(scriptUrl: url.Url, scriptBody: string): IStrictUrl | null {
35let result: IStrictUrl | null = null;
876df2a0dlebu10 years ago36
37// scriptUrl = "http://localhost:8081/index.ios.bundle?platform=ios&dev=true"
09f6024fHeniker4 years ago38const sourceMappingRelativeUrl = this.getSourceMapRelativeUrl(scriptBody); // sourceMappingRelativeUrl = "/index.ios.map?platform=ios&dev=true"
876df2a0dlebu10 years ago39if (sourceMappingRelativeUrl) {
09f6024fHeniker4 years ago40const sourceMappingUrl = url.parse(sourceMappingRelativeUrl);
876df2a0dlebu10 years ago41sourceMappingUrl.protocol = scriptUrl.protocol;
42sourceMappingUrl.host = scriptUrl.host;
43// parse() repopulates all the properties of the URL
5c8365a6Artem Egorov8 years ago44result = <IStrictUrl>url.parse(url.format(sourceMappingUrl));
876df2a0dlebu10 years ago45}
46
47return 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*/
34472878RedMickey5 years ago61public updateSourceMapFile(
62sourceMapBody: string,
63scriptPath: string,
64sourcesRootPath: string,
65packagerRemoteRoot?: string,
66packagerLocalRoot?: string,
67): string {
876df2a0dlebu10 years ago68try {
69let sourceMap = <ISourceMap>JSON.parse(sourceMapBody);
f16656e9frogcjn9 years ago70
71if (sourceMap.sections) {
57fc50d2EmmaYuan10152 months ago72// Preserve indexed sourcemap offsets even when Metro emits a null section map.
73sourceMap.sections = sourceMap.sections.map(section => ({
74...section,
75map: section.map ?? SourceMapUtil.createEmptySourceMap(),
76}));
f16656e9frogcjn9 years ago77
b5422694EmmaYuan10151 months ago78sourceMap = SourceMapUtil.flattenIndexedSourceMap(sourceMap);
f16656e9frogcjn9 years ago79}
80
09f6024fHeniker4 years ago81const sourceMapsCombinator = new SourceMapsCombinator();
48644043Dmitry Zinovyev9 years ago82sourceMap = sourceMapsCombinator.convert(sourceMap);
83
f16656e9frogcjn9 years ago84if (sourceMap.sources) {
09f6024fHeniker4 years ago85sourceMap.sources = sourceMap.sources.map(sourcePath =>
86IS_REMOTE.test(sourcePath)
34472878RedMickey5 years ago87? sourcePath
88: this.updateSourceMapPath(
89sourcePath,
90sourcesRootPath,
91packagerRemoteRoot,
92packagerLocalRoot,
09f6024fHeniker4 years ago93),
94);
f16656e9frogcjn9 years ago95}
876df2a0dlebu10 years ago96
97delete sourceMap.sourcesContent;
98sourceMap.sourceRoot = "";
99sourceMap.file = scriptPath;
100return JSON.stringify(sourceMap);
101} catch (exception) {
102return sourceMapBody;
103}
104}
105
34472878RedMickey5 years ago106public appendSourceMapPaths(scriptBody: string, sourceMappingUrl: string): string {
979d7bfemax-mironov8 years ago107scriptBody += `//# sourceMappingURL=${sourceMappingUrl}`;
108return scriptBody;
109}
110
3736c251dlebu10 years ago111/**
112* Updates source map URLs in the script body.
113*/
34472878RedMickey5 years ago114public updateScriptPaths(scriptBody: string, sourceMappingUrl: IStrictUrl): string {
716c1b85RedMickey4 years ago115const sourceMapMatch = this.searchSourceMapURL(scriptBody);
116if (sourceMapMatch) {
117// Update the body with the new location of the source map on storage.
118return scriptBody.replace(
119sourceMapMatch[0],
120`//# sourceMappingURL=${path.basename(sourceMappingUrl.pathname)}`,
121);
122}
123return scriptBody;
3736c251dlebu10 years ago124}
125
2f5c780bYuri Skorokhodov6 years ago126/**
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*/
34472878RedMickey5 years ago130public removeSourceURL(scriptBody: string): string {
2f5c780bYuri Skorokhodov6 years ago131return scriptBody.replace(SourceMapUtil.SourceURLRegex, "");
132}
133
4cf8fdf4Yuri Skorokhodov6 years ago134/**
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*/
34472878RedMickey5 years ago144public getSourceMapRelativeUrl(body: string): string | null {
716c1b85RedMickey4 years ago145const sourceMapMatch = this.searchSourceMapURL(body);
4cf8fdf4Yuri Skorokhodov6 years ago146// If match is null, the body doesn't contain the source map
716c1b85RedMickey4 years ago147if (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
151const el = sourceMapMatch[2];
152const macOsOrWin =
153(el.includes("platform=macos") || el.includes("platform=window")) &&
154el.startsWith("//") &&
155!el.includes("http:");
156
157return macOsOrWin ? `http:${el}` : el;
4cf8fdf4Yuri Skorokhodov6 years ago158}
716c1b85RedMickey4 years ago159return null;
160}
09f6024fHeniker4 years ago161
716c1b85RedMickey4 years ago162private searchSourceMapURL(str: string): RegExpMatchArray | null {
163const matchesList = str
164.match(SourceMapUtil.SourceMapURLGlobalRegex)
165?.filter(s => !s.includes("\\n"));
166if (matchesList && matchesList.length) {
167return matchesList[matchesList.length - 1].match(SourceMapUtil.SourceMapURLRegex);
168}
09f6024fHeniker4 years ago169
716c1b85RedMickey4 years ago170return null;
4cf8fdf4Yuri Skorokhodov6 years ago171}
172
876df2a0dlebu10 years ago173/**
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*/
34472878RedMickey5 years ago178private updateSourceMapPath(
179sourcePath: string,
180sourcesRootPath: string,
181packagerRemoteRoot?: string,
182packagerLocalRoot?: string,
183) {
6eeec3c0Serge Svekolnikov8 years ago184if (packagerRemoteRoot && packagerLocalRoot) {
185packagerRemoteRoot = this.makeUnixStylePath(packagerRemoteRoot);
186packagerLocalRoot = this.makeUnixStylePath(packagerLocalRoot);
187sourcePath = sourcePath.replace(packagerRemoteRoot, packagerLocalRoot);
188}
09f6024fHeniker4 years ago189const relativeSourcePath = path.relative(sourcesRootPath, sourcePath);
876df2a0dlebu10 years ago190return 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*/
197private makeUnixStylePath(p: string): string {
09f6024fHeniker4 years ago198const pathArgs = p.split(path.sep);
4e7a6f0edlebu10 years ago199return path.posix.join.apply(null, pathArgs);
876df2a0dlebu10 years ago200}
57fc50d2EmmaYuan10152 months ago201
202private static createEmptySourceMap(): ISourceMap {
203return {
204version: 3,
205sources: [],
206names: [],
207mappings: "",
208file: "",
209};
210}
b5422694EmmaYuan10151 months ago211
212private static flattenIndexedSourceMap(sourceMap: ISourceMap): ISourceMap {
213// eslint-disable-next-line @typescript-eslint/no-var-requires
214const flattenSourceMap = require("flatten-source-map");
215const meaningfulSections = (sourceMap.sections ?? []).filter(
216section => section.map && (section.map.sources?.length || section.map.mappings),
217);
218
219if (meaningfulSections.length === 1 && meaningfulSections[0].map) {
220return meaningfulSections[0].map;
221}
222
223try {
224return flattenSourceMap(sourceMap);
225} catch (error) {
226if (!meaningfulSections.length) {
227throw error;
228}
229
230const firstOffset = meaningfulSections[0].offset;
231const rebasedSections = meaningfulSections.map(section => ({
232...section,
233offset: {
234line: Math.max(0, section.offset.line - firstOffset.line),
235column:
236section.offset.line === firstOffset.line
237? Math.max(0, section.offset.column - firstOffset.column)
238: section.offset.column,
239},
240}));
241
242return flattenSourceMap({
243...sourceMap,
244sections: rebasedSections,
245});
246}
247}
f16656e9frogcjn9 years ago248}