-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathmiscUtils.ts
599 lines (465 loc) Β· 16.1 KB
/
miscUtils.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
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
import {PortablePath, npath, xfs} from '@yarnpkg/fslib';
import {UsageError} from 'clipanion';
import {isEqual, mergeWith} from 'es-toolkit/compat';
import micromatch from 'micromatch';
import pLimit, {Limit} from 'p-limit';
import semver from 'semver';
import {Readable, Transform} from 'stream';
/**
* @internal
*/
export function isTaggedYarnVersion(version: string | null) {
return !!(semver.valid(version) && version!.match(/^[^-]+(-rc\.[0-9]+)?$/));
}
export function plural(n: number, {one, more, zero = more}: {zero?: string, one: string, more: string}) {
return n === 0 ? zero : n === 1 ? one : more;
}
export function escapeRegExp(str: string) {
return str.replace(/[.*+?^${}()|[\]\\]/g, `\\$&`);
}
export function overrideType<T>(val: unknown): asserts val is T {
}
export function assertNever(arg: never): never {
throw new Error(`Assertion failed: Unexpected object '${arg}'`);
}
export function validateEnum<T>(def: {[key: string]: T}, value: string): T {
const values = Object.values(def);
if (!values.includes(value as any))
throw new UsageError(`Invalid value for enumeration: ${JSON.stringify(value)} (expected one of ${values.map(value => JSON.stringify(value)).join(`, `)})`);
return value as any as T;
}
export function mapAndFilter<In, Out>(iterable: Iterable<In>, cb: (value: In) => Out | typeof mapAndFilterSkip): Array<Out> {
const output: Array<Out> = [];
for (const value of iterable) {
const out = cb(value);
if (out !== mapAndFilterSkip) {
output.push(out);
}
}
return output;
}
const mapAndFilterSkip = Symbol();
mapAndFilter.skip = mapAndFilterSkip;
export function mapAndFind<In, Out>(iterable: Iterable<In>, cb: (value: In) => Out | typeof mapAndFindSkip): Out | undefined {
for (const value of iterable) {
const out = cb(value);
if (out !== mapAndFindSkip) {
return out;
}
}
return undefined;
}
const mapAndFindSkip = Symbol();
mapAndFind.skip = mapAndFindSkip;
export function isIndexableObject(value: unknown): value is {[key: string]: unknown} {
return typeof value === `object` && value !== null;
}
export type MapValue<T> = T extends Map<any, infer V> ? V : never;
export interface ToMapValue<T extends object> {
get<K extends keyof T>(key: K): T[K];
}
export type MapValueToObjectValue<T> =
T extends Map<infer K, infer V> ? (K extends string | number | symbol ? MapValueToObjectValue<Record<K, V>> : never)
: T extends ToMapValue<infer V> ? MapValueToObjectValue<V>
: T extends PortablePath ? PortablePath
: T extends object ? {[K in keyof T]: MapValueToObjectValue<T[K]>}
: T;
export async function allSettledSafe<T>(promises: Array<Promise<T>>) {
const results = await Promise.allSettled(promises);
const values: Array<T> = [];
for (const result of results) {
if (result.status === `rejected`) {
throw result.reason;
} else {
values.push(result.value);
}
}
return values;
}
/**
* Converts Maps to indexable objects recursively.
*/
export function convertMapsToIndexableObjects<T>(arg: T): MapValueToObjectValue<T> {
if (arg instanceof Map)
arg = Object.fromEntries(arg);
if (isIndexableObject(arg)) {
for (const key of Object.keys(arg)) {
const value = arg[key];
if (isIndexableObject(value)) {
// @ts-expect-error: Apparently nothing in this world can be used to index type 'T & { [key: string]: unknown; }'
arg[key] = convertMapsToIndexableObjects(value);
}
}
}
return arg as MapValueToObjectValue<T>;
}
export interface GetSetMap<K, V> {
get(k: K): V | undefined;
set(k: K, v: V): void;
}
export function getFactoryWithDefault<K, T>(map: GetSetMap<K, T>, key: K, factory: () => T) {
let value = map.get(key);
if (typeof value === `undefined`)
map.set(key, value = factory());
return value;
}
export function getArrayWithDefault<K, T>(map: GetSetMap<K, Array<T>>, key: K) {
let value = map.get(key);
if (typeof value === `undefined`)
map.set(key, value = []);
return value;
}
export function getSetWithDefault<K, T>(map: GetSetMap<K, Set<T>>, key: K) {
let value = map.get(key);
if (typeof value === `undefined`)
map.set(key, value = new Set<T>());
return value;
}
export function getMapWithDefault<K, MK, MV>(map: GetSetMap<K, Map<MK, MV>>, key: K) {
let value = map.get(key);
if (typeof value === `undefined`)
map.set(key, value = new Map<MK, MV>());
return value;
}
// Executes a chunk of code and calls a cleanup function once it returns (even
// if it throws an exception)
export async function releaseAfterUseAsync<T>(fn: () => Promise<T>, cleanup?: (() => any) | null) {
if (cleanup == null)
return await fn();
try {
return await fn();
} finally {
await cleanup();
}
}
// Executes a chunk of code but slightly modify its exception message if it
// throws something
export async function prettifyAsyncErrors<T>(fn: () => Promise<T>, update: (message: string) => string) {
try {
return await fn();
} catch (error) {
error.message = update(error.message);
throw error;
}
}
// Same thing but synchronous
export function prettifySyncErrors<T>(fn: () => T, update: (message: string) => string) {
try {
return fn();
} catch (error) {
error.message = update(error.message);
throw error;
}
}
// Converts a Node stream into a Buffer instance
export async function bufferStream(stream: Readable) {
return await new Promise<Buffer>((resolve, reject) => {
const chunks: Array<Buffer> = [];
stream.on(`error`, error => {
reject(error);
});
stream.on(`data`, chunk => {
chunks.push(chunk);
});
stream.on(`end`, () => {
resolve(Buffer.concat(chunks));
});
});
}
// A stream implementation that buffers a stream to send it all at once
export class BufferStream extends Transform {
private readonly chunks: Array<Buffer> = [];
_transform(chunk: Buffer, encoding: string, cb: any) {
if (encoding !== `buffer` || !Buffer.isBuffer(chunk))
throw new Error(`Assertion failed: BufferStream only accept buffers`);
this.chunks.push(chunk as Buffer);
cb(null, null);
}
_flush(cb: any) {
cb(null, Buffer.concat(this.chunks));
}
}
export type Deferred<T = void> = {
promise: Promise<T>;
resolve: (val: T) => void;
reject: (err: Error) => void;
};
export function makeDeferred<T = void>(): Deferred<T> {
let resolve: (val: T) => void;
let reject: (err: Error) => void;
const promise = new Promise<T>((resolveFn, rejectFn) => {
resolve = resolveFn;
reject = rejectFn;
});
return {promise, resolve: resolve!, reject: reject!};
}
export class AsyncActions {
private deferred = new Map<string, Deferred>();
private promises = new Map<string, Promise<void>>();
private limit: Limit;
constructor(limit: number) {
this.limit = pLimit(limit);
}
set(key: string, factory: () => Promise<void>) {
let deferred = this.deferred.get(key);
if (typeof deferred === `undefined`)
this.deferred.set(key, deferred = makeDeferred());
const promise = this.limit(() => factory());
this.promises.set(key, promise);
promise.then(() => {
if (this.promises.get(key) === promise) {
deferred!.resolve();
}
}, err => {
if (this.promises.get(key) === promise) {
deferred!.reject(err);
}
});
return deferred.promise;
}
reduce(key: string, factory: (action: Promise<void>) => Promise<void>) {
const promise = this.promises.get(key) ?? Promise.resolve();
this.set(key, () => factory(promise));
}
async wait() {
await Promise.all(this.promises.values());
}
}
// A stream implementation that prints a message if nothing was output
export class DefaultStream extends Transform {
private readonly ifEmpty: Buffer;
public active = true;
constructor(ifEmpty: Buffer = Buffer.alloc(0)) {
super();
this.ifEmpty = ifEmpty;
}
_transform(chunk: Buffer, encoding: string, cb: any) {
if (encoding !== `buffer` || !Buffer.isBuffer(chunk))
throw new Error(`Assertion failed: DefaultStream only accept buffers`);
this.active = false;
cb(null, chunk);
}
_flush(cb: any) {
if (this.active && this.ifEmpty.length > 0) {
cb(null, this.ifEmpty);
} else {
cb(null);
}
}
}
// Webpack has this annoying tendency to replace dynamic requires by a stub
// code that simply throws when called. It's all fine and dandy in the context
// of a web application, but is quite annoying when working with Node projects!
const realRequire: NodeRequire = eval(`require`);
function dynamicRequireNode(path: string) {
return realRequire(npath.fromPortablePath(path));
}
/**
* Requires a module without using the module cache
*/
function dynamicRequireNoCache(path: string) {
const physicalPath = npath.fromPortablePath(path);
const currentCacheEntry = realRequire.cache[physicalPath];
delete realRequire.cache[physicalPath];
let result;
try {
result = dynamicRequireNode(physicalPath);
const freshCacheEntry = realRequire.cache[physicalPath]!;
const dynamicModule = eval(`module`) as NodeModule;
const freshCacheIndex = dynamicModule.children.indexOf(freshCacheEntry);
if (freshCacheIndex !== -1) {
dynamicModule.children.splice(freshCacheIndex, 1);
}
} finally {
realRequire.cache[physicalPath] = currentCacheEntry;
}
return result;
}
const dynamicRequireFsTimeCache = new Map<PortablePath, {
mtime: number;
instance: any;
}>();
/**
* Requires a module without using the cache if it has changed since the last time it was loaded
*/
function dynamicRequireFsTime(path: PortablePath) {
const cachedInstance = dynamicRequireFsTimeCache.get(path);
const stat = xfs.statSync(path);
if (cachedInstance?.mtime === stat.mtimeMs)
return cachedInstance.instance;
const instance = dynamicRequireNoCache(path);
dynamicRequireFsTimeCache.set(path, {mtime: stat.mtimeMs, instance});
return instance;
}
export enum CachingStrategy {
NoCache,
FsTime,
Node,
}
export function dynamicRequire(path: string, opts?: {cachingStrategy?: CachingStrategy}): any;
export function dynamicRequire(path: PortablePath, opts: {cachingStrategy: CachingStrategy.FsTime}): any;
export function dynamicRequire(path: string | PortablePath, {cachingStrategy = CachingStrategy.Node}: {cachingStrategy?: CachingStrategy} = {}) {
switch (cachingStrategy) {
case CachingStrategy.NoCache:
return dynamicRequireNoCache(path);
case CachingStrategy.FsTime:
return dynamicRequireFsTime(path as PortablePath);
case CachingStrategy.Node:
return dynamicRequireNode(path);
default: {
throw new Error(`Unsupported caching strategy`);
}
}
}
// This function transforms an iterable into an array and sorts it according to
// the mapper functions provided as parameter. The mappers are expected to take
// each element from the iterable and generate a string from it, that will then
// be used to compare the entries.
//
// Using sortMap is more efficient than kinda reimplementing the logic in a sort
// predicate because sortMap caches the result of the mappers in such a way that
// they are guaranteed to be executed exactly once for each element.
export function sortMap<T>(values: Iterable<T>, mappers: ((value: T) => string) | Array<(value: T) => string>) {
const asArray = Array.from(values);
if (!Array.isArray(mappers))
mappers = [mappers];
const stringified: Array<Array<string>> = [];
for (const mapper of mappers)
stringified.push(asArray.map(value => mapper(value)));
const indices = asArray.map((_, index) => index);
indices.sort((a, b) => {
for (const layer of stringified) {
const comparison = layer[a] < layer[b] ? -1 : layer[a] > layer[b] ? +1 : 0;
if (comparison !== 0) {
return comparison;
}
}
return 0;
});
return indices.map(index => {
return asArray[index];
});
}
/**
* Combines an Array of glob patterns into a regular expression.
*
* @param ignorePatterns An array of glob patterns
*
* @returns A `string` representing a regular expression or `null` if no glob patterns are provided
*/
export function buildIgnorePattern(ignorePatterns: Array<string>) {
if (ignorePatterns.length === 0)
return null;
return ignorePatterns.map(pattern => {
return `(${micromatch.makeRe(pattern, {
windows: false,
dot: true,
}).source})`;
}).join(`|`);
}
export function replaceEnvVariables(value: string, {env}: {env: {[key: string]: string | undefined}}) {
const regex = /\${(?<variableName>[\d\w_]+)(?<colon>:)?(?:-(?<fallback>[^}]*))?}/g;
return value.replace(regex, (...args) => {
const {variableName, colon, fallback} = args[args.length - 1];
const variableExist = Object.hasOwn(env, variableName);
const variableValue = env[variableName];
if (variableValue)
return variableValue;
if (variableExist && !colon)
return variableValue;
if (fallback != null)
return fallback;
throw new UsageError(`Environment variable not found (${variableName})`);
});
}
export function parseBoolean(value: unknown): boolean {
switch (value) {
case `true`:
case `1`:
case 1:
case true: {
return true;
}
case `false`:
case `0`:
case 0:
case false: {
return false;
}
default: {
throw new Error(`Couldn't parse "${value}" as a boolean`);
}
}
}
export function parseOptionalBoolean(value: unknown): boolean | undefined {
if (typeof value === `undefined`)
return value;
return parseBoolean(value);
}
export function tryParseOptionalBoolean(value: unknown): boolean | undefined | null {
try {
return parseOptionalBoolean(value);
} catch {
return null;
}
}
export type FilterKeys<T extends {}, Filter> = {
[K in keyof T]: T[K] extends Filter ? K : never;
}[keyof T];
export function isPathLike(value: string): boolean {
if (npath.isAbsolute(value) || value.match(/^(\.{1,2}|~)\//))
return true;
return false;
}
type MergeObjects<T extends Array<unknown>, Accumulator> = T extends [infer U, ...infer Rest]
? MergeObjects<Rest, Accumulator & U>
: Accumulator;
/**
* Merges multiple objects into the target argument.
*
* **Important:** This function mutates the target argument.
*
* Custom classes inside the target parameter are supported (e.g. comment-json's `CommentArray` - comments from target will be preserved).
*
* @see toMerged for a version that doesn't mutate the target argument
*
*/
export function mergeIntoTarget<T extends object, S extends Array<object>>(target: T, ...sources: S): MergeObjects<S, T> {
// We need to wrap everything in an object because otherwise lodash fails to merge 2 top-level arrays
const wrap = <T>(value: T) => ({value});
const wrappedTarget = wrap(target);
const wrappedSources = sources.map(source => wrap(source));
const {value} = mergeWith(wrappedTarget, ...wrappedSources, (targetValue: unknown, sourceValue: unknown) => {
// We need to preserve comments in custom Array classes such as comment-json's `CommentArray`, so we can't use spread or `Set`s
if (Array.isArray(targetValue) && Array.isArray(sourceValue)) {
for (const sourceItem of sourceValue) {
if (!targetValue.find(targetItem => isEqual(targetItem, sourceItem))) {
targetValue.push(sourceItem);
}
}
return targetValue;
}
return undefined;
});
return value;
}
/**
* Merges multiple objects into a single one, without mutating any arguments.
*
* Custom classes are not supported (i.e. comment-json's comments will be lost).
*/
export function toMerged<S extends Array<object>>(...sources: S): MergeObjects<S, {}> {
return mergeIntoTarget({}, ...sources);
}
export function groupBy<T extends Record<string, any>, K extends keyof T>(items: Iterable<T>, key: K): {[V in T[K]]?: Array<Extract<T, {[_ in K]: V}>>} {
const groups: Record<string, any> = Object.create(null);
for (const item of items) {
const groupKey = item[key];
groups[groupKey] ??= [];
groups[groupKey].push(item);
}
return groups;
}
export function parseInt(val: string | number) {
return typeof val === `string` ? Number.parseInt(val, 10) : val;
}