-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
miscUtils.ts
378 lines (288 loc) Β· 9.9 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
import {PortablePath, npath} from '@yarnpkg/fslib';
import {UsageError} from 'clipanion';
import micromatch from 'micromatch';
import {Readable, Transform} from 'stream';
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 {
if (!Object.values(def).includes(value as any))
throw new Error(`Assertion failed: Invalid value for enumeration`);
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;
/**
* 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 function getFactoryWithDefault<K, T>(map: Map<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: Map<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: Map<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: Map<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));
}
}
// 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!
declare const __non_webpack_require__: typeof require | undefined;
export const dynamicRequire = (typeof __non_webpack_require__ !== `undefined`) ? __non_webpack_require__ : require;
export function dynamicRequireNoCache(path: PortablePath) {
const physicalPath = npath.fromPortablePath(path);
const currentCacheEntry = dynamicRequire.cache[physicalPath];
delete dynamicRequire.cache[physicalPath];
let result;
try {
result = dynamicRequire(physicalPath);
const freshCacheEntry = dynamicRequire.cache[physicalPath];
const dynamicModule = eval(`module`) as NodeModule;
const freshCacheIndex = dynamicModule.children.indexOf(freshCacheEntry);
if (freshCacheIndex !== -1) {
dynamicModule.children.splice(freshCacheIndex, 1);
}
} finally {
dynamicRequire.cache[physicalPath] = currentCacheEntry;
}
return result;
}
// 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,
}).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.prototype.hasOwnProperty.call(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;
}
}