@mikro-orm/core 7.0.0-dev.32 → 7.0.0-dev.321

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 (216) hide show
  1. package/EntityManager.d.ts +71 -63
  2. package/EntityManager.js +365 -283
  3. package/MikroORM.d.ts +44 -35
  4. package/MikroORM.js +109 -142
  5. package/README.md +7 -4
  6. package/cache/FileCacheAdapter.d.ts +1 -2
  7. package/cache/FileCacheAdapter.js +19 -14
  8. package/cache/GeneratedCacheAdapter.d.ts +0 -1
  9. package/cache/GeneratedCacheAdapter.js +0 -2
  10. package/cache/index.d.ts +1 -2
  11. package/cache/index.js +0 -2
  12. package/connections/Connection.d.ts +12 -5
  13. package/connections/Connection.js +37 -15
  14. package/drivers/DatabaseDriver.d.ts +25 -18
  15. package/drivers/DatabaseDriver.js +144 -45
  16. package/drivers/IDatabaseDriver.d.ts +118 -23
  17. package/entity/BaseEntity.d.ts +63 -4
  18. package/entity/BaseEntity.js +0 -3
  19. package/entity/Collection.d.ts +101 -29
  20. package/entity/Collection.js +473 -115
  21. package/entity/EntityAssigner.js +37 -25
  22. package/entity/EntityFactory.d.ts +7 -1
  23. package/entity/EntityFactory.js +116 -64
  24. package/entity/EntityHelper.d.ts +2 -2
  25. package/entity/EntityHelper.js +69 -27
  26. package/entity/EntityLoader.d.ts +11 -10
  27. package/entity/EntityLoader.js +264 -102
  28. package/entity/EntityRepository.d.ts +28 -8
  29. package/entity/EntityRepository.js +8 -2
  30. package/entity/PolymorphicRef.d.ts +12 -0
  31. package/entity/PolymorphicRef.js +18 -0
  32. package/entity/Reference.d.ts +2 -6
  33. package/entity/Reference.js +52 -19
  34. package/entity/WrappedEntity.d.ts +3 -8
  35. package/entity/WrappedEntity.js +6 -7
  36. package/entity/defineEntity.d.ts +525 -311
  37. package/entity/defineEntity.js +134 -290
  38. package/entity/index.d.ts +2 -2
  39. package/entity/index.js +2 -2
  40. package/entity/utils.d.ts +6 -1
  41. package/entity/utils.js +46 -11
  42. package/entity/validators.d.ts +11 -0
  43. package/entity/validators.js +66 -0
  44. package/enums.d.ts +8 -6
  45. package/enums.js +13 -17
  46. package/errors.d.ts +20 -10
  47. package/errors.js +63 -31
  48. package/events/EventManager.d.ts +2 -1
  49. package/events/EventManager.js +24 -13
  50. package/events/index.d.ts +1 -1
  51. package/events/index.js +0 -1
  52. package/exceptions.js +9 -2
  53. package/hydration/Hydrator.js +1 -2
  54. package/hydration/ObjectHydrator.d.ts +4 -4
  55. package/hydration/ObjectHydrator.js +105 -46
  56. package/index.d.ts +2 -2
  57. package/index.js +1 -2
  58. package/logging/DefaultLogger.d.ts +1 -1
  59. package/logging/DefaultLogger.js +3 -4
  60. package/logging/SimpleLogger.d.ts +1 -1
  61. package/logging/colors.d.ts +1 -1
  62. package/logging/colors.js +5 -7
  63. package/logging/index.d.ts +2 -1
  64. package/logging/index.js +1 -1
  65. package/logging/inspect.d.ts +2 -0
  66. package/logging/inspect.js +11 -0
  67. package/metadata/EntitySchema.d.ts +47 -23
  68. package/metadata/EntitySchema.js +103 -34
  69. package/metadata/MetadataDiscovery.d.ts +64 -9
  70. package/metadata/MetadataDiscovery.js +867 -354
  71. package/metadata/MetadataProvider.d.ts +11 -2
  72. package/metadata/MetadataProvider.js +71 -2
  73. package/metadata/MetadataStorage.d.ts +13 -11
  74. package/metadata/MetadataStorage.js +72 -41
  75. package/metadata/MetadataValidator.d.ts +32 -9
  76. package/metadata/MetadataValidator.js +214 -44
  77. package/metadata/discover-entities.d.ts +5 -0
  78. package/metadata/discover-entities.js +40 -0
  79. package/metadata/index.d.ts +1 -1
  80. package/metadata/index.js +0 -1
  81. package/metadata/types.d.ts +577 -0
  82. package/metadata/types.js +1 -0
  83. package/naming-strategy/AbstractNamingStrategy.d.ts +16 -4
  84. package/naming-strategy/AbstractNamingStrategy.js +26 -5
  85. package/naming-strategy/EntityCaseNamingStrategy.d.ts +3 -3
  86. package/naming-strategy/EntityCaseNamingStrategy.js +6 -5
  87. package/naming-strategy/MongoNamingStrategy.d.ts +3 -3
  88. package/naming-strategy/MongoNamingStrategy.js +6 -6
  89. package/naming-strategy/NamingStrategy.d.ts +28 -4
  90. package/naming-strategy/UnderscoreNamingStrategy.d.ts +3 -3
  91. package/naming-strategy/UnderscoreNamingStrategy.js +6 -6
  92. package/naming-strategy/index.d.ts +1 -1
  93. package/naming-strategy/index.js +0 -1
  94. package/not-supported.d.ts +2 -0
  95. package/not-supported.js +8 -0
  96. package/package.json +47 -36
  97. package/platforms/ExceptionConverter.js +1 -1
  98. package/platforms/Platform.d.ts +33 -15
  99. package/platforms/Platform.js +125 -69
  100. package/serialization/EntitySerializer.d.ts +6 -3
  101. package/serialization/EntitySerializer.js +53 -29
  102. package/serialization/EntityTransformer.js +33 -21
  103. package/serialization/SerializationContext.d.ts +6 -6
  104. package/serialization/SerializationContext.js +4 -4
  105. package/types/ArrayType.d.ts +1 -1
  106. package/types/ArrayType.js +2 -3
  107. package/types/BigIntType.js +1 -1
  108. package/types/BlobType.d.ts +0 -1
  109. package/types/BlobType.js +0 -3
  110. package/types/BooleanType.d.ts +1 -0
  111. package/types/BooleanType.js +3 -0
  112. package/types/DecimalType.js +2 -2
  113. package/types/DoubleType.js +1 -1
  114. package/types/EnumArrayType.js +1 -2
  115. package/types/JsonType.d.ts +1 -1
  116. package/types/JsonType.js +7 -2
  117. package/types/TinyIntType.js +1 -1
  118. package/types/Type.d.ts +2 -4
  119. package/types/Type.js +3 -3
  120. package/types/Uint8ArrayType.d.ts +0 -1
  121. package/types/Uint8ArrayType.js +1 -4
  122. package/types/UuidType.d.ts +2 -0
  123. package/types/UuidType.js +14 -2
  124. package/types/index.d.ts +3 -2
  125. package/typings.d.ts +427 -170
  126. package/typings.js +100 -45
  127. package/unit-of-work/ChangeSet.d.ts +4 -6
  128. package/unit-of-work/ChangeSet.js +8 -9
  129. package/unit-of-work/ChangeSetComputer.d.ts +3 -8
  130. package/unit-of-work/ChangeSetComputer.js +49 -26
  131. package/unit-of-work/ChangeSetPersister.d.ts +13 -12
  132. package/unit-of-work/ChangeSetPersister.js +107 -44
  133. package/unit-of-work/CommitOrderCalculator.d.ts +12 -10
  134. package/unit-of-work/CommitOrderCalculator.js +17 -15
  135. package/unit-of-work/IdentityMap.d.ts +12 -0
  136. package/unit-of-work/IdentityMap.js +39 -1
  137. package/unit-of-work/UnitOfWork.d.ts +34 -4
  138. package/unit-of-work/UnitOfWork.js +294 -107
  139. package/utils/AbstractMigrator.d.ts +101 -0
  140. package/utils/AbstractMigrator.js +303 -0
  141. package/utils/AbstractSchemaGenerator.d.ts +5 -5
  142. package/utils/AbstractSchemaGenerator.js +30 -18
  143. package/utils/AsyncContext.d.ts +6 -0
  144. package/utils/AsyncContext.js +42 -0
  145. package/utils/Configuration.d.ts +796 -211
  146. package/utils/Configuration.js +160 -197
  147. package/utils/ConfigurationLoader.d.ts +1 -52
  148. package/utils/ConfigurationLoader.js +1 -330
  149. package/utils/Cursor.d.ts +0 -3
  150. package/utils/Cursor.js +29 -14
  151. package/utils/DataloaderUtils.d.ts +10 -5
  152. package/utils/DataloaderUtils.js +42 -22
  153. package/utils/EntityComparator.d.ts +16 -9
  154. package/utils/EntityComparator.js +202 -96
  155. package/utils/QueryHelper.d.ts +34 -7
  156. package/utils/QueryHelper.js +183 -72
  157. package/utils/RawQueryFragment.d.ts +28 -34
  158. package/utils/RawQueryFragment.js +37 -72
  159. package/utils/RequestContext.js +2 -2
  160. package/utils/TransactionContext.js +2 -2
  161. package/utils/TransactionManager.js +11 -7
  162. package/utils/Utils.d.ts +16 -127
  163. package/utils/Utils.js +106 -401
  164. package/utils/clone.js +13 -23
  165. package/utils/env-vars.d.ts +7 -0
  166. package/utils/env-vars.js +98 -0
  167. package/utils/fs-utils.d.ts +34 -0
  168. package/utils/fs-utils.js +193 -0
  169. package/utils/index.d.ts +1 -3
  170. package/utils/index.js +1 -3
  171. package/utils/upsert-utils.d.ts +9 -4
  172. package/utils/upsert-utils.js +51 -5
  173. package/decorators/Check.d.ts +0 -3
  174. package/decorators/Check.js +0 -13
  175. package/decorators/CreateRequestContext.d.ts +0 -3
  176. package/decorators/CreateRequestContext.js +0 -32
  177. package/decorators/Embeddable.d.ts +0 -8
  178. package/decorators/Embeddable.js +0 -11
  179. package/decorators/Embedded.d.ts +0 -12
  180. package/decorators/Embedded.js +0 -18
  181. package/decorators/Entity.d.ts +0 -33
  182. package/decorators/Entity.js +0 -12
  183. package/decorators/Enum.d.ts +0 -9
  184. package/decorators/Enum.js +0 -16
  185. package/decorators/Filter.d.ts +0 -2
  186. package/decorators/Filter.js +0 -8
  187. package/decorators/Formula.d.ts +0 -4
  188. package/decorators/Formula.js +0 -15
  189. package/decorators/Indexed.d.ts +0 -19
  190. package/decorators/Indexed.js +0 -20
  191. package/decorators/ManyToMany.d.ts +0 -42
  192. package/decorators/ManyToMany.js +0 -14
  193. package/decorators/ManyToOne.d.ts +0 -34
  194. package/decorators/ManyToOne.js +0 -14
  195. package/decorators/OneToMany.d.ts +0 -28
  196. package/decorators/OneToMany.js +0 -17
  197. package/decorators/OneToOne.d.ts +0 -28
  198. package/decorators/OneToOne.js +0 -7
  199. package/decorators/PrimaryKey.d.ts +0 -8
  200. package/decorators/PrimaryKey.js +0 -20
  201. package/decorators/Property.d.ts +0 -250
  202. package/decorators/Property.js +0 -32
  203. package/decorators/Transactional.d.ts +0 -14
  204. package/decorators/Transactional.js +0 -28
  205. package/decorators/hooks.d.ts +0 -16
  206. package/decorators/hooks.js +0 -47
  207. package/decorators/index.d.ts +0 -17
  208. package/decorators/index.js +0 -17
  209. package/entity/ArrayCollection.d.ts +0 -118
  210. package/entity/ArrayCollection.js +0 -407
  211. package/entity/EntityValidator.d.ts +0 -19
  212. package/entity/EntityValidator.js +0 -150
  213. package/metadata/ReflectMetadataProvider.d.ts +0 -8
  214. package/metadata/ReflectMetadataProvider.js +0 -44
  215. package/utils/resolveContextProvider.d.ts +0 -10
  216. package/utils/resolveContextProvider.js +0 -28
