@mikro-orm/core 7.0.8 → 7.0.9-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/EntityManager.d.ts +583 -884
  2. package/EntityManager.js +1899 -1926
  3. package/MikroORM.d.ts +74 -103
  4. package/MikroORM.js +179 -178
  5. package/README.md +1 -1
  6. package/cache/CacheAdapter.d.ts +36 -36
  7. package/cache/FileCacheAdapter.d.ts +24 -30
  8. package/cache/FileCacheAdapter.js +78 -80
  9. package/cache/GeneratedCacheAdapter.d.ts +20 -18
  10. package/cache/GeneratedCacheAdapter.js +30 -30
  11. package/cache/MemoryCacheAdapter.d.ts +20 -18
  12. package/cache/MemoryCacheAdapter.js +36 -35
  13. package/cache/NullCacheAdapter.d.ts +16 -16
  14. package/cache/NullCacheAdapter.js +24 -24
  15. package/connections/Connection.d.ts +84 -95
  16. package/connections/Connection.js +168 -165
  17. package/drivers/DatabaseDriver.d.ts +80 -186
  18. package/drivers/DatabaseDriver.js +443 -450
  19. package/drivers/IDatabaseDriver.d.ts +301 -440
  20. package/entity/BaseEntity.d.ts +83 -120
  21. package/entity/BaseEntity.js +43 -43
  22. package/entity/Collection.d.ts +180 -213
  23. package/entity/Collection.js +724 -730
  24. package/entity/EntityAssigner.d.ts +77 -88
  25. package/entity/EntityAssigner.js +230 -231
  26. package/entity/EntityFactory.d.ts +55 -67
  27. package/entity/EntityFactory.js +414 -455
  28. package/entity/EntityHelper.d.ts +23 -35
  29. package/entity/EntityHelper.js +279 -291
  30. package/entity/EntityIdentifier.d.ts +4 -4
  31. package/entity/EntityIdentifier.js +10 -10
  32. package/entity/EntityLoader.d.ts +72 -98
  33. package/entity/EntityLoader.js +761 -792
  34. package/entity/EntityRepository.d.ts +201 -316
  35. package/entity/EntityRepository.js +213 -213
  36. package/entity/PolymorphicRef.d.ts +5 -5
  37. package/entity/PolymorphicRef.js +10 -10
  38. package/entity/Reference.d.ts +83 -127
  39. package/entity/Reference.js +277 -281
  40. package/entity/WrappedEntity.d.ts +72 -115
  41. package/entity/WrappedEntity.js +166 -168
  42. package/entity/defineEntity.d.ts +654 -1359
  43. package/entity/defineEntity.js +518 -527
  44. package/entity/utils.d.ts +3 -13
  45. package/entity/utils.js +73 -71
  46. package/entity/validators.js +43 -43
  47. package/entity/wrap.js +8 -8
  48. package/enums.d.ts +253 -258
  49. package/enums.js +252 -251
  50. package/errors.d.ts +72 -114
  51. package/errors.js +253 -350
  52. package/events/EventManager.d.ts +14 -26
  53. package/events/EventManager.js +77 -79
  54. package/events/EventSubscriber.d.ts +29 -29
  55. package/events/TransactionEventBroadcaster.d.ts +8 -15
  56. package/events/TransactionEventBroadcaster.js +14 -14
  57. package/exceptions.d.ts +40 -23
  58. package/exceptions.js +52 -35
  59. package/hydration/Hydrator.d.ts +17 -42
  60. package/hydration/Hydrator.js +43 -43
  61. package/hydration/ObjectHydrator.d.ts +17 -50
  62. package/hydration/ObjectHydrator.js +418 -483
  63. package/index.d.ts +2 -116
  64. package/index.js +1 -10
  65. package/logging/DefaultLogger.d.ts +32 -34
  66. package/logging/DefaultLogger.js +86 -86
  67. package/logging/Logger.d.ts +41 -41
  68. package/logging/SimpleLogger.d.ts +11 -13
  69. package/logging/SimpleLogger.js +22 -22
  70. package/logging/colors.d.ts +6 -6
  71. package/logging/colors.js +10 -11
  72. package/logging/inspect.js +7 -7
  73. package/metadata/EntitySchema.d.ts +130 -214
  74. package/metadata/EntitySchema.js +412 -411
  75. package/metadata/MetadataDiscovery.d.ts +114 -114
  76. package/metadata/MetadataDiscovery.js +1868 -1944
  77. package/metadata/MetadataProvider.d.ts +26 -29
  78. package/metadata/MetadataProvider.js +97 -95
  79. package/metadata/MetadataStorage.d.ts +32 -38
  80. package/metadata/MetadataStorage.js +118 -118
  81. package/metadata/MetadataValidator.d.ts +39 -39
  82. package/metadata/MetadataValidator.js +338 -381
  83. package/metadata/discover-entities.d.ts +2 -5
  84. package/metadata/discover-entities.js +37 -35
  85. package/metadata/types.d.ts +531 -615
  86. package/naming-strategy/AbstractNamingStrategy.d.ts +39 -54
  87. package/naming-strategy/AbstractNamingStrategy.js +85 -90
  88. package/naming-strategy/EntityCaseNamingStrategy.d.ts +6 -6
  89. package/naming-strategy/EntityCaseNamingStrategy.js +22 -22
  90. package/naming-strategy/MongoNamingStrategy.d.ts +6 -6
  91. package/naming-strategy/MongoNamingStrategy.js +18 -18
  92. package/naming-strategy/NamingStrategy.d.ts +99 -109
  93. package/naming-strategy/UnderscoreNamingStrategy.d.ts +7 -7
  94. package/naming-strategy/UnderscoreNamingStrategy.js +21 -21
  95. package/not-supported.js +4 -7
  96. package/package.json +1 -1
  97. package/platforms/ExceptionConverter.d.ts +1 -1
  98. package/platforms/ExceptionConverter.js +4 -4
  99. package/platforms/Platform.d.ts +303 -312
  100. package/platforms/Platform.js +644 -667
  101. package/serialization/EntitySerializer.d.ts +26 -49
  102. package/serialization/EntitySerializer.js +218 -224
  103. package/serialization/EntityTransformer.d.ts +6 -10
  104. package/serialization/EntityTransformer.js +217 -219
  105. package/serialization/SerializationContext.d.ts +23 -27
  106. package/serialization/SerializationContext.js +105 -105
  107. package/types/ArrayType.d.ts +8 -8
  108. package/types/ArrayType.js +33 -33
  109. package/types/BigIntType.d.ts +10 -17
  110. package/types/BigIntType.js +37 -37
  111. package/types/BlobType.d.ts +3 -3
  112. package/types/BlobType.js +13 -13
  113. package/types/BooleanType.d.ts +4 -4
  114. package/types/BooleanType.js +12 -12
  115. package/types/CharacterType.d.ts +2 -2
  116. package/types/CharacterType.js +6 -6
  117. package/types/DateTimeType.d.ts +5 -5
  118. package/types/DateTimeType.js +15 -15
  119. package/types/DateType.d.ts +5 -5
  120. package/types/DateType.js +15 -15
  121. package/types/DecimalType.d.ts +7 -7
  122. package/types/DecimalType.js +26 -26
  123. package/types/DoubleType.d.ts +3 -3
  124. package/types/DoubleType.js +12 -12
  125. package/types/EnumArrayType.d.ts +5 -5
  126. package/types/EnumArrayType.js +24 -24
  127. package/types/EnumType.d.ts +3 -3
  128. package/types/EnumType.js +11 -11
  129. package/types/FloatType.d.ts +3 -3
  130. package/types/FloatType.js +9 -9
  131. package/types/IntegerType.d.ts +3 -3
  132. package/types/IntegerType.js +9 -9
  133. package/types/IntervalType.d.ts +4 -4
  134. package/types/IntervalType.js +12 -12
  135. package/types/JsonType.d.ts +8 -8
  136. package/types/JsonType.js +32 -32
  137. package/types/MediumIntType.d.ts +1 -1
  138. package/types/MediumIntType.js +3 -3
  139. package/types/SmallIntType.d.ts +3 -3
  140. package/types/SmallIntType.js +9 -9
  141. package/types/StringType.d.ts +4 -4
  142. package/types/StringType.js +12 -12
  143. package/types/TextType.d.ts +3 -3
  144. package/types/TextType.js +9 -9
  145. package/types/TimeType.d.ts +5 -5
  146. package/types/TimeType.js +17 -17
  147. package/types/TinyIntType.d.ts +3 -3
  148. package/types/TinyIntType.js +10 -10
  149. package/types/Type.d.ts +79 -83
  150. package/types/Type.js +82 -82
  151. package/types/Uint8ArrayType.d.ts +4 -4
  152. package/types/Uint8ArrayType.js +21 -21
  153. package/types/UnknownType.d.ts +4 -4
  154. package/types/UnknownType.js +12 -12
  155. package/types/UuidType.d.ts +5 -5
  156. package/types/UuidType.js +19 -19
  157. package/types/index.d.ts +49 -75
  158. package/types/index.js +26 -52
  159. package/typings.d.ts +741 -1254
  160. package/typings.js +233 -244
  161. package/unit-of-work/ChangeSet.d.ts +26 -26
  162. package/unit-of-work/ChangeSet.js +56 -56
  163. package/unit-of-work/ChangeSetComputer.d.ts +12 -12
  164. package/unit-of-work/ChangeSetComputer.js +179 -187
  165. package/unit-of-work/ChangeSetPersister.d.ts +44 -63
  166. package/unit-of-work/ChangeSetPersister.js +423 -446
  167. package/unit-of-work/CommitOrderCalculator.d.ts +40 -40
  168. package/unit-of-work/CommitOrderCalculator.js +88 -89
  169. package/unit-of-work/IdentityMap.d.ts +31 -31
  170. package/unit-of-work/IdentityMap.js +105 -105
  171. package/unit-of-work/UnitOfWork.d.ts +141 -181
  172. package/unit-of-work/UnitOfWork.js +1222 -1236
  173. package/utils/AbstractMigrator.d.ts +91 -111
  174. package/utils/AbstractMigrator.js +275 -275
  175. package/utils/AbstractSchemaGenerator.d.ts +34 -43
  176. package/utils/AbstractSchemaGenerator.js +122 -121
  177. package/utils/AsyncContext.d.ts +3 -3
  178. package/utils/AsyncContext.js +35 -34
  179. package/utils/Configuration.d.ts +808 -852
  180. package/utils/Configuration.js +344 -359
  181. package/utils/Cursor.d.ts +22 -40
  182. package/utils/Cursor.js +127 -135
  183. package/utils/DataloaderUtils.d.ts +43 -58
  184. package/utils/DataloaderUtils.js +198 -203
  185. package/utils/EntityComparator.d.ts +82 -99
  186. package/utils/EntityComparator.js +737 -829
  187. package/utils/NullHighlighter.d.ts +1 -1
  188. package/utils/NullHighlighter.js +3 -3
  189. package/utils/QueryHelper.d.ts +51 -79
  190. package/utils/QueryHelper.js +361 -372
  191. package/utils/RawQueryFragment.d.ts +34 -50
  192. package/utils/RawQueryFragment.js +105 -107
  193. package/utils/RequestContext.d.ts +32 -32
  194. package/utils/RequestContext.js +53 -52
  195. package/utils/TransactionContext.d.ts +16 -16
  196. package/utils/TransactionContext.js +27 -27
  197. package/utils/TransactionManager.d.ts +58 -58
  198. package/utils/TransactionManager.js +197 -199
  199. package/utils/Utils.d.ts +145 -204
  200. package/utils/Utils.js +815 -815
  201. package/utils/clone.js +114 -105
  202. package/utils/env-vars.js +88 -90
  203. package/utils/fs-utils.d.ts +15 -15
  204. package/utils/fs-utils.js +181 -180
  205. package/utils/upsert-utils.d.ts +5 -20
  206. package/utils/upsert-utils.js +116 -114
