-
-
Notifications
You must be signed in to change notification settings - Fork 496
/
Utils.ts
1170 lines (950 loc) · 32.6 KB
/
Utils.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
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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { createRequire } from 'module';
import type { GlobbyOptions } from 'globby';
import globby from 'globby';
import { extname, isAbsolute, join, normalize, relative, resolve } from 'path';
import { platform } from 'os';
import type { URL } from 'url';
import { fileURLToPath, pathToFileURL } from 'url';
import { pathExists } from 'fs-extra';
import { createHash } from 'crypto';
// @ts-ignore
import { parse } from 'acorn-loose';
import { simple as walk } from 'acorn-walk';
import { clone } from './clone';
import type {
Dictionary,
EntityData,
EntityDictionary,
EntityKey,
EntityMetadata,
EntityName,
EntityProperty,
IMetadataStorage,
Primary,
} from '../typings';
import { GroupOperator, PlainObject, QueryOperator, ReferenceKind } from '../enums';
import type { Collection } from '../entity/Collection';
import type { Platform } from '../platforms';
import { helper } from '../entity/wrap';
export const ObjectBindingPattern = Symbol('ObjectBindingPattern');
function compareConstructors(a: any, b: any) {
if (a.constructor === b.constructor) {
return true;
}
if (!a.constructor) {
return b.constructor === Object;
}
if (!b.constructor) {
return a.constructor === Object;
}
return false;
}
export function compareObjects(a: any, b: any) {
// eslint-disable-next-line eqeqeq
if (a === b || (a == null && b == null)) {
return true;
}
if (!a || !b || typeof a !== 'object' || typeof b !== 'object' || !compareConstructors(a, b)) {
return false;
}
if (a.valueOf !== Object.prototype.valueOf && typeof a.valueOf === 'function' && typeof b.valueOf === 'function') {
return a.valueOf() === b.valueOf();
}
if (a.toString !== Object.prototype.toString && typeof a.toString === 'function' && typeof b.toString === 'function') {
return a.toString() === b.toString();
}
const keys = Object.keys(a);
const length = keys.length;
if (length !== Object.keys(b).length) {
return false;
}
for (let i = length; i-- !== 0;) {
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) {
return false;
}
}
for (let i = length; i-- !== 0;) {
const key = keys[i];
// eslint-disable-next-line @typescript-eslint/no-use-before-define
if (!equals(a[key], b[key])) {
return false;
}
}
return true;
}
export function compareArrays(a: any[] | string, b: any[] | string) {
const length = a.length;
if (length !== b.length) {
return false;
}
for (let i = length; i-- !== 0;) {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
if (!equals(a[i], b[i])) {
return false;
}
}
return true;
}
export function compareBooleans(a: unknown, b: unknown): boolean {
a = typeof a === 'number' ? Boolean(a) : a;
b = typeof b === 'number' ? Boolean(b) : b;
return a === b;
}
export function compareBuffers(a: Buffer, b: Buffer): boolean {
const length = a.length;
if (length !== b.length) {
return false;
}
for (let i = length; i-- !== 0;) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
/**
* Checks if arguments are deeply (but not strictly) equal.
*/
export function equals(a: any, b: any): boolean {
if (a === b) {
return true;
}
if (a && b && typeof a === 'object' && typeof b === 'object') {
if (Array.isArray(a)) {
return compareArrays(a, b);
}
if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
return compareBuffers(a as Buffer, b as Buffer);
}
return compareObjects(a, b);
}
return Number.isNaN(a) && Number.isNaN(b);
}
const equalsFn = equals;
export function parseJsonSafe<T = unknown>(value: unknown): T {
if (typeof value === 'string') {
try {
return JSON.parse(value);
} catch {
// ignore and return the value, as sometimes we get the parsed value,
// e.g. when it is a string value in JSON column
}
}
return value as T;
}
export class Utils {
static readonly PK_SEPARATOR = '~~~';
/* istanbul ignore next */
static dynamicImportProvider = (id: string) => import(id);
/**
* Checks if the argument is not undefined
*/
static isDefined<T = Record<string, unknown>>(data: any): data is T {
return typeof data !== 'undefined';
}
/**
* Checks if the argument is instance of `Object`. Returns false for arrays.
*/
static isObject<T = Dictionary>(o: any): o is T {
return !!o && typeof o === 'object' && !Array.isArray(o);
}
/**
* Relation decorators allow using two signatures
* - using first parameter as options object
* - using all parameters
*
* This function validates those two ways are not mixed and returns the final options object.
* If the second way is used, we always consider the last parameter as options object.
* @internal
*/
static processDecoratorParameters<T>(params: Dictionary): T {
const keys = Object.keys(params);
const values = Object.values(params);
if (!Utils.isPlainObject(values[0])) {
const lastKey = keys[keys.length - 1];
const last = params[lastKey];
delete params[lastKey];
return { ...last, ...params };
}
// validate only first parameter is used if its an option object
const empty = (v: unknown) => v == null || (Utils.isPlainObject(v) && !Utils.hasObjectKeys(v));
if (values.slice(1).some(v => !empty(v))) {
throw new Error('Mixing first decorator parameter as options object with other parameters is forbidden. ' +
'If you want to use the options parameter at first position, provide all options inside it.');
}
return values[0] as T;
}
/**
* Checks if the argument is instance of `Object`, but not one of the blacklisted types. Returns false for arrays.
*/
static isNotObject<T = Dictionary>(o: any, not: any[]): o is T {
return this.isObject(o) && !not.some(cls => o instanceof cls);
}
/**
* Removes `undefined` properties (recursively) so they are not saved as nulls
*/
static dropUndefinedProperties<T = Dictionary | unknown[]>(o: any): void {
if (Array.isArray(o)) {
return o.forEach((item: unknown) => Utils.dropUndefinedProperties(item));
}
if (!Utils.isObject(o)) {
return;
}
Object.keys(o).forEach(key => {
if (o[key] === undefined) {
delete o[key];
return;
}
Utils.dropUndefinedProperties(o[key]);
});
}
/**
* Returns the number of properties on `obj`. This is 20x faster than Object.keys(obj).length.
* @see https://github.com/deepkit/deepkit-framework/blob/master/packages/core/src/core.ts
*/
static getObjectKeysSize(object: Dictionary): number {
let size = 0;
for (const key in object) {
/* istanbul ignore else */
if (Object.prototype.hasOwnProperty.call(object, key)) {
size++;
}
}
return size;
}
/**
* Returns true if `obj` has at least one property. This is 20x faster than Object.keys(obj).length.
* @see https://github.com/deepkit/deepkit-framework/blob/master/packages/core/src/core.ts
*/
static hasObjectKeys(object: Dictionary): boolean {
for (const key in object) {
/* istanbul ignore else */
if (Object.prototype.hasOwnProperty.call(object, key)) {
return true;
}
}
return false;
}
/**
* Checks if the argument is string
*/
static isString(s: any): s is string {
return typeof s === 'string';
}
/**
* Checks if the argument is number
*/
static isNumber<T = number>(s: any): s is T {
return typeof s === 'number';
}
/**
* Checks if arguments are deeply (but not strictly) equal.
*/
static equals(a: any, b: any): boolean {
return equalsFn(a, b);
}
/**
* Gets array without duplicates.
*/
static unique<T = string>(items: T[]): T[] {
return [...new Set(items)];
}
/**
* Merges all sources into the target recursively.
*/
static merge(target: any, ...sources: any[]): any {
if (!sources.length) {
return target;
}
const source = sources.shift();
if (Utils.isObject(target) && Utils.isPlainObject(source)) {
Object.entries(source).forEach(([key, value]) => {
if (typeof value === 'undefined') {
return;
}
if (Utils.isPlainObject(value)) {
if (!Utils.isObject(target[key])) {
target[key] = Utils.copy(value);
return;
}
if (!(key in target)) {
Object.assign(target, { [key]: {} });
}
Utils.merge(target[key], value);
} else {
Object.assign(target, { [key]: value });
}
});
}
return Utils.merge(target, ...sources);
}
static getRootEntity(metadata: IMetadataStorage, meta: EntityMetadata): EntityMetadata {
const base = meta.extends && metadata.find(meta.extends);
if (!base || base === meta) { // make sure we do not fall into infinite loop
return meta;
}
const root = Utils.getRootEntity(metadata, base);
if (root.discriminatorColumn) {
return root;
}
return meta;
}
/**
* Computes difference between two objects, ignoring items missing in `b`.
*/
static diff(a: Dictionary, b: Dictionary): Record<keyof (typeof a & typeof b), any> {
const ret: Dictionary = {};
Object.keys(b).forEach(k => {
if (Utils.equals(a[k], b[k])) {
return;
}
ret[k] = b[k];
});
return ret;
}
/**
* Creates deep copy of given object.
*/
static copy<T>(entity: T, respectCustomCloneMethod = true): T {
return clone(entity, respectCustomCloneMethod);
}
/**
* Normalize the argument to always be an array.
*/
static asArray<T>(data?: T | readonly T[], strict = false): T[] {
if (typeof data === 'undefined' && !strict) {
return [];
}
if (data instanceof Set) {
return Array.from(data);
}
return Array.isArray(data!) ? data : [data as T];
}
/**
* Renames object key, keeps order of properties.
*/
static renameKey<T>(payload: T, from: string | keyof T, to: string): void {
if (Utils.isObject(payload) && (from as string) in payload && !(to in payload)) {
Object.keys(payload).forEach(key => {
const value = payload[key];
delete payload[key];
payload[from === key ? to : key as keyof T] = value;
}, payload);
}
}
/**
* Returns array of functions argument names. Uses `escaya` for source code analysis.
*/
static getParamNames(func: { toString(): string } | string, methodName?: string): string[] {
const ret: string[] = [];
const parsed = parse(func.toString(), { ecmaVersion: 2022 });
const checkNode = (node: any, methodName?: string) => {
if (methodName && !(node.key && (node.key as any).name === methodName)) {
return;
}
const params = node.value ? node.value.params : node.params;
ret.push(...params.map((p: any) => {
switch (p.type) {
case 'AssignmentPattern':
if (p.left.type === 'ObjectPattern') {
return ObjectBindingPattern;
}
return p.left.name;
case 'RestElement':
return '...' + p.argument.name;
default:
return p.name;
}
}));
};
walk(parsed, {
MethodDefinition: (node: any) => checkNode(node, methodName),
FunctionDeclaration: (node: any) => checkNode(node, methodName),
});
return ret;
}
/**
* Checks whether the argument looks like primary key (string, number or ObjectId).
*/
static isPrimaryKey<T>(key: any, allowComposite = false): key is Primary<T> {
if (allowComposite && Array.isArray(key) && key.every(v => Utils.isPrimaryKey(v, true))) {
return true;
}
if (Utils.isObject(key) && !Utils.isPlainObject(key) && !Utils.isEntity(key, true)) {
return true;
}
return ['string', 'number', 'bigint'].includes(typeof key) || Utils.isObjectID(key) || key instanceof Date || key instanceof Buffer;
}
/**
* Extracts primary key from `data`. Accepts objects or primary keys directly.
*/
static extractPK<T extends object>(data: any, meta?: EntityMetadata<T>, strict = false): Primary<T> | string | null {
if (Utils.isPrimaryKey(data)) {
return data as Primary<T>;
}
if (Utils.isEntity<T>(data, true)) {
return helper(data).getPrimaryKey();
}
if (strict && meta && Utils.getObjectKeysSize(data) !== meta.primaryKeys.length) {
return null;
}
if (Utils.isPlainObject(data) && meta) {
if (meta.compositePK) {
return this.getCompositeKeyValue(data as T, meta);
}
return data[meta.primaryKeys[0]] || data[meta.serializedPrimaryKey] || null;
}
return null;
}
static getCompositeKeyValue<T>(
data: EntityData<T>,
meta: EntityMetadata<T>,
convertCustomTypes: boolean | 'convertToDatabaseValue' | 'convertToJSValue' = false,
platform?: Platform,
): Primary<T> {
return meta.primaryKeys.map((pk, idx) => {
const value = Array.isArray(data) ? data[idx] : data[pk as EntityKey<T>];
const prop = meta.properties[pk];
if (prop.targetMeta && Utils.isPlainObject(value)) {
return this.getCompositeKeyValue(value as T, prop.targetMeta);
}
if (prop.customType && platform && convertCustomTypes) {
const method = typeof convertCustomTypes === 'string' ? convertCustomTypes : 'convertToJSValue';
return prop.customType[method](value, platform);
}
return value;
}) as Primary<T>;
}
static getCompositeKeyHash<T>(data: EntityData<T>, meta: EntityMetadata<T>, convertCustomTypes = false, platform?: Platform, flat = false): string {
let pks = this.getCompositeKeyValue(data, meta, convertCustomTypes, platform);
if (flat) {
pks = Utils.flatten(pks as unknown[][]) as Primary<T>;
}
return Utils.getPrimaryKeyHash(pks as string[]);
}
static getPrimaryKeyHash(pks: string[]): string {
return pks.join(this.PK_SEPARATOR);
}
static splitPrimaryKeys<T extends object>(key: string): EntityKey<T>[] {
return key.split(this.PK_SEPARATOR) as EntityKey<T>[];
}
static getPrimaryKeyValues<T>(entity: T, primaryKeys: string[], allowScalar = false, convertCustomTypes = false) {
if (entity == null) {
return entity;
}
function toArray(val: unknown): unknown {
if (Utils.isPlainObject(val)) {
return Object.values(val).flatMap(v => toArray(v));
}
return val;
}
const pk = Utils.isEntity(entity, true)
? helper(entity).getPrimaryKey(convertCustomTypes)
: primaryKeys.reduce((o, pk) => { o[pk] = entity[pk]; return o; }, {} as Dictionary);
if (primaryKeys.length > 1) {
return toArray(pk!);
}
if (allowScalar) {
if (Utils.isPlainObject(pk)) {
return pk[primaryKeys[0]];
}
return pk;
}
return [pk];
}
static getPrimaryKeyCond<T>(entity: T, primaryKeys: EntityKey<T>[]): Record<string, Primary<T>> | null {
const cond = primaryKeys.reduce((o, pk) => {
o[pk] = Utils.extractPK(entity[pk]);
return o;
}, {} as any);
if (Object.values(cond).some(v => v === null)) {
return null;
}
return cond;
}
static getPrimaryKeyCondFromArray<T extends object>(pks: Primary<T>[], meta: EntityMetadata<T>): Record<string, Primary<T>> {
return meta.getPrimaryProps().reduce((o, pk, idx) => {
if (Array.isArray(pks[idx]) && pk.targetMeta) {
o[pk.name] = pks[idx];
} else {
o[pk.name] = Utils.extractPK<T>(pks[idx], meta);
}
return o;
}, {} as any);
}
static getOrderedPrimaryKeys<T>(id: Primary<T> | Record<string, Primary<T>>, meta: EntityMetadata<T>, platform?: Platform, convertCustomTypes?: boolean): Primary<T>[] {
const data = (Utils.isPrimaryKey(id) ? { [meta.primaryKeys[0]]: id } : id) as Record<string, Primary<T>>;
const pks = meta.primaryKeys.map((pk, idx) => {
const prop = meta.properties[pk];
// `data` can be a composite PK in form of array of PKs, or a DTO
let value = Array.isArray(data) ? data[idx] : data[pk];
if (prop.kind !== ReferenceKind.SCALAR && prop.targetMeta) {
const value2 = this.getOrderedPrimaryKeys(value, prop.targetMeta, platform); // do not convert custom types yet
value = value2.length > 1 ? value2 : value2[0];
}
if (prop.customType && platform && convertCustomTypes) {
return prop.customType.convertToJSValue(value, platform);
}
return value;
});
// we need to flatten the PKs as composite PKs can be build from another composite PKs
// and this method is used to get the PK hash in identity map, that expects flat array
return Utils.flatten(pks) as Primary<T>[];
}
/**
* Checks whether given object is an entity instance.
*/
static isEntity<T = unknown>(data: any, allowReference = false): data is T & {} {
if (!Utils.isObject(data)) {
return false;
}
if (allowReference && !!data.__reference) {
return true;
}
return !!data.__entity;
}
/**
* Checks whether the argument is ObjectId instance
*/
static isObjectID(key: any) {
return Utils.isObject(key) && key.constructor && key.constructor.name.toLowerCase() === 'objectid';
}
/**
* Checks whether the argument is empty (array without items, object without keys or falsy value).
*/
static isEmpty(data: any): boolean {
if (Array.isArray(data)) {
return data.length === 0;
}
if (Utils.isObject(data)) {
return !Utils.hasObjectKeys(data);
}
return !data;
}
/**
* Gets string name of given class.
*/
static className<T>(classOrName: EntityName<T>): string {
if (Utils.isString(classOrName)) {
return classOrName;
}
return classOrName.name as string;
}
/**
* Tries to detect `ts-node` runtime.
*/
static detectTsNode(): boolean {
/* istanbul ignore next */
return process.argv[0].endsWith('ts-node') // running via ts-node directly
// @ts-ignore
|| !!process[Symbol.for('ts-node.register.instance')] // check if internal ts-node symbol exists
|| !!process.env.TS_JEST // check if ts-jest is used (works only with v27.0.4+)
|| process.argv.slice(1).some(arg => arg.includes('ts-node')) // registering ts-node runner
|| (require.extensions && !!require.extensions['.ts']); // check if the extension is registered
}
/**
* Uses some dark magic to get source path to caller where decorator is used.
* Analyses stack trace of error created inside the function call.
*/
static lookupPathFromDecorator(name: string, stack?: string[]): string {
// use some dark magic to get source path to caller
stack = stack || new Error().stack!.split('\n');
// In some situations (e.g. swc 1.3.4+), the presence of a source map can obscure the call to
// __decorate(), replacing it with the constructor name. To support these cases we look for
// Reflect.decorate() as well.
let line = stack.findIndex(line => line.includes('__decorate') || line.includes('Reflect.decorate'))!;
if (line === -1) {
return name;
}
if (stack[line].includes('Reflect.decorate')) {
line++;
}
if (Utils.normalizePath(stack[line]).includes('node_modules/tslib/tslib')) {
line++;
}
try {
const re = stack[line].match(/\(.+\)/i) ? /\((.*):\d+:\d+\)/ : /at\s*(.*):\d+:\d+$/;
return Utils.normalizePath(stack[line].match(re)![1]);
} catch {
return name;
}
}
/**
* Gets the type of the argument.
*/
static getObjectType(value: any): string {
const objectType = Object.prototype.toString.call(value);
return objectType.match(/\[object (\w+)]/)![1].toLowerCase();
}
/**
* Checks whether the value is POJO (e.g. `{ foo: 'bar' }`, and not instance of `Foo`)
*/
static isPlainObject<T extends Dictionary>(value: any): value is T {
return (
value !== null
&& typeof value === 'object'
&& typeof value.constructor === 'function'
// eslint-disable-next-line no-prototype-builtins
&& (value.constructor.prototype.hasOwnProperty('isPrototypeOf') || Object.getPrototypeOf(value.constructor.prototype) === null)
)
|| (value && Object.getPrototypeOf(value) === null)
|| value instanceof PlainObject;
}
/**
* Executes the `cb` promise serially on every element of the `items` array and returns array of resolved values.
*/
static async runSerial<T = any, U = any>(items: Iterable<U>, cb: (item: U) => Promise<T>): Promise<T[]> {
const ret = [];
for (const item of items) {
ret.push(await cb(item));
}
return ret;
}
static isCollection<T extends object, O extends object = object>(item: any): item is Collection<T, O> {
return item?.__collection;
}
static fileURLToPath(url: string | URL) {
// expose `fileURLToPath` on Utils so that it can be properly mocked in tests
return fileURLToPath(url);
}
/**
* Resolves and normalizes a series of path parts relative to each preceeding part.
* If any part is a `file:` URL, it is converted to a local path. If any part is an
* absolute path, it replaces preceeding paths (similar to `path.resolve` in NodeJS).
* Trailing directory separators are removed, and all directory separators are converted
* to POSIX-style separators (`/`).
*/
static normalizePath(...parts: string[]): string {
let start = 0;
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (isAbsolute(part)) {
start = i;
} else if (part.startsWith('file:')) {
start = i;
parts[i] = Utils.fileURLToPath(part);
}
}
if (start > 0) {
parts = parts.slice(start);
}
let path = parts.join('/').replace(/\\/g, '/').replace(/\/$/, '');
path = normalize(path).replace(/\\/g, '/');
return (path.match(/^[/.]|[a-zA-Z]:/) || path.startsWith('!')) ? path : './' + path;
}
/**
* Determines the relative path between two paths. If either path is a `file:` URL,
* it is converted to a local path.
*/
static relativePath(path: string, relativeTo: string): string {
if (!path) {
return path;
}
path = Utils.normalizePath(path);
if (path.startsWith('.')) {
return path;
}
path = relative(Utils.normalizePath(relativeTo), path);
return Utils.normalizePath(path);
}
/**
* Computes the absolute path to for the given path relative to the provided base directory.
* If either `path` or `baseDir` are `file:` URLs, they are converted to local paths.
*/
static absolutePath(path: string, baseDir = process.cwd()): string {
if (!path) {
return Utils.normalizePath(baseDir);
}
if (!isAbsolute(path) && !path.startsWith('file://')) {
path = baseDir + '/' + path;
}
return Utils.normalizePath(path);
}
static hash(data: string, length?: number): string {
const hash = createHash('md5').update(data).digest('hex');
if (length) {
return hash.substring(0, length);
}
return hash;
}
static runIfNotEmpty(clause: () => any, data: any): void {
if (!Utils.isEmpty(data)) {
clause();
}
}
static defaultValue<T extends Dictionary>(prop: T, option: keyof T, defaultValue: any): void {
prop[option] = option in prop ? prop[option] : defaultValue;
}
static findDuplicates<T>(items: T[]): T[] {
return items.reduce((acc, v, i, arr) => {
return arr.indexOf(v) !== i && acc.indexOf(v) === -1 ? acc.concat(v) : acc;
}, [] as T[]);
}
static randomInt(min: number, max: number): number {
return Math.round(Math.random() * (max - min)) + min;
}
static async pathExists(path: string, options: GlobbyOptions = {}): Promise<boolean> {
if (globby.hasMagic(path)) {
const found = await globby(path, options);
return found.length > 0;
}
return pathExists(path);
}
/**
* Extracts all possible values of a TS enum. Works with both string and numeric enums.
*/
static extractEnumValues(target: Dictionary): (string | number)[] {
const keys = Object.keys(target);
const values = Object.values<string | number>(target);
const numeric = !!values.find(v => typeof v === 'number');
const constEnum = values.length % 2 === 0 // const enum will have even number of items
&& values.slice(0, values.length / 2).every(v => typeof v === 'string') // first half are strings
&& values.slice(values.length / 2).every(v => typeof v === 'number') // second half are numbers
&& this.equals(keys, values.slice(values.length / 2).concat(values.slice(0, values.length / 2)).map(v => '' + v)); // and when swapped, it will match the keys
if (numeric || constEnum) {
return values.filter(val => !keys.includes(val as string));
}
return values;
}
static flatten<T>(arrays: T[][]): T[] {
return ([] as T[]).concat.apply([], arrays);
}
static isOperator(key: PropertyKey, includeGroupOperators = true): boolean {
if (!includeGroupOperators) {
return key in QueryOperator;
}
return key in GroupOperator || key in QueryOperator;
}
static isGroupOperator(key: PropertyKey): boolean {
return key in GroupOperator;
}
static hasNestedKey(object: unknown, key: string): boolean {
if (!object) {
return false;
}
if (Array.isArray(object)) {
return object.some(o => this.hasNestedKey(o, key));
}
if (typeof object === 'object') {
return Object.entries(object).some(([k, v]) => k === key || this.hasNestedKey(v, key));
}
return false;
}
static getGlobalStorage(namespace: string): Dictionary {
const key = `mikro-orm-${namespace}` as keyof typeof globalThis;
(globalThis as Dictionary)[key] = globalThis[key] || {};
return globalThis[key];
}
/**
* Require a module from a specific location
* @param id The module to require
* @param [from] Location to start the node resolution
*/
static requireFrom<T extends Dictionary>(id: string, from = process.cwd()): T {
if (!extname(from)) {
from = join(from, '__fake.js');
}
return createRequire(resolve(from))(id);
}
/**
* Hack to keep dynamic imports even when compiling to CJS.
* We can't use it always, as it would break ts-node.
* @see https://github.com/microsoft/TypeScript/issues/43329#issuecomment-922544562
*/
static async dynamicImport<T = any>(id: string): Promise<T> {
if (id.endsWith('.json') || process.env.TS_JEST) {
return require(id);
}
/* istanbul ignore next */
if (platform() === 'win32') {
try {
id = pathToFileURL(id).toString();
} catch {
// ignore
}
}
/* istanbul ignore next */
return this.dynamicImportProvider(id);
}
/* istanbul ignore next */
static setDynamicImportProvider(provider: (id: string) => Promise<unknown>): void {
this.dynamicImportProvider = provider;
}
static getORMVersion(): string {
/* istanbul ignore next */
try {
// this works with ts-node during development (where we have `src` folder)
// eslint-disable-next-line @typescript-eslint/no-var-requires
return require('../../package.json').version;
} catch {
// this works with node in production build (where we do not have the `src` folder)
// eslint-disable-next-line @typescript-eslint/no-var-requires
return require('../package.json').version;
}
}
/* istanbul ignore next */
static createFunction(context: Map<string, any>, code: string) {
try {
return new Function(...context.keys(), `'use strict';\n` + code)(...context.values());
} catch (e) {
// eslint-disable-next-line no-console
console.error(code);
throw e;
}
}
/* istanbul ignore next */
static callCompiledFunction<T extends unknown[], R>(fn: (...args: T) => R, ...args: T) {
try {
return fn(...args);
} catch (e: any) {
if ([SyntaxError, TypeError, EvalError, ReferenceError].some(t => e instanceof t)) {
const position = e.stack.match(/<anonymous>:(\d+):(\d+)/);
let code = fn.toString();
if (position) {
const lines = code.split('\n').map((line, idx) => {
if (idx === +position[1] - 5) {
return '> ' + line;
}
return ' ' + line;
});
lines.splice(+position[1] - 4, 0, ' '.repeat(+position[2]) + '^');
code = lines.join('\n');
}
// eslint-disable-next-line no-console