package/utils/clone.js CHANGED
@@ -3,8 +3,6 @@
3
3
  * clone `EventEmitter`s to get around https://github.com/mikro-orm/mikro-orm/issues/2748
4
4
  * @internal
5
5
  */
6
- import { EventEmitter } from 'node:events';
7
- import { RawQueryFragment } from './RawQueryFragment.js';
8
6
  /**
9
7
  * Get the property descriptor of a property on an object or its prototype chain.
10
8
  *
@@ -22,6 +20,7 @@ function getPropertyDescriptor(obj, prop) {
22
20
  }
23
21
  return null;
24
22
  }
23
+ const TypedArray = Object.getPrototypeOf(Uint8Array);
25
24
  export function clone(parent, respectCustomCloneMethod = true) {
26
25
  const allParents = [];
27
26
  const allChildren = [];
@@ -30,11 +29,7 @@ export function clone(parent, respectCustomCloneMethod = true) {
30
29
  if (parent === null) {
31
30
  return null;
32
31
  }
33
- const raw = RawQueryFragment.getKnownFragment(parent, false);
34
- if (raw && respectCustomCloneMethod) {
35
- return raw.clone();
36
- }
37
- if (typeof parent !== 'object' || parent instanceof EventEmitter) {
32
+ if (typeof parent !== 'object') {
38
33
  return parent;
39
34
  }
40
35
  if (respectCustomCloneMethod && 'clone' in parent && typeof parent.clone === 'function') {
@@ -80,6 +75,10 @@ export function clone(parent, respectCustomCloneMethod = true) {
80
75
  parent.copy(child);
81
76
  return child;
82
77
  }
78
+ else if (parent instanceof TypedArray) {
79
+ child = parent.copyWithin(0);
80
+ return child;
81
+ }
83
82
  else if (parent instanceof Error) {
84
83
  child = new parent.constructor(parent.message);
85
84
  }
@@ -114,25 +113,16 @@ export function clone(parent, respectCustomCloneMethod = true) {
114
113
  if (attrs && typeof attrs.get === 'function' && attrs.set == null) {
115
114
  continue;
116
115
  }
117
- const raw = RawQueryFragment.getKnownFragment(i, false);
118
- if (raw && respectCustomCloneMethod) {
119
- const i2 = raw.clone().toString();
120
- child[i2] = _clone(parent[i]);
121
- continue;
122
- }
123
116
  child[i] = _clone(parent[i]);
124
117
  }
125
- if (Object.getOwnPropertySymbols) {
126
- const symbols = Object.getOwnPropertySymbols(parent);
127
- for (let i = 0; i < symbols.length; i++) {
128
- const symbol = symbols[i];
129
- const descriptor = Object.getOwnPropertyDescriptor(parent, symbol);
130
- /* v8 ignore next 3 */
131
- if (descriptor && !descriptor.enumerable) {
132
- continue;
133
- }
134
- child[symbol] = _clone(parent[symbol]);
118
+ const symbols = Object.getOwnPropertySymbols(parent);
119
+ for (let i = 0; i < symbols.length; i++) {
120
+ const symbol = symbols[i];
121
+ const descriptor = Object.getOwnPropertyDescriptor(parent, symbol);
122
+ if (descriptor && !descriptor.enumerable) {
123
+ continue;
135
124
  }
125
+ child[symbol] = _clone(parent[symbol]);
136
126
  }