package/utils/Utils.js CHANGED
@@ -6,851 +6,851 @@ import { Collection } from '../entity/Collection.js';
6
6
  import { EntityHelper } from '../entity/EntityHelper.js';
7
7
  import { Raw, isRaw } from './RawQueryFragment.js';
8
8
  function compareConstructors(a, b) {
9
- if (a.constructor === b.constructor) {
10
- return true;
11
- }
12
- if (!a.constructor) {
13
- return b.constructor === Object;
14
- }
15
- if (!b.constructor) {
16
- return a.constructor === Object;
17
- }
18
- return false;
9
+ if (a.constructor === b.constructor) {
10
+ return true;
11
+ }
12
+ if (!a.constructor) {
13
+ return b.constructor === Object;
14
+ }
15
+ if (!b.constructor) {
16
+ return a.constructor === Object;
17
+ }
18
+ return false;
19
19
  }
20
20
  /** Deeply compares two objects for equality, handling dates, regexes, and raw fragments. */
21
21
  export function compareObjects(a, b) {
22
- if (a === b || (a == null && b == null)) {
22
+ if (a === b || (a == null && b == null)) {
23
+ return true;
24
+ }
25
+ if (!a || !b || typeof a !== 'object' || typeof b !== 'object' || !compareConstructors(a, b)) {
26
+ return false;
27
+ }
28
+ if (isRaw(a) && isRaw(b)) {
29
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
30
+ return a.sql === b.sql && compareArrays(a.params, b.params);
31
+ }
32
+ if (a instanceof Date && b instanceof Date) {
33
+ const timeA = a.getTime();
34
+ const timeB = b.getTime();
35
+ if (isNaN(timeA) || isNaN(timeB)) {
36
+ throw new Error('Comparing invalid dates is not supported');
37
+ }
38
+ return timeA === timeB;
39
+ }
40
+ /* v8 ignore next */
41
+ if ((typeof a === 'function' && typeof b === 'function') ||
42
+ (a instanceof RegExp && b instanceof RegExp) ||
43
+ (a instanceof String && b instanceof String) ||
44
+ (a instanceof Number && b instanceof Number)) {
45
+ return a.toString() === b.toString();
46
+ }
47
+ const keys = Object.keys(a);
48
+ const length = keys.length;
49
+ if (length !== Object.keys(b).length) {
50
+ return false;
51
+ }
52
+ for (let i = length; i-- !== 0;) {
53
+ if (!Object.hasOwn(b, keys[i])) {
54
+ return false;
55
+ }
56
+ }
57
+ for (let i = length; i-- !== 0;) {
58
+ const key = keys[i];
59
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
60
+ if (!equals(a[key], b[key])) {
61
+ return false;
62
+ }
63
+ }
23
64
  return true;
24
- }
25
- if (!a || !b || typeof a !== 'object' || typeof b !== 'object' || !compareConstructors(a, b)) {
26
- return false;
27
- }
28
- if (isRaw(a) && isRaw(b)) {
29
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
30
- return a.sql === b.sql && compareArrays(a.params, b.params);
31
- }
32
- if (a instanceof Date && b instanceof Date) {
33
- const timeA = a.getTime();
34
- const timeB = b.getTime();
35
- if (isNaN(timeA) || isNaN(timeB)) {
36
- throw new Error('Comparing invalid dates is not supported');
37
- }
38
- return timeA === timeB;
39
- }
40
- /* v8 ignore next */
41
- if (
42
- (typeof a === 'function' && typeof b === 'function') ||
43
- (a instanceof RegExp && b instanceof RegExp) ||
44
- (a instanceof String && b instanceof String) ||
45
- (a instanceof Number && b instanceof Number)
46
- ) {
47
- return a.toString() === b.toString();
48
- }
49
- const keys = Object.keys(a);
50
- const length = keys.length;
51
- if (length !== Object.keys(b).length) {
52
- return false;
53
- }
54
- for (let i = length; i-- !== 0; ) {
55
- if (!Object.hasOwn(b, keys[i])) {
56
- return false;
57
- }
58
- }
59
- for (let i = length; i-- !== 0; ) {
60
- const key = keys[i];
61
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
62
- if (!equals(a[key], b[key])) {
63
- return false;
64
- }
65
- }
66
- return true;
67
65
  }
68
66
  /** Compares two arrays element-by-element for deep equality. */
69
67
  export function compareArrays(a, b) {
70
- const length = a.length;
71
- if (length !== b.length) {
72
- return false;
73
- }
74
- for (let i = length; i-- !== 0; ) {
75
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
76
- if (!equals(a[i], b[i])) {
77
- return false;
78
- }
79
- }
80
- return true;
68
+ const length = a.length;
69
+ if (length !== b.length) {
70
+ return false;
71
+ }
72
+ for (let i = length; i-- !== 0;) {
73
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
74
+ if (!equals(a[i], b[i])) {
75
+ return false;
76
+ }
77
+ }
78
+ return true;
81
79
  }
82
80
  /** Compares two boolean values, treating numeric 0/1 as false/true. */
83
81
  export function compareBooleans(a, b) {
84
- a = typeof a === 'number' ? Boolean(a) : a;
85
- b = typeof b === 'number' ? Boolean(b) : b;
86
- return a === b;
82
+ a = typeof a === 'number' ? Boolean(a) : a;
83
+ b = typeof b === 'number' ? Boolean(b) : b;
84
+ return a === b;
87
85
  }
88
86
  /** Compares two byte arrays element-by-element. */
