-
Notifications
You must be signed in to change notification settings - Fork 298
/
Copy pathimplementation.ts
386 lines (328 loc) · 12.9 KB
/
implementation.ts
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
import { inject, injectable } from 'inversify';
import micromatch from 'micromatch';
import { Cdp } from '../../cdp/api';
import { ICdpApi } from '../../cdp/connection';
import { MapUsingProjection } from '../../common/datastructure/mapUsingProjection';
import { EventEmitter } from '../../common/events';
import { ILogger, LogTag } from '../../common/logging';
import { node15InternalsPrefix } from '../../common/node15Internal';
import { memoizeLast, trailingEdgeThrottle, truthy } from '../../common/objUtils';
import * as pathUtils from '../../common/pathUtils';
import { getDeferred, IDeferred } from '../../common/promiseUtil';
import { escapeRegexSpecialChars } from '../../common/stringUtils';
import * as urlUtils from '../../common/urlUtils';
import { AnyLaunchConfiguration } from '../../configuration';
import Dap from '../../dap/api';
import { ITarget } from '../../targets/targets';
import {
ISourceWithMap,
isSourceWithMap,
Source,
SourceContainer,
SourceFromMap,
} from '../sources';
import { getSourceSuffix } from '../templates';
import { simpleGlobsToRe } from './simpleGlobToRe';
interface ISharedSkipToggleEvent {
rootTargetId: string;
targetId: string;
params: Dap.ToggleSkipFileStatusParams;
}
function preprocessNodeInternals(userSkipPatterns: ReadonlyArray<string>): string[] | undefined {
const nodeInternalRegex = /^<node_internals>[\/\\](.*)$/;
const nodeInternalPatterns = userSkipPatterns
.map(userPattern => {
userPattern = userPattern.trim();
const nodeInternalPattern = nodeInternalRegex.exec(userPattern);
return nodeInternalPattern ? nodeInternalPattern[1] : null;
})
.filter(truthy);
return nodeInternalPatterns.length > 0 ? nodeInternalPatterns : undefined;
}
function preprocessAuthoredGlobs(userSkipPatterns: ReadonlyArray<string>): string[] {
const authoredGlobs = userSkipPatterns
.filter(pattern => !pattern.includes('<node_internals>'))
.map(pattern =>
urlUtils.isAbsolute(pattern)
? urlUtils.absolutePathToFileUrl(pattern)
: pathUtils.forceForwardSlashes(pattern),
)
.map(urlUtils.lowerCaseInsensitivePath);
return authoredGlobs;
}
@injectable()
export class ScriptSkipper {
private static sharedSkipsEmitter = new EventEmitter<ISharedSkipToggleEvent>();
/**
* Globs for non-<node_internals> skipfiles. This might be changed over time
* if the user uses the "toggle skipping this file" command.
*/
private _authoredGlobs: readonly string[];
/** Memoized computer for non-<node_internals> skipfiles */
private _regexForAuthored = memoizeLast(simpleGlobsToRe);
/**
* Globs for node internals. These are treated specially, at least until we
* drop support for Node <=14, since in Node 15 the internals all have a
* `node:` prefix that we can match against.
*/
private _nodeInternalsGlobs: string[] | undefined;
/** Set of all internal modules, read from the runtime */
private _allNodeInternals?: IDeferred<ReadonlySet<string>>;
/**
* Mapping of URLs from sourcemaps to a boolean indicating whether they're
* skipped. These are kept and used in addition to the authoredGlobs, since
* if a compiled file is skipped, we want to skip the sourcemapped sources
* as well.
*/
private _isUrlFromSourceMapSkipped: Map<string, boolean>;
/**
* A set of script ID that have one or more skipped ranges in them. Mostly
* used to avoid unnecessarily sending skip data for new scripts.
*/
private _scriptsWithSkipping = new Set<string>();
private _sourceContainer!: SourceContainer;
private _updateSkippedDebounce: () => void;
private _targetId: string;
private _rootTargetId: string;
constructor(
@inject(AnyLaunchConfiguration) { skipFiles }: AnyLaunchConfiguration,
@inject(ILogger) private readonly logger: ILogger,
@inject(ICdpApi) private readonly cdp: Cdp.Api,
@inject(ITarget) target: ITarget,
) {
this._targetId = target.id();
this._rootTargetId = getRootTarget(target).id();
this._isUrlFromSourceMapSkipped = new MapUsingProjection<string, boolean>(key =>
this._normalizeUrl(key),
);
this._authoredGlobs = preprocessAuthoredGlobs(skipFiles);
this._nodeInternalsGlobs = preprocessNodeInternals(skipFiles);
this._initNodeInternals(target); // Purposely don't wait, no need to slow things down
this._updateSkippedDebounce = trailingEdgeThrottle(500, () =>
this._updateGeneratedSkippedSources(),
);
if (skipFiles.length) {
this._updateGeneratedSkippedSources();
}
ScriptSkipper.sharedSkipsEmitter.event(e => {
if (e.rootTargetId === this._rootTargetId && e.targetId !== this._targetId) {
this._toggleSkippingFile(e.params);
}
});
}
public setSourceContainer(sourceContainer: SourceContainer): void {
this._sourceContainer = sourceContainer;
}
private _testSkipNodeInternal(testString: string): boolean {
if (!this._nodeInternalsGlobs) {
return false;
}
if (testString.startsWith(node15InternalsPrefix)) {
testString = testString.slice(node15InternalsPrefix.length);
}
return micromatch([testString], this._nodeInternalsGlobs).length > 0;
}
private _testSkipAuthored(testString: string): boolean {
return this._regexForAuthored(this._authoredGlobs).some(re => re.test(testString));
}
private _isNodeInternal(url: string, nodeInternals: ReadonlySet<string> | undefined): boolean {
if (url.startsWith(node15InternalsPrefix)) {
return true;
}
return nodeInternals?.has(url) || /^internal\/.+\.js$/.test(url);
}
private async _updateGeneratedSkippedSources(): Promise<void> {
const patterns: string[] = this._regexForAuthored(this._authoredGlobs).map(re => re.source);
const nodeInternals = this._allNodeInternals?.settledValue;
if (nodeInternals) {
patterns.push(`^(${node15InternalsPrefix})?internal\\/`);
for (const internal of nodeInternals) {
if (this._testSkipNodeInternal(internal)) {
patterns.push(`^(${node15InternalsPrefix})?${escapeRegexSpecialChars(internal)}$`);
}
}
}
await this.cdp.Debugger.setBlackboxPatterns({ patterns });
}
private _normalizeUrl(url: string): string {
return pathUtils.forceForwardSlashes(url.toLowerCase());
}
/**
* Gets whether the script at the URL is skipped.
*/
public isScriptSkipped(url: string): boolean {
if (this._isNodeInternal(url, this._allNodeInternals?.settledValue)) {
return this._testSkipNodeInternal(url);
}
url = this._normalizeUrl(url);
if (this._isUrlFromSourceMapSkipped.get(url) === true) {
return true;
}
return this._testSkipAuthored(this._normalizeUrl(url));
}
private async _updateSourceWithSkippedSourceMappedSources(
source: ISourceWithMap,
scriptIds: Cdp.Runtime.ScriptId[],
): Promise<void> {
// Order "should" be correct
const parentIsSkipped = this.isScriptSkipped(source.url);
const skipRanges: Cdp.Debugger.ScriptPosition[] = [];
let inSkipRange = parentIsSkipped;
Array.from(source.sourceMap.sourceByUrl.values()).forEach(authoredSource => {
let isSkippedSource = this.isScriptSkipped(authoredSource.url);
if (typeof isSkippedSource === 'undefined') {
// If not toggled or specified in launch config, inherit the parent's status
isSkippedSource = parentIsSkipped;
}
if (isSkippedSource !== inSkipRange) {
const locations = this._sourceContainer.currentSiblingUiLocations(
{ source: authoredSource, lineNumber: 1, columnNumber: 1 },
source,
);
if (locations[0]) {
skipRanges.push({
lineNumber: locations[0].lineNumber - 1,
columnNumber: locations[0].columnNumber - 1,
});
inSkipRange = !inSkipRange;
} else {
this.logger.error(
LogTag.Internal,
'Could not map script beginning for ' + authoredSource.sourceReference,
);
}
}
});
let targets = scriptIds;
if (!skipRanges.length) {
targets = targets.filter(t => this._scriptsWithSkipping.has(t));
targets.forEach(t => this._scriptsWithSkipping.delete(t));
}
await Promise.all(
targets.map(scriptId =>
this.cdp.Debugger.setBlackboxedRanges({ scriptId, positions: skipRanges }),
),
);
}
public initializeSkippingValueForSource(source: Source) {
this._initializeSkippingValueForSource(source);
}
private _initializeSkippingValueForSource(source: Source, scriptIds = source.scriptIds()) {
const url = source.url;
let skipped = this.isScriptSkipped(url);
// Check if this source was mapped to a URL we should have skipped, but didn't (oops)
// This can happen if the user skips absolute paths which are served from a different
// place in the server.
if (
!skipped &&
source.absolutePath &&
urlUtils.isAbsolute(source.absolutePath) &&
this._testSkipAuthored(urlUtils.absolutePathToFileUrl(source.absolutePath))
) {
this.setIsUrlBlackboxSkipped(url, true);
skipped = true;
this._updateSkippedDebounce();
}
if (isSourceWithMap(source)) {
if (skipped) {
// if compiled and skipped, also skip authored sources
for (const authoredSource of source.sourceMap.sourceByUrl.values()) {
this._isUrlFromSourceMapSkipped.set(authoredSource.url, true);
}
}
for (const nestedSource of source.sourceMap.sourceByUrl.values()) {
this._initializeSkippingValueForSource(nestedSource, scriptIds);
}
this._updateSourceWithSkippedSourceMappedSources(source, scriptIds);
}
}
private async _initNodeInternals(target: ITarget): Promise<void> {
if (target.type() !== 'node' || !this._nodeInternalsGlobs || this._allNodeInternals) {
return;
}
const deferred = (this._allNodeInternals = getDeferred());
const evalResult = await this.cdp.Runtime.evaluate({
expression: "require('module').builtinModules" + getSourceSuffix(),
returnByValue: true,
includeCommandLineAPI: true,
});
if (evalResult && !evalResult.exceptionDetails) {
deferred.resolve(new Set((evalResult.result.value as string[]).map(name => name + '.js')));
} else {
deferred.resolve(new Set());
}
await this._updateGeneratedSkippedSources(); // updates skips now that we loaded internals
}
private async _toggleSkippingFile(
params: Dap.ToggleSkipFileStatusParams,
): Promise<Dap.ToggleSkipFileStatusResult> {
let path: string | undefined = undefined;
if (params.resource) {
if (urlUtils.isAbsolute(params.resource)) {
path = params.resource;
}
}
const sourceParams: Dap.Source = { path: path, sourceReference: params.sourceReference };
const source = this._sourceContainer.source(sourceParams);
if (!source) {
return {};
}
const newSkipValue = !this.isScriptSkipped(source.url);
if (source instanceof SourceFromMap) {
this._isUrlFromSourceMapSkipped.set(source.url, newSkipValue);
// Changed the skip value for an authored source, update it for all its compiled sources
const compiledSources = Array.from(source.compiledToSourceUrl.keys());
await Promise.all(
compiledSources.map(compiledSource =>
this._updateSourceWithSkippedSourceMappedSources(
compiledSource,
compiledSource.scriptIds(),
),
),
);
} else {
if (isSourceWithMap(source)) {
// if compiled, get authored sources
for (const authoredSource of source.sourceMap.sourceByUrl.values()) {
this._isUrlFromSourceMapSkipped.set(authoredSource.url, newSkipValue);
}
}
this.setIsUrlBlackboxSkipped(source.url, newSkipValue);
await this._updateGeneratedSkippedSources();
}
return {};
}
/** Sets whether the URL is explicitly skipped in the blackbox patterns */
private setIsUrlBlackboxSkipped(url: string, skipped: boolean) {
const positive = url;
const negative = `!${positive}`;
const globs = this._authoredGlobs.filter(g => g !== positive && g !== negative);
if (this._regexForAuthored(globs).some(r => r.test(url)) !== skipped) {
globs.push(skipped ? positive : negative);
this._regexForAuthored.clear();
}
this._authoredGlobs = globs;
}
public async toggleSkippingFile(
params: Dap.ToggleSkipFileStatusParams,
): Promise<Dap.ToggleSkipFileStatusResult> {
const result = await this._toggleSkippingFile(params);
ScriptSkipper.sharedSkipsEmitter.fire({
params,
rootTargetId: this._rootTargetId,
targetId: this._targetId,
});
return result;
}
}
function getRootTarget(target: ITarget): ITarget {
const parent = target.parent();
if (parent) {
return getRootTarget(parent);
} else {
return target;
}
}