137
127
  return child;
138
128
  }
@@ -0,0 +1,7 @@
1
+ import { type Options } from './Configuration.js';
2
+ /** @internal */
3
+ export declare function setEnv(key: string, value: unknown): void;
4
+ /** @internal */
5
+ export declare function getEnv(key: string): string | undefined;
6
+ /** @internal */
7
+ export declare function loadEnvironmentVars(): Partial<Options>;
@@ -0,0 +1,98 @@
1
+ import { Utils } from './Utils.js';
2
+ /** @internal */
3
+ export function setEnv(key, value) {
4
+ if (globalThis.process?.env) {
5
+ globalThis.process.env[key] = String(value);
6
+ }
7
+ }
8
+ /** @internal */
9
+ export function getEnv(key) {
10
+ return globalThis.process?.env?.[key];
11
+ }
12
+ /** @internal */
13
+ export function loadEnvironmentVars() {
14
+ const ret = {};
15
+ const getEnvKey = (key, envPrefix = 'MIKRO_ORM_') => {
16
+ return (envPrefix +
17
+ key
18
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
19
+ .replace(/([A-Z])([A-Z][a-z])/g, '$1_$2')
20
+ .toUpperCase());
21
+ };
22
+ const array = (v) => v.split(',').map(vv => vv.trim());
23
+ const bool = (v) => ['true', 't', '1'].includes(v.toLowerCase());
24
+ const num = (v) => +v;
25
+ const read = (o, envPrefix, key, mapper = v => v) => {
26
+ const envKey = getEnvKey(key, envPrefix);
27
+ /* v8 ignore next */
28
+ if (envKey in (globalThis.process?.env ?? {})) {
29
+ o[key] = mapper(getEnv(envKey));
30
+ }
31
+ };
32
+ const cleanup = (o, k) => (Utils.hasObjectKeys(o[k]) ? {} : delete o[k]);
33
+ const read0 = read.bind(null, ret, 'MIKRO_ORM_');
34
+ read0('baseDir');
35
+ read0('entities', array);
36
+ read0('entitiesTs', array);
37
+ read0('clientUrl');
38
+ read0('host');
39
+ read0('port', num);
40
+ read0('user');
41
+ read0('password');
42
+ read0('dbName');
43
+ read0('schema');
44
+ read0('loadStrategy');
45
+ read0('batchSize', num);
46
+ read0('useBatchInserts', bool);
47
+ read0('useBatchUpdates', bool);
48
+ read0('allowGlobalContext', bool);
49
+ read0('autoJoinOneToOneOwner', bool);
50
+ read0('populateAfterFlush', bool);
51
+ read0('forceEntityConstructor', bool);
52
+ read0('forceUndefined', bool);
53
+ read0('forceUtcTimezone', bool);
54
+ read0('timezone');
55
+ read0('ensureIndexes', bool);
56
+ read0('implicitTransactions', bool);
57
+ read0('debug', bool);
58
+ read0('colors', bool);
59
+ ret.discovery = {};
60
+ const read1 = read.bind(null, ret.discovery, 'MIKRO_ORM_DISCOVERY_');
61
+ read1('warnWhenNoEntities', bool);
62
+ read1('checkDuplicateTableNames', bool);
63
+ read1('checkDuplicateFieldNames', bool);
64
+ read1('checkNonPersistentCompositeProps', bool);
65
+ read1('inferDefaultValues', bool);
66
+ read1('tsConfigPath');
67
+ cleanup(ret, 'discovery');
68
+ ret.migrations = {};
69
+ const read2 = read.bind(null, ret.migrations, 'MIKRO_ORM_MIGRATIONS_');
70
+ read2('tableName');
71
+ read2('path');
72
+ read2('pathTs');
73
+ read2('glob');
74
+ read2('transactional', bool);
75
+ read2('disableForeignKeys', bool);
76
+ read2('allOrNothing', bool);
77
+ read2('dropTables', bool);
78
+ read2('safe', bool);
79
+ read2('silent', bool);
80
+ read2('emit');
81
+ read2('snapshot', bool);
82
+ read2('snapshotName');
83
+ cleanup(ret, 'migrations');
84
+ ret.schemaGenerator = {};
85
+ const read3 = read.bind(null, ret.schemaGenerator, 'MIKRO_ORM_SCHEMA_GENERATOR_');
86
+ read3('disableForeignKeys', bool);
87
+ read3('createForeignKeyConstraints', bool);
88
+ cleanup(ret, 'schemaGenerator');
89
+ ret.seeder = {};
90
+ const read4 = read.bind(null, ret.seeder, 'MIKRO_ORM_SEEDER_');
91
+ read4('path');
92
+ read4('pathTs');
93
+ read4('glob');
94
+ read4('emit');
95
+ read4('defaultSeeder');
96
+ cleanup(ret, 'seeder');
97
+ return ret;
98
+ }
@@ -0,0 +1,34 @@
1
+ import { type Dictionary } from '../typings.js';
2
+ export declare const fs: {
3
+ init(): Promise<void>;
4
+ pathExists(path: string): boolean;
5
+ ensureDir(path: string): void;
6
+ readJSONSync<T = Dictionary>(path: string): T;
7
+ glob(input: string | string[], cwd?: string): string[];
8
+ resolveGlob(input: string | string[], cwd?: string): string[];
9
+ getPackageConfig<T extends Dictionary>(basePath?: string): T;
10
+ getORMPackages(): Set<string>;
11
+ getORMPackageVersion(name: string): string | undefined;
12
+ checkPackageVersion(): void;
13
+ /**
14
+ * Resolves and normalizes a series of path parts relative to each preceding part.
15
+ * If any part is a `file:` URL, it is converted to a local path. If any part is an
16
+ * absolute path, it replaces preceding paths (similar to `path.resolve` in NodeJS).
17
+ * Trailing directory separators are removed, and all directory separators are converted
18
+ * to POSIX-style separators (`/`).
19
+ */
20
+ normalizePath(...parts: string[]): string;
21
+ /**
22
+ * Determines the relative path between two paths. If either path is a `file:` URL,
23
+ * it is converted to a local path.
24
+ */
25
+ relativePath(path: string, relativeTo: string): string;
26
+ /**
27
+ * Computes the absolute path to for the given path relative to the provided base directory.
28
+ * If either `path` or `baseDir` are `file:` URLs, they are converted to local paths.
29
+ */
30
+ absolutePath(path: string, baseDir?: string): string;
31
+ writeFile(path: string, data: string, options?: Record<string, any>): Promise<void>;
32
+ dynamicImport<T = any>(id: string): Promise<T>;
33
+ };
34
+ export * from '../cache/FileCacheAdapter.js';
@@ -0,0 +1,193 @@
1
+ import { existsSync, globSync as nodeGlobSync, mkdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
2
+ import { writeFile as nodeWriteFile } from 'node:fs/promises';
3
+ import { isAbsolute, join, normalize, relative } from 'node:path';
4
+ import { fileURLToPath, pathToFileURL } from 'node:url';
5
+ import { Utils } from './Utils.js';
6
+ import { colors } from '../logging/colors.js';
7
+ let globSync = (patterns, options) => {
8
+ const files = nodeGlobSync(patterns, { ...options, withFileTypes: true });
9
+ return files.filter(f => f.isFile()).map(f => join(f.parentPath, f.name));
10
+ };
11
+ export const fs = {
12
+ async init() {
13
+ const tinyGlobby = await import('tinyglobby').catch(() => null);
14
+ if (tinyGlobby) {
15
+ globSync = (patterns, options) => {
16
+ patterns = Utils.asArray(patterns).map(p => p.replace(/\\/g, '/'));
17
+ if (options?.cwd) {
18
+ options = { ...options, cwd: options.cwd.replace(/\\/g, '/') };
19
+ }
20
+ return tinyGlobby.globSync(patterns, { ...options, expandDirectories: false });
21
+ };
22
+ }
23
+ },
24
+ pathExists(path) {
25
+ if (/[*?[\]]/.test(path)) {
26
+ return globSync(path).length > 0;
27
+ }
28
+ return existsSync(path);
29
+ },
30
+ ensureDir(path) {
31
+ if (!existsSync(path)) {
32
+ mkdirSync(path, { recursive: true });
33
+ }
34
+ },
35
+ readJSONSync(path) {
36
+ const file = readFileSync(path);
37
+ return JSON.parse(file.toString());
38
+ },
39
+ glob(input, cwd) {
40
+ const patterns = Array.isArray(input) ? input : [input];
41
+ const positive = [];
42
+ const negative = [];
43
+ for (const p of patterns) {
44
+ if (p.startsWith('!')) {
45
+ negative.push(p.slice(1));
46
+ }
47
+ else {
48
+ positive.push(p);
49
+ }
50
+ }
51
+ const included = new Set(this.resolveGlob(positive, cwd));
52
+ if (included.size > 0 && negative.length > 0) {
53
+ const excluded = this.resolveGlob(negative, cwd);
54
+ for (const file of excluded) {
55
+ included.delete(file);
56
+ }
57
+ }
58
+ return [...included];
59
+ },
60
+ resolveGlob(input, cwd) {
61
+ if (Array.isArray(input)) {
62
+ return input.flatMap(paths => this.resolveGlob(paths, cwd));
63
+ }
64
+ const hasGlobChars = /[*?[\]]/.test(input);
65
+ if (!hasGlobChars) {
66
+ try {
67
+ const s = statSync(cwd ? this.normalizePath(cwd, input) : input);
68
+ if (s.isDirectory()) {
69
+ return globSync(join(input, '**'), { cwd });
70
+ }
71
+ }
72
+ catch {
73
+ // ignore
74
+ }
75
+ }
76
+ return globSync(input, { cwd });
77
+ },
78
+ getPackageConfig(basePath = process.cwd()) {
79
+ if (this.pathExists(`${basePath}/package.json`)) {
80
+ try {
81
+ const path = this.normalizePath(import.meta.resolve(`${basePath}/package.json`));
82
+ return this.readJSONSync(path);
83
+ }
84
+ catch (e) {
85
+ /* v8 ignore next */
86
+ return {};
87
+ }
88
+ }
89
+ const parentFolder = realpathSync(`${basePath}/..`);
90
+ // we reached the root folder
91
+ if (basePath === parentFolder) {
92
+ return {};
93
+ }
94
+ return this.getPackageConfig(parentFolder);
95
+ },
96
+ getORMPackages() {
97
+ const pkg = this.getPackageConfig();
98
+ return new Set([...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})]);
99
+ },
100
+ getORMPackageVersion(name) {
101
+ try {
102
+ const path = import.meta.resolve(`${name}/package.json`);
103
+ const pkg = this.readJSONSync(fileURLToPath(path));
104
+ return pkg?.version;
105
+ }
106
+ catch (e) {
107
+ return undefined;
108
+ }
109
+ },
110
+ // inspired by https://github.com/facebook/docusaurus/pull/3386
111
+ checkPackageVersion() {
112
+ const coreVersion = Utils.getORMVersion();
113
+ if (process.env.MIKRO_ORM_ALLOW_VERSION_MISMATCH || coreVersion === '[[MIKRO_ORM_VERSION]]') {
114
+ return;
115
+ }
116
+ const deps = this.getORMPackages();
117
+ const exceptions = new Set(['nestjs', 'sql-highlighter', 'mongo-highlighter']);
118
+ const ormPackages = [...deps].filter(d => d.startsWith('@mikro-orm/') && d !== '@mikro-orm/core' && !exceptions.has(d.substring('@mikro-orm/'.length)));
119
+ for (const ormPackage of ormPackages) {
120
+ const version = this.getORMPackageVersion(ormPackage);
121
+ if (version != null && version !== coreVersion) {
122
+ throw new Error(`Bad ${colors.cyan(ormPackage)} version ${colors.yellow('' + version)}.\n` +
123
+ `All official @mikro-orm/* packages need to have the exact same version as @mikro-orm/core (${colors.green(coreVersion)}).\n` +
124
+ `Only exceptions are packages that don't live in the 'mikro-orm' repository: ${[...exceptions].join(', ')}.\n` +
125
+ `Maybe you want to check, or regenerate your yarn.lock or package-lock.json file?`);
126
+ }
127
+ }
128
+ },
129
+ /**
130
+ * Resolves and normalizes a series of path parts relative to each preceding part.
131
+ * If any part is a `file:` URL, it is converted to a local path. If any part is an
132
+ * absolute path, it replaces preceding paths (similar to `path.resolve` in NodeJS).
133
+ * Trailing directory separators are removed, and all directory separators are converted
134
+ * to POSIX-style separators (`/`).
135
+ */
136
+ normalizePath(...parts) {
137
+ let start = 0;
138
+ for (let i = 0; i < parts.length; i++) {
139
+ const part = parts[i];
140
+ if (isAbsolute(part)) {
141
+ start = i;
142
+ }
143
+ else if (part.startsWith('file:')) {
144
+ start = i;
145
+ parts[i] = fileURLToPath(part);
146
+ }
147
+ }
148
+ if (start > 0) {
149
+ parts = parts.slice(start);
150
+ }
151
+ let path = parts.join('/').replace(/\\/g, '/').replace(/\/$/, '');
152
+ path = normalize(path).replace(/\\/g, '/');
153
+ return /^[/.]|[a-zA-Z]:/.exec(path) || path.startsWith('!') ? path : './' + path;
154
+ },
155
+ /**
156
+ * Determines the relative path between two paths. If either path is a `file:` URL,
157
+ * it is converted to a local path.
158
+ */
159
+ relativePath(path, relativeTo) {
160
+ if (!path) {
161
+ return path;
162
+ }
163
+ path = this.normalizePath(path);
164
+ if (path.startsWith('.')) {
165
+ return path;
166
+ }
167
+ path = relative(this.normalizePath(relativeTo), path);
168
+ return this.normalizePath(path);
169
+ },
170
+ /**
171
+ * Computes the absolute path to for the given path relative to the provided base directory.
172
+ * If either `path` or `baseDir` are `file:` URLs, they are converted to local paths.
173
+ */
174
+ absolutePath(path, baseDir = process.cwd()) {
175
+ if (!path) {
176
+ return this.normalizePath(baseDir);
177
+ }
178
+ if (!isAbsolute(path) && !path.startsWith('file://')) {
179
+ path = baseDir + '/' + path;
180
+ }
181
+ return this.normalizePath(path);
182
+ },
183
+ async writeFile(path, data, options) {
184
+ await nodeWriteFile(path, data, options);
185
+ },
186
+ async dynamicImport(id) {
187
+ /* v8 ignore next */
188
+ const specifier = id.startsWith('file://') ? id : pathToFileURL(id).href;
189
+ const dynamicImportProvider = globalThis.dynamicImportProvider ?? ((id) => import(id));
190
+ return dynamicImportProvider(specifier);
191
+ },
192
+ };
193
+ export * from '../cache/FileCacheAdapter.js';
package/utils/index.d.ts CHANGED
@@ -1,7 +1,5 @@
1
1
  export * from './Configuration.js';