89
87
  export function compareBuffers(a, b) {
90
- const length = a.length;
91
- if (length !== b.length) {
92
- return false;
93
- }
94
- for (let i = length; i-- !== 0; ) {
95
- if (a[i] !== b[i]) {
96
- return false;
88
+ const length = a.length;
89
+ if (length !== b.length) {
90
+ return false;
91
+ }
92
+ for (let i = length; i-- !== 0;) {
93
+ if (a[i] !== b[i]) {
94
+ return false;
95
+ }
97
96
  }
98
- }
99
- return true;
97
+ return true;
100
98
  }
101
99
  /**
102
100
  * Checks if arguments are deeply (but not strictly) equal.
103
101
  */
104
102
  export function equals(a, b) {
105
- if (a === b) {
106
- return true;
107
- }
108
- if (a && b && typeof a === 'object' && typeof b === 'object') {
109
- if (Array.isArray(a)) {
110
- return compareArrays(a, b);
103
+ if (a === b) {
104
+ return true;
111
105
  }
112
- if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
113
- return compareBuffers(a, b);
106
+ if (a && b && typeof a === 'object' && typeof b === 'object') {
107
+ if (Array.isArray(a)) {
108
+ return compareArrays(a, b);
109
+ }
110
+ if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
111
+ return compareBuffers(a, b);
112
+ }
113
+ return compareObjects(a, b);
114
114
  }
115
- return compareObjects(a, b);
116
- }
117
- return Number.isNaN(a) && Number.isNaN(b);
115
+ return Number.isNaN(a) && Number.isNaN(b);
118
116
  }
119
117
  const equalsFn = equals;
120
118
  /** Parses a JSON string safely, returning the original value if parsing fails. */
121
119
  export function parseJsonSafe(value) {
122
- if (typeof value === 'string') {
123
- /* v8 ignore next */
124
- try {
125
- return JSON.parse(value);
126
- } catch {
127
- // ignore and return the value, as sometimes we get the parsed value,
128
- // e.g. when it is a string value in JSON column
129
- }
130
- }
131
- return value;
120
+ if (typeof value === 'string') {
121
+ /* v8 ignore next */
122
+ try {
123
+ return JSON.parse(value);
124
+ }
125
+ catch {
126
+ // ignore and return the value, as sometimes we get the parsed value,
127
+ // e.g. when it is a string value in JSON column
128
+ }
129
+ }
130
+ return value;
132
131
  }
133
132
  /** Collection of general-purpose utility methods used throughout the ORM. */
134
133
  export class Utils {
135
- static PK_SEPARATOR = '~~~';
136
- static #ORM_VERSION = '7.0.8';
137
- /**
138
- * Checks if the argument is instance of `Object`. Returns false for arrays.
139
- */
140
- static isObject(o) {
141
- return !!o && typeof o === 'object' && !Array.isArray(o);
142
- }
143
- /**
144
- * Removes `undefined` properties (recursively) so they are not saved as nulls
145
- */
146
- static dropUndefinedProperties(o, value, visited = new Set()) {
147
- if (Array.isArray(o)) {
148
- for (const item of o) {
149
- Utils.dropUndefinedProperties(item, value, visited);
150
- }
151
- return;
152
- }
153
- if (!Utils.isPlainObject(o) || visited.has(o)) {
154
- return;
155
- }
156
- visited.add(o);
157
- for (const key of Object.keys(o)) {
158
- if (o[key] === value) {
159
- delete o[key];
160
- continue;
161
- }
162
- Utils.dropUndefinedProperties(o[key], value, visited);
163
- }
164
- }
165
- /**
166
- * Returns the number of properties on `obj`. This is 20x faster than Object.keys(obj).length.
167
- * @see https://github.com/deepkit/deepkit-framework/blob/master/packages/core/src/core.ts
168
- */
169
- static getObjectKeysSize(object) {
170
- let size = 0;
171
- for (const key in object) {
172
- if (Object.hasOwn(object, key)) {
173
- size++;
174
- }
175
- }
176
- return size;
177
- }
178
- /**
179
- * Returns true if `obj` has at least one property. This is 20x faster than Object.keys(obj).length.
180
- * @see https://github.com/deepkit/deepkit-framework/blob/master/packages/core/src/core.ts
181
- */
182
- static hasObjectKeys(object) {
183
- for (const key in object) {
184
- if (Object.hasOwn(object, key)) {
185
- return true;
186
- }
134
+ static PK_SEPARATOR = '~~~';
135
+ static #ORM_VERSION = '7.0.9-dev.0';
136
+ /**
137
+ * Checks if the argument is instance of `Object`. Returns false for arrays.
138
+ */
139
+ static isObject(o) {
140
+ return !!o && typeof o === 'object' && !Array.isArray(o);
141
+ }
142
+ /**
143
+ * Removes `undefined` properties (recursively) so they are not saved as nulls
144
+ */
145
+ static dropUndefinedProperties(o, value, visited = new Set()) {
146
+ if (Array.isArray(o)) {
147
+ for (const item of o) {
148
+ Utils.dropUndefinedProperties(item, value, visited);
149
+ }
150
+ return;
151
+ }
152
+ if (!Utils.isPlainObject(o) || visited.has(o)) {
153
+ return;
154
+ }
155
+ visited.add(o);
156
+ for (const key of Object.keys(o)) {
157
+ if (o[key] === value) {
158
+ delete o[key];
159
+ continue;
160
+ }
161
+ Utils.dropUndefinedProperties(o[key], value, visited);
162
+ }
187
163
  }
188
- return false;
189
- }
190
- /**
191
- * Checks if arguments are deeply (but not strictly) equal.
192
- */
193
- static equals(a, b) {
194
- return equalsFn(a, b);
195
- }
196
- /**
197
- * Gets array without duplicates.
198
- */
199
- static unique(items) {
200
- if (items.length < 2) {
201
- return items;
202
- }
203
- return [...new Set(items)];
204
- }
205
- /**
206
- * Merges all sources into the target recursively.
207
- */
208
- static merge(target, ...sources) {
209
- return Utils._merge(target, sources, false);
210
- }
211
- /**
212
- * Merges all sources into the target recursively. Ignores `undefined` values.
213
- */
214
- static mergeConfig(target, ...sources) {
215
- return Utils._merge(target, sources, true);
216
- }
217
- /**
218
- * Merges all sources into the target recursively.
219
- */
220
- static _merge(target, sources, ignoreUndefined) {
221
- if (!sources.length) {
222
- return target;
223
- }
224
- const source = sources.shift();
225
- if (Utils.isObject(target) && Utils.isPlainObject(source)) {
226
- for (const [key, value] of Object.entries(source)) {
227
- if (['__proto__', 'constructor', 'prototype'].includes(key)) {
228
- continue;
229
- }
230
- if (ignoreUndefined && typeof value === 'undefined') {
231
- continue;
232
- }
233
- if (Utils.isPlainObject(value)) {
234
- if (!Utils.isObject(target[key])) {
235
- target[key] = Utils.copy(value);
236
- continue;
237
- }
238
- /* v8 ignore next */
239
- if (!(key in target)) {
240
- Object.assign(target, { [key]: {} });
241
- }
242
- Utils._merge(target[key], [value], ignoreUndefined);
243
- } else {
244
- Object.assign(target, { [key]: value });
245
- }
246
- }
247
- }
248
- return Utils._merge(target, sources, ignoreUndefined);
249
- }
250
- /**
251
- * Creates deep copy of given object.
252
- */
253
- static copy(entity, respectCustomCloneMethod = true) {
254
- return clone(entity, respectCustomCloneMethod);
255
- }
256
- /**
257
- * Normalize the argument to always be an array.
258
- */
259
- static asArray(data, strict = false) {
260
- if (typeof data === 'undefined' && !strict) {
261
- return [];
262
- }
263
- if (this.isIterable(data)) {
264
- return Array.from(data);
265
- }
266
- return [data];
267
- }
268
- /**
269
- * Checks if the value is iterable, but considers strings and buffers as not iterable.
270
- */
271
- static isIterable(value) {
272
- if (value == null || typeof value === 'string' || ArrayBuffer.isView(value)) {
273
- return false;
274
- }
275
- return typeof Object(value)[Symbol.iterator] === 'function';
276
- }
277
- /**
278
- * Renames object key, keeps order of properties.
279
- */
280
- static renameKey(payload, from, to) {
281
- if (Utils.isObject(payload) && from in payload && !(to in payload)) {
282
- for (const key of Object.keys(payload)) {
283
- const value = payload[key];
284
- delete payload[key];
285
- payload[from === key ? to : key] = value;
286
- }
287
- }
288
- }
289
- /**
290
- * Returns array of functions argument names. Uses basic regex for source code analysis, might not work with advanced syntax.
291
- */
292
- static getConstructorParams(func) {
293
- const source = func.toString();
294
- const i = source.indexOf('constructor');
295
- if (i === -1) {
296
- return undefined;
297
- }
298
- const start = source.indexOf('(', i);
299
- if (start === -1) {
300
- return undefined;
301
- }
302
- let depth = 0;
303
- let end = start;
304
- for (; end < source.length; end++) {
305
- if (source[end] === '(') {
306
- depth++;
307
- }
308
- if (source[end] === ')') {
309
- depth--;
310
- }
311
- if (depth === 0) {
312
- break;
313
- }
314
- }
315
- const raw = source.slice(start + 1, end);
316
- return raw
317
- .split(',')
318
- .map(s => s.trim().replace(/=.*$/, '').trim())
319
- .filter(Boolean)
320
- .map(raw => (raw.startsWith('{') && raw.endsWith('}') ? '' : raw));
321
- }
322
- /**
323
- * Checks whether the argument looks like primary key (string, number or ObjectId).
324
- */
325
- static isPrimaryKey(key, allowComposite = false) {
326
- if (['string', 'number', 'bigint'].includes(typeof key)) {
327
- return true;
328
- }
329
- if (allowComposite && Array.isArray(key) && key.every(v => Utils.isPrimaryKey(v, true))) {
330
- return true;
331
- }
332
- if (Utils.isObject(key)) {
333
- if (key.constructor?.name === 'ObjectId') {
334
- return true;
335
- }
336
- if (!Utils.isPlainObject(key) && !Utils.isEntity(key, true)) {
337
- return true;
338
- }
164
+ /**
165
+ * Returns the number of properties on `obj`. This is 20x faster than Object.keys(obj).length.
166
+ * @see https://github.com/deepkit/deepkit-framework/blob/master/packages/core/src/core.ts
167
+ */
168
+ static getObjectKeysSize(object) {
169
+ let size = 0;
170
+ for (const key in object) {
171
+ if (Object.hasOwn(object, key)) {
172
+ size++;
173
+ }
174
+ }
175
+ return size;
176
+ }
177
+ /**
178
+ * Returns true if `obj` has at least one property. This is 20x faster than Object.keys(obj).length.
179
+ * @see https://github.com/deepkit/deepkit-framework/blob/master/packages/core/src/core.ts
180
+ */
181
+ static hasObjectKeys(object) {
182
+ for (const key in object) {
183
+ if (Object.hasOwn(object, key)) {
184
+ return true;
185
+ }
186
+ }
187
+ return false;
339
188
  }
340
- return false;
341
- }
342
- /**
343
- * Extracts primary key from `data`. Accepts objects or primary keys directly.
344
- */
345
- static extractPK(data, meta, strict = false) {
346
- if (Utils.isPrimaryKey(data)) {
347
- return data;
348
- }
349
- if (Utils.isEntity(data, true)) {
350
- const wrapped = helper(data);
351
- if (wrapped.__meta.compositePK) {
352
- return wrapped.getPrimaryKeys();
353
- }
354
- return wrapped.getPrimaryKey();
355
- }
356
- if (strict && meta && Utils.getObjectKeysSize(data) !== meta.primaryKeys.length) {
357
- return null;
358
- }
359
- if (Utils.isPlainObject(data) && meta) {
360
- if (meta.compositePK) {
361
- return this.getCompositeKeyValue(data, meta);
362
- }
363
- return data[meta.primaryKeys[0]] ?? data[meta.serializedPrimaryKey] ?? null;
364
- }
365
- return null;
366
- }
367
- static getCompositeKeyValue(data, meta, convertCustomTypes = false, platform) {
368
- return meta.primaryKeys.map((pk, idx) => {
369
- const value = Array.isArray(data) ? data[idx] : data[pk];
370
- const prop = meta.properties[pk];
371
- if (prop.targetMeta && Utils.isPlainObject(value)) {
372
- return this.getCompositeKeyValue(value, prop.targetMeta);
373
- }
374
- if (prop.customType && platform && convertCustomTypes) {
375
- const method = typeof convertCustomTypes === 'string' ? convertCustomTypes : 'convertToJSValue';
376
- return prop.customType[method](value, platform);
377
- }
378
- return value;
379
- });
380
- }
381
- static getCompositeKeyHash(data, meta, convertCustomTypes = false, platform, flat = false) {
382
- let pks = this.getCompositeKeyValue(data, meta, convertCustomTypes, platform);
383
- if (flat) {
384
- pks = Utils.flatten(pks);
385
- }
386
- return Utils.getPrimaryKeyHash(pks);
387
- }
388
- static getPrimaryKeyHash(pks) {
389
- return pks
390
- .map(pk => {
391
- if (Buffer.isBuffer(pk)) {
392
- return pk.toString('hex');
393
- }
394
- if (pk instanceof Date) {
395
- return pk.toISOString();
396
- }
397
- return pk;
398
- })
399
- .join(this.PK_SEPARATOR);
400
- }
401
- static splitPrimaryKeys(key) {
402
- return key.split(this.PK_SEPARATOR);
403
- }
404
- static getPrimaryKeyValues(entity, meta, allowScalar = false, convertCustomTypes = false) {
405
- /* v8 ignore next */
406
- if (entity == null) {
407
- return entity;
408
- }
409
- function toArray(val) {
410
- if (Utils.isPlainObject(val)) {
411
- return Object.values(val).flatMap(v => toArray(v));
412
- }
413
- return val;
414
- }
415
- let pk;
416
- if (Utils.isEntity(entity, true)) {
417
- pk = helper(entity).getPrimaryKey(convertCustomTypes);
418
- } else {
419
- pk = meta.primaryKeys.reduce((o, pk) => {
420
- const targetMeta = meta.properties[pk].targetMeta;
421
- if (targetMeta && Utils.isPlainObject(entity[pk])) {
422
- o[pk] = Utils.getPrimaryKeyValues(entity[pk], targetMeta, allowScalar, convertCustomTypes);
423
- } else {
424
- o[pk] = entity[pk];
425
- }
426
- return o;
427
- }, {});
428
- }
429
- if (meta.primaryKeys.length > 1) {
430
- return toArray(pk);
431
- }
432
- if (allowScalar) {
433
- if (Utils.isPlainObject(pk)) {
434
- return pk[meta.primaryKeys[0]];
435
- }
436
- return pk;
437
- }
438
- return [pk];
439
- }
440
- static getPrimaryKeyCond(entity, primaryKeys) {
441
- const cond = primaryKeys.reduce((o, pk) => {
442
- o[pk] = Utils.extractPK(entity[pk]);
443
- return o;
444
- }, {});
445
- if (Object.values(cond).some(v => v === null)) {
446
- return null;
447
- }
448
- return cond;
449
- }
450
- /**
451
- * Maps nested FKs from `[1, 2, 3]` to `[1, [2, 3]]`.
452
- */
453
- static mapFlatCompositePrimaryKey(fk, prop, fieldNames = prop.fieldNames, idx = 0) {
454
- if (!prop.targetMeta) {
455
- return fk[idx++];
456
- }
457
- const parts = [];
458
- for (const pk of prop.targetMeta.getPrimaryProps()) {
459
- parts.push(this.mapFlatCompositePrimaryKey(fk, pk, fieldNames, idx));
460
- idx += pk.fieldNames.length;
461
- }
462
- if (parts.length < 2) {
463
- return parts[0];
464
- }
465
- return parts;
466
- }
467
- static getPrimaryKeyCondFromArray(pks, meta) {
468
- return meta.getPrimaryProps().reduce((o, pk, idx) => {
469
- if (Array.isArray(pks[idx]) && pk.targetMeta) {
470
- o[pk.name] = pks[idx];
471
- } else {
472
- o[pk.name] = Utils.extractPK(pks[idx], meta);
473
- }
474
- return o;
475
- }, {});
476
- }
477
- static getOrderedPrimaryKeys(id, meta, platform, convertCustomTypes = false, allowScalar = false) {
478
- const data = Utils.isPrimaryKey(id) ? { [meta.primaryKeys[0]]: id } : id;
479
- const pks = meta.primaryKeys.map((pk, idx) => {
480
- const prop = meta.properties[pk];
481
- // `data` can be a composite PK in form of array of PKs, or a DTO
482
- let value = Array.isArray(data) ? data[idx] : (data[pk] ?? data);
483
- if (convertCustomTypes && platform && prop.customType && !prop.targetMeta) {
484
- value = prop.customType.convertToJSValue(value, platform);
485
- }
486
- if (prop.kind !== ReferenceKind.SCALAR && prop.targetMeta) {
487
- const value2 = this.getOrderedPrimaryKeys(value, prop.targetMeta, platform, convertCustomTypes, allowScalar);
488
- value = value2.length > 1 ? value2 : value2[0];
489
- }
490
- return value;
491
- });
492
- if (allowScalar && pks.length === 1) {
493
- return pks[0];
494
- }
495
- // we need to flatten the PKs as composite PKs can be build from another composite PKs
496
- // and this method is used to get the PK hash in identity map, that expects flat array
497
- return Utils.flatten(pks);
498
- }
499
- /**
500
- * Checks whether given object is an entity instance.
501
- */
502
- static isEntity(data, allowReference = false) {
503
- if (!Utils.isObject(data)) {
504
- return false;
505
- }
506
- if (allowReference && Reference.isReference(data)) {
507
- return true;
508
- }
509
- return EntityHelper.isEntity(data);
510
- }
511
- /**
512
- * Checks whether given object is a scalar reference.
513
- */
514
- static isScalarReference(data) {
515
- return ScalarReference.isScalarReference(data);
516
- }
517
- /**
518
- * Checks whether the argument is empty (array without items, object without keys or falsy value).
519
- */
520
- static isEmpty(data) {
521
- if (Array.isArray(data)) {
522
- return data.length === 0;
523
- }
524
- if (Utils.isObject(data)) {
525
- return !Utils.hasObjectKeys(data);
526
- }
527
- return !data;
528
- }
529
- /**
530
- * Gets string name of given class.
531
- */
532
- static className(classOrName) {
533
- if (typeof classOrName === 'string') {
534
- return classOrName;
535
- }
536
- return classOrName.name;
537
- }
538
- static extractChildElements(items, prefix, allSymbol) {
539
- return items
540
- .filter(field => field === allSymbol || field.startsWith(`${prefix}.`))
541
- .map(field => (field === allSymbol ? allSymbol : field.substring(prefix.length + 1)));
542
- }
543
- /**
544
- * Tries to detect TypeScript support.
545
- */
546
- static detectTypeScriptSupport() {
547
- /* v8 ignore next */
548
- const process = globalThis.process ?? {};
549
- /* v8 ignore next */
550
- return (
551
- process.argv?.[0]?.endsWith('ts-node') || // running via ts-node directly
552
- !!process.env?.MIKRO_ORM_CLI_ALWAYS_ALLOW_TS || // forced explicitly or enabled via `registerTypeScriptSupport()`
553
- !!process.env?.TS_JEST || // check if ts-jest is used
554
- !!process.env?.VITEST || // check if vitest is used
555
- !!process.versions?.bun || // check if bun is used
556
- process.argv?.slice(1).some(arg => /\.([mc]?ts|tsx)$/.exec(arg)) || // executing `.ts` file
557
- process.execArgv?.some(arg => {
558
- return (
559
- arg.includes('ts-node') || // check for ts-node loader
560
- arg.includes('@swc-node/register') || // check for swc-node/register loader
561
- arg.includes('node_modules/tsx/') || // check for tsx loader
562
- arg.includes('@oxc-node/core') // check for oxc-node loader
563
- );
564
- })
565
- );
566
- }
567
- /**
568
- * Gets the type of the argument.
569
- */
570
- static getObjectType(value) {
571
- const simple = typeof value;
572
- if (['string', 'number', 'boolean', 'bigint'].includes(simple)) {
573
- return simple;
574
- }
575
- const objectType = Object.prototype.toString.call(value);
576
- const type = /^\[object (.+)]$/.exec(objectType)[1];
577
- if (type === 'Uint8Array') {
578
- return 'Buffer';
579
- }
580
- return type;
581
- }
582
- /**
583
- * Checks whether the value is POJO (e.g. `{ foo: 'bar' }`, and not instance of `Foo`)
584
- */
585
- static isPlainObject(value) {
586
- return (
587
- (value !== null &&
588
- typeof value === 'object' &&
589
- typeof value.constructor === 'function' &&
590
- (Object.hasOwn(value.constructor.prototype, 'isPrototypeOf') ||
591
- Object.getPrototypeOf(value.constructor.prototype) === null)) ||
592
- (value && Object.getPrototypeOf(value) === null) ||
593
- value instanceof PlainObject
594
- );
595
- }
596
- /**
597
- * Executes the `cb` promise serially on every element of the `items` array and returns array of resolved values.
598
- */
599
- static async runSerial(items, cb) {
600
- const ret = [];
601
- for (const item of items) {
602
- ret.push(await cb(item));
603
- }
604
- return ret;
605
- }
606
- static isCollection(item) {
607
- return Collection.isCollection(item);
608
- }
609
- // FNV-1a 64-bit
610
- static hash(data, length) {
611
- let h1 = 0xcbf29ce484222325n;
612
- for (let i = 0; i < data.length; i++) {
613
- h1 ^= BigInt(data.charCodeAt(i));
614
- h1 = (h1 * 0x100000001b3n) & 0xffffffffffffffffn;
615
- }
616
- const hash = h1.toString(16).padStart(16, '0');
617
- if (length) {
618
- return hash.substring(0, length);
619
- }
620
- return hash;
621
- }
622
- static runIfNotEmpty(clause, data) {
623
- if (!Utils.isEmpty(data)) {
624
- clause();
625
- }
626
- }
627
- static defaultValue(prop, option, defaultValue) {
628
- prop[option] = option in prop ? prop[option] : defaultValue;
629
- }
630
- static findDuplicates(items) {
631
- return items.reduce((acc, v, i, arr) => {
632
- return arr.indexOf(v) !== i && !acc.includes(v) ? acc.concat(v) : acc;
633
- }, []);
634
- }
635
- static removeDuplicates(items) {
636
- const ret = [];
637
- const contains = (arr, val) => !!arr.find(v => equals(val, v));
638
- for (const item of items) {
639
- if (!contains(ret, item)) {
640
- ret.push(item);
641
- }
642
- }
643
- return ret;
644
- }
645
- static randomInt(min, max) {
646
- return Math.round(Math.random() * (max - min)) + min;
647
- }
648
- /**
649
- * Extracts all possible values of a TS enum. Works with both string and numeric enums.
650
- */
651
- static extractEnumValues(target) {
652
- const keys = Object.keys(target);
653
- const values = Object.values(target);
654
- const numeric = !!values.find(v => typeof v === 'number');
655
- const constEnum =
656
- values.length % 2 === 0 && // const enum will have even number of items
657
- values.slice(0, values.length / 2).every(v => typeof v === 'string') && // first half are strings
658
- values.slice(values.length / 2).every(v => typeof v === 'number') && // second half are numbers
659
- this.equals(
660
- keys,
661
- values
662
- .slice(values.length / 2)
663
- .concat(values.slice(0, values.length / 2))
664
- .map(v => '' + v),
665
- ); // and when swapped, it will match the keys
666
- if (numeric || constEnum) {
667
- return values.filter(val => !keys.includes(val));
668
- }
669
- return values;
670
- }
671
- static flatten(arrays, deep) {
672
- return arrays.flatMap(v => (deep && Array.isArray(v) ? this.flatten(v, true) : v));
673
- }
674
- static isOperator(key, includeGroupOperators = true) {
675
- if (!includeGroupOperators) {
676
- return key in QueryOperator;
677
- }
678
- return key in GroupOperator || key in QueryOperator;
679
- }
680
- static hasNestedKey(object, key) {
681
- if (!object) {
682
- return false;
683
- }
684
- if (Array.isArray(object)) {
685
- return object.some(o => this.hasNestedKey(o, key));
686
- }
687
- if (typeof object === 'object') {
688
- return Object.entries(object).some(([k, v]) => k === key || this.hasNestedKey(v, key));
189
+ /**
190
+ * Checks if arguments are deeply (but not strictly) equal.
191
+ */
192
+ static equals(a, b) {
193
+ return equalsFn(a, b);
194
+ }
195
+ /**
196
+ * Gets array without duplicates.
197
+ */
198
+ static unique(items) {
199
+ if (items.length < 2) {
200
+ return items;
201
+ }
202
+ return [...new Set(items)];
203
+ }
204
+ /**
205
+ * Merges all sources into the target recursively.
206
+ */
207
+ static merge(target, ...sources) {
208
+ return Utils._merge(target, sources, false);
209
+ }
210
+ /**
211
+ * Merges all sources into the target recursively. Ignores `undefined` values.
212
+ */
213
+ static mergeConfig(target, ...sources) {
214
+ return Utils._merge(target, sources, true);
215
+ }
216
+ /**
217
+ * Merges all sources into the target recursively.
218
+ */
219
+ static _merge(target, sources, ignoreUndefined) {
220
+ if (!sources.length) {
221
+ return target;
222
+ }
223
+ const source = sources.shift();
224
+ if (Utils.isObject(target) && Utils.isPlainObject(source)) {
225
+ for (const [key, value] of Object.entries(source)) {
226
+ if (['__proto__', 'constructor', 'prototype'].includes(key)) {
227
+ continue;
228
+ }
229
+ if (ignoreUndefined && typeof value === 'undefined') {
230
+ continue;
231
+ }
232
+ if (Utils.isPlainObject(value)) {
233
+ if (!Utils.isObject(target[key])) {
234
+ target[key] = Utils.copy(value);
235
+ continue;
236
+ }
237
+ /* v8 ignore next */
238
+ if (!(key in target)) {
239
+ Object.assign(target, { [key]: {} });
240
+ }
241
+ Utils._merge(target[key], [value], ignoreUndefined);
242
+ }
243
+ else {
244
+ Object.assign(target, { [key]: value });
245
+ }
246
+ }
247
+ }
248
+ return Utils._merge(target, sources, ignoreUndefined);
249
+ }
250
+ /**
251
+ * Creates deep copy of given object.
252
+ */
253
+ static copy(entity, respectCustomCloneMethod = true) {
254
+ return clone(entity, respectCustomCloneMethod);
255
+ }
256
+ /**
257
+ * Normalize the argument to always be an array.
258
+ */
259
+ static asArray(data, strict = false) {
260
+ if (typeof data === 'undefined' && !strict) {
261
+ return [];
262
+ }
263
+ if (this.isIterable(data)) {
264
+ return Array.from(data);
265
+ }
266
+ return [data];
267
+ }
268
+ /**
269
+ * Checks if the value is iterable, but considers strings and buffers as not iterable.
270
+ */
271
+ static isIterable(value) {
272
+ if (value == null || typeof value === 'string' || ArrayBuffer.isView(value)) {
273
+ return false;
274
+ }
275
+ return typeof Object(value)[Symbol.iterator] === 'function';
276
+ }
277
+ /**
278
+ * Renames object key, keeps order of properties.
279
+ */
280
+ static renameKey(payload, from, to) {
281
+ if (Utils.isObject(payload) && from in payload && !(to in payload)) {
282
+ for (const key of Object.keys(payload)) {
283
+ const value = payload[key];
284
+ delete payload[key];
285
+ payload[from === key ? to : key] = value;
286
+ }
287
+ }
689
288
  }
690
- return false;
691
- }
692
- static getORMVersion() {
693
- return this.#ORM_VERSION;
694
- }
695
- static createFunction(context, code, compiledFunctions, key) {
696
- if (key && compiledFunctions?.[key]) {
697
- return compiledFunctions[key](...context.values());
698
- }
699
- try {
700
- // eslint-disable-next-line @typescript-eslint/no-implied-eval
701
- return new Function(...context.keys(), `'use strict';\n` + code)(...context.values());
702
- /* v8 ignore next */
703
- } catch (e) {
704
- // eslint-disable-next-line no-console
705
- console.error(code);
706
- throw e;
707
- }
708
- }
709
- static callCompiledFunction(fn, ...args) {
710
- try {
711
- return fn(...args);
712
- } catch (e) {
713
- /* v8 ignore next */
714
- if ([SyntaxError, TypeError, EvalError, ReferenceError].some(t => e instanceof t)) {
715
- const position = e.stack.match(/<anonymous>:(\d+):(\d+)/);
716
- let code = fn.toString();
717
- if (position) {
718
- const lines = code.split('\n').map((line, idx) => {
719
- if (idx === +position[1] - 5) {
720
- return '> ' + line;
721
- }
722
- return ' ' + line;
723
- });
724
- lines.splice(+position[1] - 4, 0, ' '.repeat(+position[2]) + '^');
725
- code = lines.join('\n');
726
- }
727
- // eslint-disable-next-line no-console
728
- console.error(`JIT runtime error: ${e.message}\n\n${code}`);
729
- }
730
- throw e;
731
- }
732
- }
733
- static unwrapProperty(entity, meta, prop, payload = false) {
734
- let p = prop;
735
- const path = [];
736
- if (!prop.object && !prop.array && !prop.embedded) {
737
- return entity[prop.name] != null ? [[entity[prop.name], []]] : [];
738
- }
739
- while (p.embedded) {
740
- const child = meta.properties[p.embedded[0]];
741
- if (payload && !child.object && !child.array) {
742
- break;
743
- }
744
- path.shift();
745
- path.unshift(p.embedded[0], p.embedded[1]);
746
- p = child;
747
- }
748
- const ret = [];
749
- const follow = (t, idx = 0, i = []) => {
750
- const k = path[idx];
751
- if (Array.isArray(t)) {
752
- for (const t1 of t) {
753
- const ii = t.indexOf(t1);
754
- follow(t1, idx, [...i, ii]);
755
- }
756
- return;
757
- }
758
- if (t == null) {
759
- return;
760
- }
761
- const target = t[k];
762
- if (path[++idx]) {
763
- follow(target, idx, i);
764
- } else if (target != null) {
765
- ret.push([target, i]);
766
- }
767
- };
768
- follow(entity);
769
- return ret;
770
- }
771
- static setPayloadProperty(entity, meta, prop, value, idx) {
772
- if (!prop.object && !prop.array && !prop.embedded) {
773
- entity[prop.name] = value;
774
- return;
775
- }
776
- let target = entity;
777
- let p = prop;
778
- const path = [];
779
- while (p.embedded) {
780
- path.shift();
781
- path.unshift(p.embedded[0], p.embedded[1]);
782
- const prev = p;
783
- p = meta.properties[p.embedded[0]];
784
- if (!p.object) {
785
- path.shift();
786
- path[0] = prev.name;
787
- break;
788
- }
789
- }
790
- let j = 0;
791
- for (const k of path) {
792
- const i = path.indexOf(k);
793
- if (i === path.length - 1) {
794
- if (Array.isArray(target)) {
795
- target[idx[j++]][k] = value;
796
- } else {
797
- target[k] = value;
798
- }
799
- } else {
800
- if (Array.isArray(target)) {
801
- target = target[idx[j++]][k];
802
- } else {
803
- target = target[k];
804
- }
805
- }
806
- }
807
- }
808
- static async tryImport({ module, warning }) {
809
- try {
810
- return await import(module);
811
- } catch (err) {
812
- if (warning && err.code === 'ERR_MODULE_NOT_FOUND') {
813
- // eslint-disable-next-line no-console
814
- console.warn(warning);
815
- }
816
- return undefined;
817
- }
818
- }
819
- static xor(a, b) {
820
- return (a || b) && !(a && b);
821
- }
822
- static keys(obj) {
823
- return Object.keys(obj);
824
- }
825
- static values(obj) {
826
- return Object.values(obj);
827
- }
828
- static entries(obj) {
829
- return Object.entries(obj);
830
- }
831
- static primaryKeyToObject(meta, primaryKey, visible) {
832
- const pks =
833
- meta.compositePK && Utils.isPlainObject(primaryKey) ? Object.values(primaryKey) : Utils.asArray(primaryKey);
834
- const pkProps = meta.getPrimaryProps();
835
- return meta.primaryKeys.reduce((o, pk, idx) => {
836
- const pkProp = pkProps[idx];
837
- if (visible && !visible.includes(pkProp.name)) {
838
- return o;
839
- }
840
- if (Utils.isPlainObject(pks[idx]) && pkProp.targetMeta) {
841
- o[pk] = Utils.getOrderedPrimaryKeys(pks[idx], pkProp.targetMeta);
842
- return o;
843
- }
844
- o[pk] = pks[idx];
845
- return o;
846
- }, {});
847
- }
848
- static getObjectQueryKeys(obj) {
849
- return Reflect.ownKeys(obj).filter(key => {
850
- if (!Object.prototype.propertyIsEnumerable.call(obj, key)) {
289
+ /**
290
+ * Returns array of functions argument names. Uses basic regex for source code analysis, might not work with advanced syntax.
291
+ */
292
+ static getConstructorParams(func) {
293
+ const source = func.toString();
294
+ const i = source.indexOf('constructor');
295
+ if (i === -1) {
296
+ return undefined;
297
+ }
298
+ const start = source.indexOf('(', i);
299
+ if (start === -1) {
300
+ return undefined;
301
+ }
302
+ let depth = 0;
303
+ let end = start;
304
+ for (; end < source.length; end++) {
305
+ if (source[end] === '(') {
306
+ depth++;
307
+ }
308
+ if (source[end] === ')') {
309
+ depth--;
310
+ }
311
+ if (depth === 0) {
312
+ break;
313
+ }
314
+ }
315
+ const raw = source.slice(start + 1, end);
316
+ return raw
317
+ .split(',')
318
+ .map(s => s.trim().replace(/=.*$/, '').trim())
319
+ .filter(Boolean)
320
+ .map(raw => (raw.startsWith('{') && raw.endsWith('}') ? '' : raw));
321
+ }
322
+ /**
323
+ * Checks whether the argument looks like primary key (string, number or ObjectId).
324
+ */
325
+ static isPrimaryKey(key, allowComposite = false) {
326
+ if (['string', 'number', 'bigint'].includes(typeof key)) {
327
+ return true;
328
+ }
329
+ if (allowComposite && Array.isArray(key) && key.every(v => Utils.isPrimaryKey(v, true))) {
330
+ return true;
331
+ }
332
+ if (Utils.isObject(key)) {
333
+ if (key.constructor?.name === 'ObjectId') {
334
+ return true;
335
+ }
336
+ if (!Utils.isPlainObject(key) && !Utils.isEntity(key, true)) {
337
+ return true;
338
+ }
339
+ }
340
+ return false;
341
+ }
342
+ /**
343
+ * Extracts primary key from `data`. Accepts objects or primary keys directly.
344
+ */
345
+ static extractPK(data, meta, strict = false) {
346
+ if (Utils.isPrimaryKey(data)) {
347
+ return data;
348
+ }
349
+ if (Utils.isEntity(data, true)) {
350
+ const wrapped = helper(data);
351
+ if (wrapped.__meta.compositePK) {
352
+ return wrapped.getPrimaryKeys();
353
+ }
354
+ return wrapped.getPrimaryKey();
355
+ }
356
+ if (strict && meta && Utils.getObjectKeysSize(data) !== meta.primaryKeys.length) {
357
+ return null;
358
+ }
359
+ if (Utils.isPlainObject(data) && meta) {
360
+ if (meta.compositePK) {
361
+ return this.getCompositeKeyValue(data, meta);
362
+ }
363
+ return data[meta.primaryKeys[0]] ?? data[meta.serializedPrimaryKey] ?? null;
364
+ }
365
+ return null;
366
+ }
367
+ static getCompositeKeyValue(data, meta, convertCustomTypes = false, platform) {
368
+ return meta.primaryKeys.map((pk, idx) => {
369
+ const value = Array.isArray(data) ? data[idx] : data[pk];
370
+ const prop = meta.properties[pk];
371
+ if (prop.targetMeta && Utils.isPlainObject(value)) {
372
+ return this.getCompositeKeyValue(value, prop.targetMeta);
373
+ }
374
+ if (prop.customType && platform && convertCustomTypes) {
375
+ const method = typeof convertCustomTypes === 'string' ? convertCustomTypes : 'convertToJSValue';
376
+ return prop.customType[method](value, platform);
377
+ }
378
+ return value;
379
+ });
380
+ }
381
+ static getCompositeKeyHash(data, meta, convertCustomTypes = false, platform, flat = false) {
382
+ let pks = this.getCompositeKeyValue(data, meta, convertCustomTypes, platform);
383
+ if (flat) {
384
+ pks = Utils.flatten(pks);
385
+ }
386
+ return Utils.getPrimaryKeyHash(pks);
387
+ }
388
+ static getPrimaryKeyHash(pks) {
389
+ return pks
390
+ .map(pk => {
391
+ if (Buffer.isBuffer(pk)) {
392
+ return pk.toString('hex');
393
+ }
394
+ if (pk instanceof Date) {
395
+ return pk.toISOString();
396
+ }
397
+ return pk;
398
+ })
399
+ .join(this.PK_SEPARATOR);
400
+ }
401
+ static splitPrimaryKeys(key) {
402
+ return key.split(this.PK_SEPARATOR);
403
+ }
404
+ static getPrimaryKeyValues(entity, meta, allowScalar = false, convertCustomTypes = false) {
405
+ /* v8 ignore next */
406
+ if (entity == null) {
407
+ return entity;
408
+ }
409
+ function toArray(val) {
410
+ if (Utils.isPlainObject(val)) {
411
+ return Object.values(val).flatMap(v => toArray(v));
412
+ }
413
+ return val;
414
+ }
415
+ let pk;
416
+ if (Utils.isEntity(entity, true)) {
417
+ pk = helper(entity).getPrimaryKey(convertCustomTypes);
418
+ }
419
+ else {
420
+ pk = meta.primaryKeys.reduce((o, pk) => {
421
+ const targetMeta = meta.properties[pk].targetMeta;
422
+ if (targetMeta && Utils.isPlainObject(entity[pk])) {
423
+ o[pk] = Utils.getPrimaryKeyValues(entity[pk], targetMeta, allowScalar, convertCustomTypes);
424
+ }
425
+ else {
426
+ o[pk] = entity[pk];
427
+ }
428
+ return o;
429
+ }, {});
430
+ }
431
+ if (meta.primaryKeys.length > 1) {
432
+ return toArray(pk);
433
+ }
434
+ if (allowScalar) {
435
+ if (Utils.isPlainObject(pk)) {
436
+ return pk[meta.primaryKeys[0]];
437
+ }
438
+ return pk;
439
+ }
440
+ return [pk];
441
+ }
442
+ static getPrimaryKeyCond(entity, primaryKeys) {
443
+ const cond = primaryKeys.reduce((o, pk) => {
444
+ o[pk] = Utils.extractPK(entity[pk]);
445
+ return o;
446
+ }, {});
447
+ if (Object.values(cond).some(v => v === null)) {
448
+ return null;
449
+ }
450
+ return cond;
451
+ }
452
+ /**
453
+ * Maps nested FKs from `[1, 2, 3]` to `[1, [2, 3]]`.
454
+ */
455
+ static mapFlatCompositePrimaryKey(fk, prop, fieldNames = prop.fieldNames, idx = 0) {
456
+ if (!prop.targetMeta) {
457
+ return fk[idx++];
458
+ }
459
+ const parts = [];
460
+ for (const pk of prop.targetMeta.getPrimaryProps()) {
461
+ parts.push(this.mapFlatCompositePrimaryKey(fk, pk, fieldNames, idx));
462
+ idx += pk.fieldNames.length;
463
+ }
464
+ if (parts.length < 2) {
465
+ return parts[0];
466
+ }
467
+ return parts;
468
+ }
469
+ static getPrimaryKeyCondFromArray(pks, meta) {
470
+ return meta.getPrimaryProps().reduce((o, pk, idx) => {
471
+ if (Array.isArray(pks[idx]) && pk.targetMeta) {
472
+ o[pk.name] = pks[idx];
473
+ }
474
+ else {
475
+ o[pk.name] = Utils.extractPK(pks[idx], meta);
476
+ }
477
+ return o;
478
+ }, {});
479
+ }
480
+ static getOrderedPrimaryKeys(id, meta, platform, convertCustomTypes = false, allowScalar = false) {
481
+ const data = (Utils.isPrimaryKey(id) ? { [meta.primaryKeys[0]]: id } : id);
482
+ const pks = meta.primaryKeys.map((pk, idx) => {
483
+ const prop = meta.properties[pk];
484
+ // `data` can be a composite PK in form of array of PKs, or a DTO
485
+ let value = Array.isArray(data) ? data[idx] : (data[pk] ?? data);
486
+ if (convertCustomTypes && platform && prop.customType && !prop.targetMeta) {
487
+ value = prop.customType.convertToJSValue(value, platform);
488
+ }
489
+ if (prop.kind !== ReferenceKind.SCALAR && prop.targetMeta) {
490
+ const value2 = this.getOrderedPrimaryKeys(value, prop.targetMeta, platform, convertCustomTypes, allowScalar);
491
+ value = value2.length > 1 ? value2 : value2[0];
492
+ }
493
+ return value;
494
+ });
495
+ if (allowScalar && pks.length === 1) {
496
+ return pks[0];
497
+ }
498
+ // we need to flatten the PKs as composite PKs can be build from another composite PKs
499
+ // and this method is used to get the PK hash in identity map, that expects flat array
500
+ return Utils.flatten(pks);
501
+ }
502
+ /**
503
+ * Checks whether given object is an entity instance.
504
+ */
505
+ static isEntity(data, allowReference = false) {
506
+ if (!Utils.isObject(data)) {
507
+ return false;
508
+ }
509
+ if (allowReference && Reference.isReference(data)) {
510
+ return true;
511
+ }
512
+ return EntityHelper.isEntity(data);
513
+ }
514
+ /**
515
+ * Checks whether given object is a scalar reference.
516
+ */
517
+ static isScalarReference(data) {
518
+ return ScalarReference.isScalarReference(data);
519
+ }
520
+ /**
521
+ * Checks whether the argument is empty (array without items, object without keys or falsy value).
522
+ */
523
+ static isEmpty(data) {
524
+ if (Array.isArray(data)) {
525
+ return data.length === 0;
526
+ }
527
+ if (Utils.isObject(data)) {
528
+ return !Utils.hasObjectKeys(data);
529
+ }
530
+ return !data;
531
+ }
532
+ /**
533
+ * Gets string name of given class.
534
+ */
535
+ static className(classOrName) {
536
+ if (typeof classOrName === 'string') {
537
+ return classOrName;
538
+ }
539
+ return classOrName.name;
540
+ }
541
+ static extractChildElements(items, prefix, allSymbol) {
542
+ return items
543
+ .filter(field => field === allSymbol || field.startsWith(`${prefix}.`))
544
+ .map(field => (field === allSymbol ? allSymbol : field.substring(prefix.length + 1)));
545
+ }
546
+ /**
547
+ * Tries to detect TypeScript support.
548
+ */
549
+ static detectTypeScriptSupport() {
550
+ /* v8 ignore next */
551
+ const process = globalThis.process ?? {};
552
+ /* v8 ignore next */
553
+ return (process.argv?.[0]?.endsWith('ts-node') || // running via ts-node directly
554
+ !!process.env?.MIKRO_ORM_CLI_ALWAYS_ALLOW_TS || // forced explicitly or enabled via `registerTypeScriptSupport()`
555
+ !!process.env?.TS_JEST || // check if ts-jest is used
556
+ !!process.env?.VITEST || // check if vitest is used
557
+ !!process.versions?.bun || // check if bun is used
558
+ process.argv?.slice(1).some(arg => /\.([mc]?ts|tsx)$/.exec(arg)) || // executing `.ts` file
559
+ process.execArgv?.some(arg => {
560
+ return (arg.includes('ts-node') || // check for ts-node loader
561
+ arg.includes('@swc-node/register') || // check for swc-node/register loader
562
+ arg.includes('node_modules/tsx/') || // check for tsx loader
563
+ arg.includes('@oxc-node/core') // check for oxc-node loader
564
+ );
565
+ }));
566
+ }
567
+ /**
568
+ * Gets the type of the argument.
569
+ */
570
+ static getObjectType(value) {
571
+ const simple = typeof value;
572
+ if (['string', 'number', 'boolean', 'bigint'].includes(simple)) {
573
+ return simple;
574
+ }
575
+ const objectType = Object.prototype.toString.call(value);
576
+ const type = /^\[object (.+)]$/.exec(objectType)[1];
577
+ if (type === 'Uint8Array') {
578
+ return 'Buffer';
579
+ }
580
+ return type;
581
+ }
582
+ /**
583
+ * Checks whether the value is POJO (e.g. `{ foo: 'bar' }`, and not instance of `Foo`)
584
+ */
585
+ static isPlainObject(value) {
586
+ return ((value !== null &&
587
+ typeof value === 'object' &&
588
+ typeof value.constructor === 'function' &&
589
+ (Object.hasOwn(value.constructor.prototype, 'isPrototypeOf') ||
590
+ Object.getPrototypeOf(value.constructor.prototype) === null)) ||
591
+ (value && Object.getPrototypeOf(value) === null) ||
592
+ value instanceof PlainObject);
593
+ }
594
+ /**
595
+ * Executes the `cb` promise serially on every element of the `items` array and returns array of resolved values.
596
+ */
597
+ static async runSerial(items, cb) {
598
+ const ret = [];
599
+ for (const item of items) {
600
+ ret.push(await cb(item));
601
+ }
602
+ return ret;
603
+ }
604
+ static isCollection(item) {
605
+ return Collection.isCollection(item);
606
+ }
607
+ // FNV-1a 64-bit
608
+ static hash(data, length) {
609
+ let h1 = 0xcbf29ce484222325n;
610
+ for (let i = 0; i < data.length; i++) {
611
+ h1 ^= BigInt(data.charCodeAt(i));
612
+ h1 = (h1 * 0x100000001b3n) & 0xffffffffffffffffn;
613
+ }
614
+ const hash = h1.toString(16).padStart(16, '0');
615
+ if (length) {
616
+ return hash.substring(0, length);
617
+ }
618
+ return hash;
619
+ }
620
+ static runIfNotEmpty(clause, data) {
621
+ if (!Utils.isEmpty(data)) {
622
+ clause();
623
+ }
624
+ }
625
+ static defaultValue(prop, option, defaultValue) {
626
+ prop[option] = option in prop ? prop[option] : defaultValue;
627
+ }
628
+ static findDuplicates(items) {
629
+ return items.reduce((acc, v, i, arr) => {
630
+ return arr.indexOf(v) !== i && !acc.includes(v) ? acc.concat(v) : acc;
631
+ }, []);
632
+ }
633
+ static removeDuplicates(items) {
634
+ const ret = [];
635
+ const contains = (arr, val) => !!arr.find(v => equals(val, v));
636
+ for (const item of items) {
637
+ if (!contains(ret, item)) {
638
+ ret.push(item);
639
+ }
640
+ }
641
+ return ret;
642
+ }
643
+ static randomInt(min, max) {
644
+ return Math.round(Math.random() * (max - min)) + min;
645
+ }
646
+ /**
647
+ * Extracts all possible values of a TS enum. Works with both string and numeric enums.
648
+ */
649
+ static extractEnumValues(target) {
650
+ const keys = Object.keys(target);
651
+ const values = Object.values(target);
652
+ const numeric = !!values.find(v => typeof v === 'number');
653
+ const constEnum = values.length % 2 === 0 && // const enum will have even number of items
654
+ values.slice(0, values.length / 2).every(v => typeof v === 'string') && // first half are strings
655
+ values.slice(values.length / 2).every(v => typeof v === 'number') && // second half are numbers
656
+ this.equals(keys, values
657
+ .slice(values.length / 2)
658
+ .concat(values.slice(0, values.length / 2))
659
+ .map(v => '' + v)); // and when swapped, it will match the keys
660
+ if (numeric || constEnum) {
661
+ return values.filter(val => !keys.includes(val));
662
+ }
663
+ return values;
664
+ }
665
+ static flatten(arrays, deep) {
666
+ return arrays.flatMap(v => (deep && Array.isArray(v) ? this.flatten(v, true) : v));
667
+ }
668
+ static isOperator(key, includeGroupOperators = true) {
669
+ if (!includeGroupOperators) {
670
+ return key in QueryOperator;
671
+ }
672
+ return key in GroupOperator || key in QueryOperator;
673
+ }
674
+ static hasNestedKey(object, key) {
675
+ if (!object) {
676
+ return false;
677
+ }
678
+ if (Array.isArray(object)) {
679
+ return object.some(o => this.hasNestedKey(o, key));
680
+ }
681
+ if (typeof object === 'object') {
682
+ return Object.entries(object).some(([k, v]) => k === key || this.hasNestedKey(v, key));
683
+ }
851
684
  return false;
852
- }
853
- return typeof key === 'string' || Raw.isKnownFragmentSymbol(key);
854
- });
855
- }
685
+ }
686
+ static getORMVersion() {
687
+ return this.#ORM_VERSION;
688
+ }
689
+ static createFunction(context, code, compiledFunctions, key) {
690
+ if (key && compiledFunctions?.[key]) {
691
+ return compiledFunctions[key](...context.values());
692
+ }
693
+ try {
694
+ // eslint-disable-next-line @typescript-eslint/no-implied-eval
695
+ return new Function(...context.keys(), `'use strict';\n` + code)(...context.values());
696
+ /* v8 ignore next */
697
+ }
698
+ catch (e) {
699
+ // eslint-disable-next-line no-console
700
+ console.error(code);
701
+ throw e;
702
+ }
703
+ }
704
+ static callCompiledFunction(fn, ...args) {
705
+ try {
706
+ return fn(...args);
707
+ }
708
+ catch (e) {
709
+ /* v8 ignore next */
710
+ if ([SyntaxError, TypeError, EvalError, ReferenceError].some(t => e instanceof t)) {
711
+ const position = e.stack.match(/<anonymous>:(\d+):(\d+)/);
712
+ let code = fn.toString();
713
+ if (position) {
714
+ const lines = code.split('\n').map((line, idx) => {
715
+ if (idx === +position[1] - 5) {
716
+ return '> ' + line;
717
+ }
718
+ return ' ' + line;
719
+ });
720
+ lines.splice(+position[1] - 4, 0, ' '.repeat(+position[2]) + '^');
721
+ code = lines.join('\n');
722
+ }
723
+ // eslint-disable-next-line no-console
724
+ console.error(`JIT runtime error: ${e.message}\n\n${code}`);
725
+ }
726
+ throw e;
727
+ }
728
+ }
729
+ static unwrapProperty(entity, meta, prop, payload = false) {
730
+ let p = prop;
731
+ const path = [];
732
+ if (!prop.object && !prop.array && !prop.embedded) {
733
+ return entity[prop.name] != null ? [[entity[prop.name], []]] : [];
734
+ }
735
+ while (p.embedded) {
736
+ const child = meta.properties[p.embedded[0]];
737
+ if (payload && !child.object && !child.array) {
738
+ break;
739
+ }
740
+ path.shift();
741
+ path.unshift(p.embedded[0], p.embedded[1]);
742
+ p = child;
743
+ }
744
+ const ret = [];
745
+ const follow = (t, idx = 0, i = []) => {
746
+ const k = path[idx];
747
+ if (Array.isArray(t)) {
748
+ for (const t1 of t) {
749
+ const ii = t.indexOf(t1);
750
+ follow(t1, idx, [...i, ii]);
751
+ }
752
+ return;
753
+ }
754
+ if (t == null) {
755
+ return;
756
+ }
757
+ const target = t[k];
758
+ if (path[++idx]) {
759
+ follow(target, idx, i);
760
+ }
761
+ else if (target != null) {
762
+ ret.push([target, i]);
763
+ }
764
+ };
765
+ follow(entity);
766
+ return ret;
767
+ }
768
+ static setPayloadProperty(entity, meta, prop, value, idx) {
769
+ if (!prop.object && !prop.array && !prop.embedded) {
770
+ entity[prop.name] = value;
771
+ return;
772
+ }
773
+ let target = entity;
774
+ let p = prop;
775
+ const path = [];
776
+ while (p.embedded) {
777
+ path.shift();
778
+ path.unshift(p.embedded[0], p.embedded[1]);
779
+ const prev = p;
780
+ p = meta.properties[p.embedded[0]];
781
+ if (!p.object) {
782
+ path.shift();
783
+ path[0] = prev.name;
784
+ break;
785
+ }
786
+ }
787
+ let j = 0;
788
+ for (const k of path) {
789
+ const i = path.indexOf(k);
790
+ if (i === path.length - 1) {
791
+ if (Array.isArray(target)) {
792
+ target[idx[j++]][k] = value;
793
+ }
794
+ else {
795
+ target[k] = value;
796
+ }
797
+ }
798
+ else {
799
+ if (Array.isArray(target)) {
800
+ target = target[idx[j++]][k];
801
+ }
802
+ else {
803
+ target = target[k];
804
+ }
805
+ }
806
+ }
807
+ }
808
+ static async tryImport({ module, warning, }) {
809
+ try {
810
+ return await import(module);
811
+ }
812
+ catch (err) {
813
+ if (warning && err.code === 'ERR_MODULE_NOT_FOUND') {
814
+ // eslint-disable-next-line no-console
815
+ console.warn(warning);
816
+ }
817
+ return undefined;
818
+ }
819
+ }
820
+ static xor(a, b) {
821
+ return (a || b) && !(a && b);
822
+ }
823
+ static keys(obj) {
824
+ return Object.keys(obj);
825
+ }
826
+ static values(obj) {
827
+ return Object.values(obj);
828
+ }
829
+ static entries(obj) {
830
+ return Object.entries(obj);
831
+ }
832
+ static primaryKeyToObject(meta, primaryKey, visible) {
833
+ const pks = meta.compositePK && Utils.isPlainObject(primaryKey) ? Object.values(primaryKey) : Utils.asArray(primaryKey);
834
+ const pkProps = meta.getPrimaryProps();
835
+ return meta.primaryKeys.reduce((o, pk, idx) => {
836
+ const pkProp = pkProps[idx];
837
+ if (visible && !visible.includes(pkProp.name)) {
838
+ return o;
839
+ }
840
+ if (Utils.isPlainObject(pks[idx]) && pkProp.targetMeta) {
841
+ o[pk] = Utils.getOrderedPrimaryKeys(pks[idx], pkProp.targetMeta);
842
+ return o;
843
+ }
844
+ o[pk] = pks[idx];
845
+ return o;
846
+ }, {});
847
+ }
848
+ static getObjectQueryKeys(obj) {
849
+ return Reflect.ownKeys(obj).filter(key => {
850
+ if (!Object.prototype.propertyIsEnumerable.call(obj, key)) {
851
+ return false;
852
+ }
853
+ return typeof key === 'string' || Raw.isKnownFragmentSymbol(key);
854
+ });
855
+ }
856
856
  }