-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathutils.ts
More file actions
678 lines (645 loc) · 19.4 KB
/
Copy pathutils.ts
File metadata and controls
678 lines (645 loc) · 19.4 KB
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
import type { FileSystem, POJO } from 'polykey/types.js';
import type {
TableRow,
TableOptions,
DictOptions,
PromiseDeconstructed,
} from '../types.js';
import process from 'node:process';
import { LogLevel } from '@matrixai/logger';
import ErrorPolykey from 'polykey/ErrorPolykey.js';
import * as clientUtils from 'polykey/client/utils.js';
import * as clientErrors from 'polykey/client/errors.js';
import * as networkErrors from 'polykey/network/errors.js';
import * as utils from 'polykey/utils/index.js';
import polykeyConfig from 'polykey/config.js';
import * as binProcessors from './processors.js';
import * as errors from '../errors.js';
// @ts-ignore package.json is outside rootDir
import packageJson from '../../package.json' assert { type: 'json' };
const validEnvRegex = /[a-zA-Z_]+[a-zA-Z0-9_]*/;
// We want to actually match control codes here!
// eslint-disable-next-line no-control-regex
const encodeEscapedRegex = /[\x00-\x1F\x7F-\x9F"'`\\]/g;
const decodeEscapedRegex = /\\([nrtvf"'`\\]|u[0-9a-fA-F]{4})/g;
const urlProtocolRegex = /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//;
/**
* Convert verbosity to LogLevel
*/
function verboseToLogLevel(c: number = 0): LogLevel {
let logLevel = LogLevel.WARN;
if (c === 1) {
logLevel = LogLevel.INFO;
} else if (c >= 2) {
logLevel = LogLevel.DEBUG;
}
return logLevel;
}
type OutputObject =
| {
type: 'raw';
data: string | Uint8Array;
}
| {
type: 'list';
data: Array<string>;
}
| {
type: 'table';
data: Array<POJO>;
options?: TableOptions;
}
| {
type: 'dict';
data: POJO;
options?: DictOptions;
}
| {
type: 'json';
data: any;
}
| {
type: 'error';
data: Error;
};
function standardErrorReplacer(_key: string, value: any) {
if (value instanceof Error && !(value instanceof ErrorPolykey)) {
return {
type: value.name,
data: {
message: value.message,
stack: value.stack,
cause: value.cause,
},
};
}
return value;
}
function encodeEscapedReplacer(_key: string, value: any) {
if (typeof value === 'string') {
return encodeEscaped(value);
}
if (typeof value === 'object' && !Array.isArray(value)) {
for (const valueKey of Object.keys(value)) {
if (typeof valueKey === 'string') {
const newValueKey = encodeEscaped(valueKey);
const valueKeyValue = value[valueKey];
delete value[valueKey];
// This is done in case it is defined as `__proto__`
Object.defineProperty(value, newValueKey, {
value: valueKeyValue,
writable: true,
enumerable: true,
configurable: true,
});
}
}
}
return value;
}
/**
* This function:
*
* 1. Keeps regular spaces, only ' ', as they are.
* 2. Converts \\n \\r \\t to escaped versions, \\\\n \\\\r and \\\\t.
* 3. Converts other control characters to their Unicode escape sequences.
* 4. Converts ' \` " to escaped versions, \\\\' \\\\\` and \\\\"
* 5. Wraps the whole thing in `""` if any characters have been encoded.
*/
function encodeEscapedWrapped(str: string): string {
if (!encodeEscapedRegex.test(str)) {
return str;
}
return `"${encodeEscaped(str)}"`;
}
/**
* This function:
*
* 1. Keeps regular spaces, only ' ', as they are.
* 2. Converts \\\\n \\\\r and \\\\t to unescaped versions, \\n \\r \\t.
* 3. Converts Unicode escape sequences to their control characters.
* 4. Converts \\\\' \\\\\` and \\\\" to their unescaped versions, ' \` ".
* 5. If it is wrapped in "" double quotes, the double quotes will be trimmed.
*/
function decodeEscapedWrapped(str: string): string {
if (!decodeEscapedRegex.test(str)) {
return str;
}
return decodeEscaped(str.substring(1, str.length - 1));
}
/**
* This function:
*
* 1. Keeps regular spaces, only ' ', as they are.
* 2. Converts \\n \\r \\t to escaped versions, \\\\n \\\\r and \\\\t.
* 3. Converts other control characters to their Unicode escape sequences.\
* 4. Converts ' \` " to escaped versions, \\\\' \\\\\` and \\\\"
*
* Unless you're using this in a `JSON.stringify` replacer, you probably want to use {@link encodeEscapedWrapped} instead.
*/
function encodeEscaped(str: string): string {
return str.replace(encodeEscapedRegex, (char) => {
switch (char) {
case '\n':
return '\\n'; // Encode newline
case '\r':
return '\\r'; // Encode carriage return
case '\t':
return '\\t'; // Encode tab
case '\v':
return '\\v'; // Encode tab
case '\f':
return '\\f'; // Encode tab
case '"': // Fallthrough
case "'": // Fallthrough
case '`': // Fallthrough
case '\\':
return '\\' + char;
// Add cases for other whitespace characters if needed
default:
// Return the Unicode escape sequence for control characters
return `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`;
}
});
}
/**
* This function:
*
* 1. Keeps regular spaces, only ' ', as they are.
* 2. Converts \\\\n \\\\r and \\\\t to unescaped versions, \\n \\r \\t.
* 3. Converts Unicode escape sequences to their control characters.
* 4. Converts \\\\' \\\\\` and \\\\" to their unescaped versions, ' \` ".
*
* Unless you're using this in a `JSON.parse` reviver, you probably want to use {@link decodeEscapedWrapped} instead.
*/
function decodeEscaped(str: string): string {
return str.replace(decodeEscapedRegex, (substr) => {
// Unicode escape sequence must be characters (e.g. `\u0000`)
if (substr.length === 6 && substr.at(1) === 'u') {
return String.fromCharCode(parseInt(substr.substring(2), 16));
}
// Length of substr will always be at least 1
const lastChar = substr.at(-1);
if (lastChar == null) {
utils.never('length must be greater than 0');
}
switch (lastChar) {
case 'n':
return '\n';
case 'r':
return '\r';
case 't':
return '\t';
case 'v':
return '\v';
case 'f':
return '\f';
case '"': // Fallthrough
case "'": // Fallthrough
case '`': // Fallthrough
case '\\':
return lastChar;
}
utils.never(`character "${lastChar}" is not handled`);
});
}
/**
* Formats a message suitable for output.
*
* @param msg - The msg that needs to be formatted.
* @see {@link outputFormatterTable} for information regarding usage where `msg.type === 'table'`.
* @returns
*/
function outputFormatter(msg: OutputObject): string | Uint8Array {
switch (msg.type) {
case 'raw':
return msg.data;
case 'list':
return outputFormatterList(msg.data);
case 'table':
return outputFormatterTable(msg.data, msg.options);
case 'dict':
return outputFormatterDict(msg.data, msg.options);
case 'json':
return outputFormatterJson(msg.data);
case 'error':
return outputFormatterError(msg.data);
}
}
function outputFormatterList(items: Array<string>): string {
let output = '';
for (const elem of items) {
// Convert null or undefined to empty string
output += `${elem ?? ''}\n`;
}
return output;
}
/**
* Function to handle the `table` output format.
*
* @param rows
* @param options
* @param options.columns - Can either be an `Array<string>` or `Record<string, number>`.
* If it is `Record<string, number>`, the `number` values will be used as the initial padding lengths.
* The object is also mutated if any cells exceed the initial padding lengths.
* This parameter can also be supplied to filter the columns that will be displayed.
* @param options.includeHeaders - Defaults to `True`.
* @param options.includeRowCount - Defaults to `False`.
* @returns
*/
function outputFormatterTable(
rows: Array<TableRow>,
{
includeHeaders = true,
includeRowCount = false,
columns,
}: TableOptions = {},
): string {
let output = '';
let rowCount = 0;
// Default includeHeaders to true
const maxColumnLengths: Record<string, number> = {};
const optionColumns =
columns != null
? Array.isArray(columns)
? columns
: Object.keys(columns)
: undefined;
// Initialize maxColumnLengths with header lengths if headers with lengths are provided
if (optionColumns != null) {
for (const column of optionColumns) {
maxColumnLengths[column] = columns?.[column];
}
}
// Map<originalColumn, encodedColumn>
const encodedColumns: Map<string, string> = new Map();
// Precompute max column lengths by iterating over the rows first
for (const row of rows) {
for (const column of optionColumns ?? Object.keys(row)) {
if (row[column] != null) {
if (typeof row[column] === 'string') {
row[column] = encodeEscapedWrapped(row[column]);
} else {
row[column] = JSON.stringify(row[column], encodeEscapedReplacer);
}
}
// Null or '' will both cause cellLength to be 3
const cellLength =
row[column] == null || row[column] === '""' ? 3 : row[column].length; // 3 is length of 'N/A'
maxColumnLengths[column] = Math.max(
maxColumnLengths[column] || 0,
cellLength, // Use the length of the encoded value
);
// If headers are included, we need to check if the column header length is bigger
if (includeHeaders && !encodedColumns.has(column)) {
// This only has to be done once, so if the column already exists in the map, don't bother
const encodedColumn = encodeEscapedWrapped(column);
encodedColumns.set(column, encodedColumn);
maxColumnLengths[column] = Math.max(
maxColumnLengths[column] || 0,
encodedColumn.length,
);
}
}
}
// After this point, maxColumnLengths will have been filled with all the necessary keys.
// Thus, the column keys can be derived from it.
const finalColumns = Object.keys(maxColumnLengths);
// If headers are provided, add them to your output first
if (optionColumns != null) {
for (let i = 0; i < optionColumns.length; i++) {
const column = optionColumns[i];
const maxColumnLength = maxColumnLengths[column];
// Options.headers is definitely defined as optionHeaders != null
if (!Array.isArray(columns)) {
columns![column] = maxColumnLength;
}
if (includeHeaders) {
output += (encodedColumns.get(column) ?? column).padEnd(
maxColumnLength,
);
if (i !== optionColumns.length - 1) {
output += '\t';
} else {
output += '\n';
}
}
}
}
for (const row of rows) {
let formattedRow = '';
if (includeRowCount) {
formattedRow += `${++rowCount}\t`;
}
for (const column of finalColumns) {
// Assume row[key] has been already encoded as a string or null
const cellValue =
row[column] == null || row[column].length === 0 ? 'N/A' : row[column];
formattedRow += `${cellValue.padEnd(maxColumnLengths[column] || 0)}\t`;
}
output += formattedRow.trimEnd() + '\n';
}
return output;
}
function outputFormatterDict(
data: POJO,
{
padding = 0,
}: {
padding?: number;
} = {},
): string {
let output = '';
let maxKeyLength = 0;
const leftPadding = ' '.repeat(padding);
// Array<[originalKey, encodedKey]>
const keypairs: Array<[string, string]> = [];
const dataIsArray = Array.isArray(data);
if (!dataIsArray) {
for (const key in data) {
const encodedKey = encodeEscapedWrapped(key);
keypairs.push([key, encodedKey]);
if (encodedKey.length > maxKeyLength) {
maxKeyLength = encodedKey.length;
}
}
} else {
for (const key of data) {
const safeKey = key ?? 'null';
const encodedKey = encodeEscapedWrapped(safeKey);
keypairs.push([safeKey, encodedKey]);
if (encodedKey.length > maxKeyLength) {
maxKeyLength = encodedKey.length;
}
}
}
for (const [originalKey, encodedKey] of keypairs) {
const rightPadding = ' '.repeat(maxKeyLength - encodedKey.length);
output += `${leftPadding}${encodedKey}${rightPadding}\t`;
if (dataIsArray) {
output += '\n';
continue;
}
let value = data[originalKey];
if (value == null) {
value = 'null';
} else if (typeof value == 'object') {
output += `\n${outputFormatterDict(value, {
padding: padding + 2,
})}`;
continue;
} else if (typeof value === 'string') {
value = encodeEscapedWrapped(value);
} else {
value = JSON.stringify(value, encodeEscapedReplacer);
}
value = value.replace(/(?:\r\n|\n)$/, '');
value = value.replace(/(\r\n|\n)/g, '$1\t');
output += `${value}\n`;
}
return output;
}
function outputFormatterJson(json: string): string {
return `${JSON.stringify(json, standardErrorReplacer)}\n`;
}
// Anything is throwable
function outputFormatterError(err: any): string {
let output = '';
let indent = ' ';
while (err != null) {
if (
err instanceof networkErrors.ErrorPolykeyRemote ||
err instanceof errors.ErrorPolykeyCLI
) {
output += `${err.name}: ${err.description}`;
if (err.message && err.message !== '') {
output += ` - ${err.message}`;
}
if (
err instanceof networkErrors.ErrorPolykeyRemote &&
err.metadata != null
) {
output += '\n';
for (const [key, value] of Object.entries(err.metadata)) {
output += `${indent}${key}\t${value}\n`;
}
output += `${indent}timestamp\t${err.timestamp}\n`;
} else {
if (err.data && !utils.isEmptyObject(err.data)) {
output += `\n${indent}data: ${JSON.stringify(err.data)}\n`;
} else {
output += '\n';
}
}
output += `${indent}cause: `;
err = err.cause;
} else if (err instanceof ErrorPolykey) {
output += `${err.name}: ${err.description}`;
if (err.message && err.message !== '') {
output += ` - ${err.message}`;
}
output += '\n';
// Disabled to streamline output
// output += `${indent}exitCode\t${currError.exitCode}\n`;
// output += `${indent}timestamp\t${currError.timestamp}\n`;
if (err.data && !utils.isEmptyObject(err.data)) {
output += `${indent}data\t${JSON.stringify(err.data)}\n`;
}
if (err.cause) {
output += `${indent}cause: `;
if (err.cause instanceof ErrorPolykey) {
err = err.cause;
} else if (err.cause instanceof Error) {
output += `${err.cause.name}`;
if (err.cause.message && err.cause.message !== '') {
output += `: ${err.cause.message}`;
}
output += '\n';
break;
} else {
output += `${JSON.stringify(err.cause)}\n`;
break;
}
} else {
break;
}
} else if (err instanceof Error) {
output += `${err.name}`;
if (err.message && err.message !== '') {
output += `: ${err.message}`;
}
output += '\n';
break;
} else {
output += composeErrorMessage(err);
if (err.message && err.message !== '') {
output += `: ${err.message}`;
}
output += '\n';
break;
}
indent = indent + ' ';
}
return output;
}
function composeErrorMessage(error: any) {
switch (typeof error) {
case 'boolean': // Fallthrough
case 'number': // Fallthrough
case 'string': // Fallthrough
case 'bigint': // Fallthrough
case 'symbol':
return `Thrown non-error literal '${String(error)}'`;
case 'object':
if (error == null) break;
if ('name' in error && typeof error.name === 'string') {
return `Thrown '${error.name}'`;
}
if (error.constructor?.name != null) {
if (error.constructor.name === 'Object') {
// If the constructor name is Object, then the error is a JSON
// object.
return `Thrown non-error JSON '${JSON.stringify(error)}'`;
} else {
// Otherwise, it is a regular object.
return `Thrown non-error object '${error.constructor.name}'`;
}
}
break;
}
try {
return `Thrown non-error value '${error}'`;
} catch (e) {
if (e instanceof TypeError) return `Thrown non-error value 'null'`;
else throw e;
}
}
/**
* CLI Authentication Retry Loop
* Retries unary calls on attended authentication errors
* Known as "privilege elevation"
*/
async function retryAuthentication<T>(
f: (meta: { authorization?: string }) => Promise<T>,
meta: { authorization?: string } = {},
): Promise<T> {
try {
return await f(meta);
} catch (e) {
// If it is unattended, throw the exception.
// Don't enter into a retry loop when unattended.
// Unattended means that either the `PK_PASSWORD` or `PK_TOKEN` was set.
if ('PK_PASSWORD' in process.env || 'PK_TOKEN' in process.env) {
throw e;
}
// If it is exception is not missing or denied, then throw the exception
const [cause] = remoteErrorCause(e);
if (
!(cause instanceof clientErrors.ErrorClientAuthMissing) &&
!(cause instanceof clientErrors.ErrorClientAuthDenied)
) {
throw e;
}
}
// Now enter the retry loop
while (true) {
// Prompt the user for password
const password = await binProcessors.promptPassword();
if (password == null) {
throw new errors.ErrorPolykeyCLIPasswordMissing();
}
// Augment existing metadata
const auth = {
authorization: clientUtils.encodeAuthFromPassword(password),
};
try {
return await f(auth);
} catch (e) {
const [cause] = remoteErrorCause(e);
// The auth cannot be missing, so when it is denied do we retry
if (!(cause instanceof clientErrors.ErrorClientAuthDenied)) {
throw e;
}
}
}
}
function remoteErrorCause(e: any): [any, number] {
let errorCause = e;
let depth = 0;
while (errorCause instanceof networkErrors.ErrorPolykeyRemote) {
errorCause = errorCause.cause;
depth++;
}
return [errorCause, depth];
}
/**
* Returns a formatted version string in the format of `[ APPVERSION, LIBRARYVERSION, NETWORKVERSION, STATEVERSION ]`
*/
function generateVersionString(): string {
const version = [
packageJson.version,
polykeyConfig.sourceVersion,
`${polykeyConfig.networkVersion}`,
`${polykeyConfig.stateVersion}`,
];
return JSON.stringify(version);
}
/**
* Deconstructed promise
*/
function promise<T = void>(): PromiseDeconstructed<T> {
let resolveP, rejectP;
const p = new Promise<T>((resolve, reject) => {
resolveP = resolve;
rejectP = reject;
});
return {
p,
resolveP,
rejectP,
};
}
async function importFS(fs?: FileSystem): Promise<FileSystem> {
if (fs != null) return fs;
const { default: fsImported } = await import('node:fs');
return fsImported;
}
/**
* The return URL will not contain a trailing slash
*/
function normalizeURL(url: string): URL {
// If the protocol is missing from the URL, add https:// as the default
if (!urlProtocolRegex.test(url)) {
url = 'https://' + url;
}
if (url.endsWith('/')) {
url = url.slice(0, url.length);
}
return new URL(url);
}
export {
verboseToLogLevel,
standardErrorReplacer,
encodeEscapedReplacer,
outputFormatter,
outputFormatterList,
outputFormatterTable,
outputFormatterDict,
outputFormatterJson,
outputFormatterError,
composeErrorMessage,
retryAuthentication,
remoteErrorCause,
encodeEscapedWrapped,
encodeEscaped,
encodeEscapedRegex,
decodeEscapedWrapped,
decodeEscaped,
decodeEscapedRegex,
validEnvRegex,
generateVersionString,
promise,
importFS,
normalizeURL,
};
export type { OutputObject };