2
- export * from './ConfigurationLoader.js';
3
2
  export * from './Cursor.js';
4
- export * from './DataloaderUtils.js';
5
3
  export * from './Utils.js';
6
4
  export * from './RequestContext.js';
7
5
  export * from './TransactionContext.js';
@@ -9,6 +7,6 @@ export * from './TransactionManager.js';
9
7
  export * from './QueryHelper.js';
10
8
  export * from './NullHighlighter.js';
11
9
  export * from './EntityComparator.js';
12
- export * from './AbstractSchemaGenerator.js';
13
10
  export * from './RawQueryFragment.js';
11
+ export * from './env-vars.js';
14
12
  export * from './upsert-utils.js';
package/utils/index.js CHANGED
@@ -1,7 +1,5 @@
1
1
  export * from './Configuration.js';
2
- export * from './ConfigurationLoader.js';
3
2
  export * from './Cursor.js';
4
- export * from './DataloaderUtils.js';
5
3
  export * from './Utils.js';
6
4
  export * from './RequestContext.js';
7
5
  export * from './TransactionContext.js';
@@ -9,6 +7,6 @@ export * from './TransactionManager.js';
9
7
  export * from './QueryHelper.js';
10
8
  export * from './NullHighlighter.js';
11
9
  export * from './EntityComparator.js';
