-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathutilities.ts
501 lines (433 loc) · 16.3 KB
/
utilities.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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
// TODO: Some functions can be moved to common.
import * as http from 'http';
import * as os from 'os';
import * as fs from 'fs';
import * as url from 'url';
import * as path from 'path';
import {ILaunchRequestArgs, IAttachRequestArgs} from './WebKitAdapterInterfaces';
const DEFAULT_CHROME_PATH = {
OSX: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
WIN: 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
WINx86: 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
LINUX: '/usr/bin/google-chrome'
};
export function getBrowserPath(): string {
const platform = getPlatform();
if (platform === Platform.OSX) {
return existsSync(DEFAULT_CHROME_PATH.OSX) ? DEFAULT_CHROME_PATH.OSX : null;
} else if (platform === Platform.Windows) {
if (existsSync(DEFAULT_CHROME_PATH.WINx86)) {
return DEFAULT_CHROME_PATH.WINx86;
} else if (existsSync(DEFAULT_CHROME_PATH.WIN)) {
return DEFAULT_CHROME_PATH.WIN;
} else {
return null;
}
} else {
return existsSync(DEFAULT_CHROME_PATH.LINUX) ? DEFAULT_CHROME_PATH.LINUX : null;
}
}
export const enum Platform {
Windows, OSX, Linux
}
export function getPlatform(): Platform {
const platform = os.platform();
return platform === 'darwin' ? Platform.OSX :
platform === 'win32' ? Platform.Windows :
Platform.Linux;
}
/**
* Node's fs.existsSync is deprecated, implement it in terms of statSync
*/
export function existsSync(path: string): boolean {
try {
fs.statSync(path);
return true;
} catch (e) {
// doesn't exist
return false;
}
}
export class DebounceHelper {
private waitToken: NodeJS.Timer;
constructor(private timeoutMs: number) { }
/**
* If not waiting already, call fn after the timeout
*/
public wait(fn: () => any): void {
if (!this.waitToken) {
this.waitToken = setTimeout(() => {
this.waitToken = null;
fn();
},
this.timeoutMs);
}
}
/**
* If waiting for something, cancel it and call fn immediately
*/
public doAndCancel(fn: () => any): void {
if (this.waitToken) {
clearTimeout(this.waitToken);
this.waitToken = null;
}
fn();
}
}
/**
* Returns a reversed version of arr. Doesn't modify the input.
*/
export function reversedArr(arr: any[]): any[] {
return arr.reduce((reversed: any[], x: any) => {
reversed.unshift(x);
return reversed;
}, []);
}
export function promiseTimeout(p?: Promise<any>, timeoutMs: number = 1000, timeoutMsg?: string): Promise<any> {
if (timeoutMsg === undefined) {
timeoutMsg = `Promise timed out after ${timeoutMs}ms`;
}
return new Promise((resolve, reject) => {
if (p) {
p.then(resolve, reject);
}
setTimeout(() => {
if (p) {
reject(timeoutMsg);
} else {
resolve();
}
}, timeoutMs);
});
}
export function retryAsync(fn: () => Promise<any>, timeoutMs: number): Promise<any> {
const startTime = Date.now();
function tryUntilTimeout(): Promise<any> {
return fn().catch(
e => {
if (Date.now() - startTime < timeoutMs) {
return tryUntilTimeout();
} else {
return errP(e);
}
});
}
return tryUntilTimeout();
}
/**
* Holds a singleton to manage access to console.log.
* Logging is only allowed when running in server mode, because otherwise it goes through the same channel that Code uses to
* communicate with the adapter, which can cause communication issues.
*/
export class Logger {
private static _logger: Logger;
private _isServer: boolean;
private _diagnosticLogCallback: (msg: string) => void;
private _diagnosticLoggingEnabled: boolean;
public static log(msg: string, forceDiagnosticLogging = false): void {
if (this._logger) this._logger._log(msg, forceDiagnosticLogging);
}
public static init(isServer: boolean, logCallback: (msg: string) => void): void {
if (!this._logger) {
this._logger = new Logger(isServer);
this._logger._diagnosticLogCallback = logCallback;
if (isServer) {
Logger.logVersionInfo();
}
}
}
public static enableDiagnosticLogging(): void {
if (this._logger) {
this._logger._diagnosticLoggingEnabled = true;
if (!this._logger._isServer) {
Logger.logVersionInfo();
}
}
}
public static logVersionInfo(): void {
Logger.log(`OS: ${os.platform() } ${os.arch() }`);
Logger.log('Node version: ' + process.version);
Logger.log('Adapter version: ' + require('../../package.json').version);
}
constructor(isServer: boolean) {
this._isServer = isServer;
}
private _log(msg: string, forceDiagnosticLogging: boolean): void {
if (this._isServer || this._diagnosticLoggingEnabled || forceDiagnosticLogging) {
this._sendLog(msg);
}
}
private _sendLog(msg: string): void {
if (this._isServer) {
console.log(msg);
} else if (this._diagnosticLogCallback) {
this._diagnosticLogCallback(msg);
}
}
}
function tryFindSourcePathInNSProject(nsProjectPath: string, additionalFileExtension: string, resorcePath: string) : string {
let guesses = [];
const pathParts = resorcePath.split(path.sep);
let appIndex = pathParts.indexOf("app");
let isTnsModule = appIndex >= 0 && pathParts.length > appIndex + 1 && pathParts[appIndex + 1] === "tns_modules";
//let isTnsModule: boolean = (pathParts.length >= 3 && pathParts[0] == '' && pathParts[1] == 'app' && pathParts[2] == 'tns_modules');
if (isTnsModule) {
// the file is part of a module, so we search it in '{ns-app}/node_modules/tns-core-modules/' and '{ns-app}/node_modules/'
let nsNodeModulesPath: string = path.join(nsProjectPath, 'node_modules');
let tnsCoreNodeModulesPath: string = path.join(nsNodeModulesPath, 'tns-core-modules');
let modulePath: string = path.join.apply(path, pathParts.slice(appIndex + 2));
guesses.push(path.join(tnsCoreNodeModulesPath, modulePath));
guesses.push(path.join(nsNodeModulesPath, modulePath));
}
else {
guesses.push(path.join(nsProjectPath, resorcePath));
}
for (var guessPath of guesses) {
if (existsSync(guessPath)) {
return canonicalizeUrl(guessPath);
}
let extension: string = path.extname(guessPath);
let platformSpecificPath: string = guessPath.substr(0, guessPath.length - extension.length) + '.' + additionalFileExtension + extension;
if (existsSync(platformSpecificPath)) {
return canonicalizeUrl(platformSpecificPath);
}
}
return null;
}
/**
* Maps a url from webkit to an absolute local path.
* If not given an absolute path (with file: prefix), searches the current working directory for a matching file.
* http://localhost/scripts/code.js => d:/app/scripts/code.js
* file:///d:/scripts/code.js => d:/scripts/code.js
*/
export function webkitUrlToClientPath(webRoot: string, additionalFileExtension: string, aUrl: string): string {
if (!aUrl) {
return '';
}
// If we don't have the client workingDirectory for some reason, don't try to map the url to a client path
if (!webRoot) {
return '';
}
aUrl = decodeURI(aUrl);
// Search the filesystem under the webRoot for the file that best matches the given url
let pathName = url.parse(canonicalizeUrl(aUrl)).pathname;
if (!pathName || pathName === '/') {
return '';
}
// Dealing with the path portion of either a url or an absolute path to remote file.
// Need to force path.sep separator
pathName = pathName.replace(/\//g, path.sep);
let nsProjectFile = tryFindSourcePathInNSProject(webRoot, additionalFileExtension, pathName);
if(nsProjectFile) {
return nsProjectFile;
}
let pathParts = pathName.split(path.sep);
while (pathParts.length > 0) {
const clientPath = path.join(webRoot, pathParts.join(path.sep));
if (existsSync(clientPath)) {
return canonicalizeUrl(clientPath);
}
pathParts.shift();
}
//check for {N} android internal files
pathParts = pathName.split(path.sep);
while (pathParts.length > 0) {
const clientPath = path.join(webRoot, "platforms/android/src/main/assets", pathParts.join(path.sep));
if (existsSync(clientPath)) {
return canonicalizeUrl(clientPath);
}
pathParts.shift();
}
return '';
}
/**
* Infers the device root of a given path.
* The device root is the parent directory of all {N} source files
* This implementation assumes that all files are all under one common root on the device
* Returns all the device parent directories of a source file until the file is found on the client by client path
*/
export function inferDeviceRoot(projectRoot: string, additionalFileExtension: string, aUrl: string): string {
if (!aUrl) {
return null;
}
// If we don't have the projectRoot for some reason, don't try to map the url to a client path
if (!projectRoot) {
return null;
}
aUrl = decodeURI(aUrl);
// Search the filesystem under the webRoot for the file that best matches the given url
let pathName = url.parse(canonicalizeUrl(aUrl)).pathname;
if (!pathName || pathName === '/') {
return null;
}
// Dealing with the path portion of either a url or an absolute path to remote file.
// Need to force path.sep separator
pathName = pathName.replace(/\//g, path.sep);
let shiftedParts = [];
let pathParts = pathName.split(path.sep);
while (pathParts.length > 0) {
const clientPath = path.join(projectRoot, pathParts.join(path.sep));
if (existsSync(clientPath)) {
//return canonicalizeUrl(clientPath);
return shiftedParts.join(path.sep).replace(/\\/g, "/");
}
let shifted = pathParts.shift();
shiftedParts.push(shifted);
}
//check for {N} android internal files
shiftedParts = [];
pathParts = pathName.split(path.sep);
while (pathParts.length > 0) {
const clientPath = path.join(projectRoot, "platforms/android/src/main/assets", pathParts.join(path.sep));
if (existsSync(clientPath)) {
//return canonicalizeUrl(clientPath);
return shiftedParts.join(path.sep).replace(/\\/g, "/");
}
let shifted = pathParts.shift();
shiftedParts.push(shifted);
}
return null;
}
/**
* Modify a url either from the client or the webkit target to a common format for comparing.
* The client can handle urls in this format too.
* file:///D:\\scripts\\code.js => d:/scripts/code.js
* file:///Users/me/project/code.js => /Users/me/project/code.js
* c:\\scripts\\code.js => c:/scripts/code.js
* http://site.com/scripts/code.js => (no change)
* http://site.com/ => http://site.com
*/
export function canonicalizeUrl(aUrl: string): string {
aUrl = aUrl.replace('file:///', '');
aUrl = stripTrailingSlash(aUrl);
aUrl = fixDriveLetterAndSlashes(aUrl);
if (aUrl[0] !== '/' && aUrl.indexOf(':') < 0 && getPlatform() === Platform.OSX) {
// Ensure osx path starts with /, it can be removed when file:/// was stripped.
// Don't add if the url still has a protocol
aUrl = '/' + aUrl;
}
return aUrl;
}
/**
* Ensure lower case drive letter and \ on Windows
*/
export function fixDriveLetterAndSlashes(aPath: string): string {
if (getPlatform() === Platform.Windows) {
if (aPath.match(/file:\/\/\/[A-Za-z]:/)) {
const prefixLen = 'file:///'.length;
aPath =
'file:///' +
aPath[prefixLen].toLowerCase() +
aPath.substr(prefixLen + 1).replace(/\//g, path.sep);
} else if (aPath.match(/^[A-Za-z]:/)) {
// If this is Windows and the path starts with a drive letter, ensure lowercase. VS Code uses a lowercase drive letter
aPath = aPath[0].toLowerCase() + aPath.substr(1);
aPath = aPath.replace(/\//g, path.sep);
}
}
return aPath;
}
/**
* Remove a slash of any flavor from the end of the path
*/
export function stripTrailingSlash(aPath: string): string {
return aPath
.replace(/\/$/, '')
.replace(/\\$/, '');
}
export function remoteObjectToValue(object: WebKitProtocol.Runtime.RemoteObject, stringify = true): { value: string, variableHandleRef: string } {
let value = '';
let variableHandleRef: string;
if (object) { // just paranoia?
if (object && object.type === 'object') {
if (object.subtype === 'null') {
value = 'null';
} else {
// If it's a non-null object, create a variable reference so the client can ask for its props
variableHandleRef = object.objectId;
value = object.description;
}
} else if (object && object.type === 'undefined') {
value = 'undefined';
} else if (object.type === 'function') {
const firstBraceIdx = object.description.indexOf('{');
if (firstBraceIdx >= 0) {
value = object.description.substring(0, firstBraceIdx) + '{ … }';
} else {
const firstArrowIdx = object.description.indexOf('=>');
value = firstArrowIdx >= 0 ?
object.description.substring(0, firstArrowIdx + 2) + ' …' :
object.description;
}
} else {
// The value is a primitive value, or something that has a description (not object, primitive, or undefined). And force to be string
if (typeof object.value === 'undefined') {
value = object.description;
} else {
value = stringify ? JSON.stringify(object.value) : object.value;
}
}
}
return { value, variableHandleRef };
}
/**
* A helper for returning a rejected promise with an Error object. Avoids double-wrapping an Error, which could happen
* when passing on a failure from a Promise error handler.
* @param msg - Should be either a string or an Error
*/
export function errP(msg: any): Promise<any> {
let e: Error;
if (!msg) {
e = new Error('Unknown error');
} else if (msg.message) {
// msg is already an Error object
e = msg;
} else {
e = new Error(msg);
}
return Promise.reject(e);
}
/**
* Calculates the appRoot from a launch/attach request. The appRoot is the root directory of the NativeScript app.
*/
export function getAppRoot(args: ILaunchRequestArgs | IAttachRequestArgs): string {
return (args.appRoot && path.isAbsolute(args.appRoot)) ? args.appRoot : '';
}
/**
* Helper function to GET the contents of a url
*/
export function getURL(aUrl: string): Promise<string> {
return new Promise((resolve, reject) => {
http.get(aUrl, response => {
let responseData = '';
response.on('data', chunk => responseData += chunk);
response.on('end', () => {
// Sometimes the 'error' event is not fired. Double check here.
if (response.statusCode === 200) {
resolve(responseData);
} else {
reject(responseData);
}
});
}).on('error', e => {
reject(e);
});
});
}
/**
* Returns true if urlOrPath is like "http://localhost" and not like "c:/code/file.js" or "/code/file.js"
*/
export function isURL(urlOrPath: string): boolean {
return urlOrPath && !path.isAbsolute(urlOrPath) && !!url.parse(urlOrPath).protocol;
}
/**
* Strip a string from the left side of a string
*/
export function lstrip(s: string, lStr: string): string {
return s.startsWith(lStr) ?
s.substr(lStr.length) :
s;
}