12
- export * from './AbstractSchemaGenerator.js';
13
10
  export * from './RawQueryFragment.js';
11
+ export * from './env-vars.js';
14
12
  export * from './upsert-utils.js';
@@ -1,7 +1,12 @@
1
- import type { EntityData, EntityMetadata } from '../typings.js';
1
+ import type { EntityData, EntityMetadata, FilterQuery } from '../typings.js';
2
2
  import type { UpsertOptions } from '../drivers/IDatabaseDriver.js';
3
- import type { RawQueryFragment } from '../utils/RawQueryFragment.js';
3
+ import { type Raw } from '../utils/RawQueryFragment.js';
4
4
  /** @internal */
5
- export declare function getOnConflictFields<T>(meta: EntityMetadata<T> | undefined, data: EntityData<T>, uniqueFields: (keyof T)[] | RawQueryFragment, options: UpsertOptions<T>): (keyof T)[];
5
+ export declare function getOnConflictFields<T>(meta: EntityMetadata<T> | undefined, data: EntityData<T>, uniqueFields: (keyof T)[] | Raw, options: UpsertOptions<T>): (keyof T)[];
6
6
  /** @internal */
7
- export declare function getOnConflictReturningFields<T, P extends string>(meta: EntityMetadata<T> | undefined, data: EntityData<T>, uniqueFields: (keyof T)[] | RawQueryFragment, options: UpsertOptions<T, P>): (keyof T)[] | '*';
7
+ export declare function getOnConflictReturningFields<T, P extends string>(meta: EntityMetadata<T> | undefined, data: EntityData<T>, uniqueFields: (keyof T)[] | Raw, options: UpsertOptions<T, P>): (keyof T)[] | '*';
8
+ /** @internal */
9
+ export declare function getWhereCondition<T extends object>(meta: EntityMetadata<T>, onConflictFields: (keyof T)[] | Raw | undefined, data: EntityData<T>, where: FilterQuery<T>): {
10
+ where: FilterQuery<T>;
11
+ propIndex: number | false;
12
+ };
@@ -1,9 +1,11 @@
1
+ import { isRaw } from '../utils/RawQueryFragment.js';
2
+ import { Utils } from './Utils.js';
1
3
  function expandEmbeddedProperties(prop, key) {
2
4
  if (prop.object) {
3
5
  return [prop.name];
4
6
  }
5
7
  return Object.values(prop.embeddedProps).flatMap(p => {
6
- /* v8 ignore next 3 */
8
+ /* v8 ignore next */
7
9
  if (p.embeddable && !p.object) {
8
10
  return expandEmbeddedProperties(p);
9
11
  }
@@ -42,7 +44,7 @@ export function getOnConflictFields(meta, data, uniqueFields, options) {
42
44
  const onConflictMergeFields = expandFields(meta, options.onConflictMergeFields);
43
45
  return onConflictMergeFields.flatMap(f => {
44
46
  const prop = meta?.properties[f];
45
- /* v8 ignore next 3 */
47
+ /* v8 ignore next */
46
48
  if (prop?.embeddable && !prop.object) {
47
49
  return Object.values(prop.embeddedProps).map(p => p.name);
48
50
  }
@@ -67,11 +69,12 @@ export function getOnConflictFields(meta, data, uniqueFields, options) {
67
69
  }
68
70
  /** @internal */
69
71
  export function getOnConflictReturningFields(meta, data, uniqueFields, options) {
70
- /* v8 ignore next 3 */
72
+ /* v8 ignore next */
71
73
  if (!meta) {
72
74
  return '*';
73
75
  }
74
- const keys = meta.comparableProps.filter(p => {
76
+ const keys = meta.comparableProps
77
+ .filter(p => {
75
78
  if (p.lazy || p.embeddable) {
76
79
  return false;
77
80
  }
@@ -79,7 +82,8 @@ export function getOnConflictReturningFields(meta, data, uniqueFields, options)
79
82
  return true;
80
83
  }
81
84
  return Array.isArray(uniqueFields) && !uniqueFields.includes(p.name);
82
- }).map(p => p.name);
85
+ })
86
+ .map(p => p.name);
83
87
  if (meta.versionProperty) {
84
88
  keys.push(meta.versionProperty);
85
89
  }
@@ -96,3 +100,45 @@ export function getOnConflictReturningFields(meta, data, uniqueFields, options)
96
100
  }
97
101
  return keys.filter(key => !(key in data));
98
102
  }
103
+ function getPropertyValue(obj, key) {
104
+ if (!key.includes('.')) {
105
+ return obj[key];
106
+ }
107
+ const parts = key.split('.');
108
+ let curr = obj;
109
+ for (let i = 0; i < parts.length - 1; i++) {
110
+ curr[parts[i]] ??= {};
111
+ curr = curr[parts[i]];
112
+ }
113
+ return curr[parts[parts.length - 1]];
114
+ }
115
+ /** @internal */
116
+ export function getWhereCondition(meta, onConflictFields, data, where) {
117
+ const unique = onConflictFields ?? meta.props.filter(p => p.unique).map(p => p.name);
118
+ const propIndex = !isRaw(unique) &&
119
+ unique.findIndex(p => data[p] ?? data[p.substring(0, p.indexOf('.'))] != null);
120
+ if (onConflictFields || where == null) {
121
+ if (propIndex !== false && propIndex >= 0) {
122
+ let key = unique[propIndex];
123
+ if (key.includes('.')) {
124
+ const prop = meta.properties[key.substring(0, key.indexOf('.'))];
125
+ if (prop) {
126
+ key = `${prop.fieldNames[0]}${key.substring(key.indexOf('.'))}`;
127
+ }
128
+ }
129
+ where = { [key]: getPropertyValue(data, unique[propIndex]) };
130
+ }
131
+ else if (meta.uniques.length > 0) {
132
+ for (const u of meta.uniques) {
133
+ if (Utils.asArray(u.properties).every(p => data[p] != null)) {
134
+ where = Utils.asArray(u.properties).reduce((o, key) => {
135
+ o[key] = data[key];
136
+ return o;
137
+ }, {});
138
+ break;
139
+ }
140
+ }
141
+ }
142
+ }
143
+ return { where, propIndex };
144
+ }
@@ -1,3 +0,0 @@
1
- import type { CheckConstraint, EntityClass } from '../typings.js';
2
- export declare function Check<T>(options: CheckOptions<T>): (target: T, propertyName?: T extends EntityClass<unknown> ? undefined : keyof T) => any;
3
- export type CheckOptions<T = any> = CheckConstraint<T>;
@@ -1,13 +0,0 @@
1
- import { MetadataStorage } from '../metadata/MetadataStorage.js';
2
- import { Utils } from '../utils/Utils.js';
3
- export function Check(options) {
4
- return function (target, propertyName) {
5
- const meta = MetadataStorage.getMetadataFromDecorator((propertyName ? target.constructor : target));
6
- options.property ??= propertyName;
7
- meta.checks.push(options);
8
- if (!propertyName) {
9
- return target;
10
- }
11
- return Utils.propertyDecoratorReturnValue();
12
- };
13
- }
@@ -1,3 +0,0 @@
1
- import type { ContextProvider } from '../typings.js';
2
- export declare function CreateRequestContext<T extends object>(context?: ContextProvider<T>, respectExistingContext?: boolean): MethodDecorator;
3
- export declare function EnsureRequestContext<T extends object>(context?: ContextProvider<T>): MethodDecorator;
@@ -1,32 +0,0 @@
1
- import { RequestContext } from '../utils/RequestContext.js';
2
- import { resolveContextProvider } from '../utils/resolveContextProvider.js';
3
- import { TransactionContext } from '../utils/TransactionContext.js';
4
- export function CreateRequestContext(context, respectExistingContext = false) {
5
- return function (target, propertyKey, descriptor) {
6
- const originalMethod = descriptor.value;
7
- const name = respectExistingContext ? 'EnsureRequestContext' : 'CreateRequestContext';
8
- if (originalMethod.constructor.name !== 'AsyncFunction') {
9
- throw new Error(`@${name}() should be use with async functions`);
10
- }
11
- descriptor.value = async function (...args) {
12
- const em = await resolveContextProvider(this, context);
13
- if (!em) {
14
- throw new Error(`@${name}() decorator can only be applied to methods of classes with \`orm: MikroORM\` property, \`em: EntityManager\` property, or with a callback parameter like \`@${name}(() => orm)\` that returns one of those types. The parameter will contain a reference to current \`this\`. Returning an EntityRepository from it is also supported.`);
15
- }
16
- // reuse existing context if available for given respect `contextName`
17
- if (respectExistingContext && RequestContext.getEntityManager(em.name)) {
18
- return originalMethod.apply(this, args);
19
- }
20
- // Otherwise, the outer tx context would be preferred.
21
- const txContext = TransactionContext.currentTransactionContext();
22
- const provider = txContext ? TransactionContext : RequestContext;
23
- return txContext
24
- ? provider.create(em.fork({ useContext: true }), () => originalMethod.apply(this, args))
25
- : provider.create(em, () => originalMethod.apply(this, args));
26
- };
27
- return descriptor;
28
- };
29
- }
30
- export function EnsureRequestContext(context) {
31
- return CreateRequestContext(context, true);
32
- }
@@ -1,8 +0,0 @@
1
- import type { AnyString, Dictionary, EntityClass } from '../typings.js';
2
- export declare function Embeddable<T>(options?: EmbeddableOptions<T>): (target: T) => T;
3
- export interface EmbeddableOptions<T> {
4
- discriminatorColumn?: (T extends EntityClass<infer P> ? keyof P : string) | AnyString;
5
- discriminatorMap?: Dictionary<string>;
6
- discriminatorValue?: number | string;
7
- abstract?: boolean;
8
- }
@@ -1,11 +0,0 @@
1
- import { MetadataStorage } from '../metadata/MetadataStorage.js';
2
- export function Embeddable(options = {}) {
3
- return function (target) {
4
- const meta = MetadataStorage.getMetadataFromDecorator(target);
5
- meta.class = target;
6
- meta.name = meta.class.name;
7
- meta.embeddable = true;
8
- Object.assign(meta, options);
9
- return target;
10
- };
11
- }
@@ -1,12 +0,0 @@
1
- import type { AnyEntity, EntityName } from '../typings.js';
2
- import type { PropertyOptions } from './Property.js';
3
- export declare function Embedded<Owner extends object, Target>(type?: EmbeddedOptions<Owner, Target> | (() => EntityName<Target> | EntityName<Target>[]), options?: EmbeddedOptions<Owner, Target>): (target: AnyEntity, propertyName: string) => any;
4
- /** With `absolute` the prefix is set at the root of the entity (regardless of the nesting level) */
5
- export type EmbeddedPrefixMode = 'absolute' | 'relative';
6
- export interface EmbeddedOptions<Owner, Target> extends PropertyOptions<Owner> {
7
- entity?: string | (() => EntityName<Target> | EntityName<Target>[]);
8
- prefix?: string | boolean;
9
- prefixMode?: EmbeddedPrefixMode;
10
- object?: boolean;
11
- array?: boolean;
12
- }
@@ -1,18 +0,0 @@
1
- import { MetadataValidator } from '../metadata/MetadataValidator.js';
2
- import { MetadataStorage } from '../metadata/MetadataStorage.js';
3
- import { Utils } from '../utils/Utils.js';
4
- import { ReferenceKind } from '../enums.js';
5
- export function Embedded(type = {}, options = {}) {
6
- return function (target, propertyName) {
7
- const meta = MetadataStorage.getMetadataFromDecorator(target.constructor);
8
- MetadataValidator.validateSingleDecorator(meta, propertyName, ReferenceKind.EMBEDDED);
9
- options = type instanceof Function ? { entity: type, ...options } : { ...type, ...options };
10
- Utils.defaultValue(options, 'prefix', true);
11
- meta.properties[propertyName] = {
12
- name: propertyName,
13
- kind: ReferenceKind.EMBEDDED,
14
- ...options,
15
- };
16
- return Utils.propertyDecoratorReturnValue();
17
- };
18
- }