@mikro-orm/cli 7.0.15-dev.9 → 7.0.15

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.
package/CLIHelper.js CHANGED
@@ -2,348 +2,357 @@ import { extname, join } from 'node:path';
2
2
  import { createRequire } from 'node:module';
3
3
  import { fileURLToPath, pathToFileURL } from 'node:url';
4
4
  import yargs from 'yargs';
5
- import { colors, Configuration, loadEnvironmentVars, loadOptionalDependencies, MikroORM, Utils, } from '@mikro-orm/core';
5
+ import { colors, Configuration, loadEnvironmentVars, loadOptionalDependencies, MikroORM, Utils } from '@mikro-orm/core';
6
6
  import { fs } from '@mikro-orm/core/fs-utils';
7
7
  /**
8
8
  * @internal
9
9
  */
10
10
  export class CLIHelper {
11
- /**
12
- * Gets a named configuration
13
- *
14
- * @param contextName Load a config with the given `contextName` value. Used when config file exports array or factory function. Setting it to "default" matches also config objects without `contextName` set.
15
- * @param paths Array of possible paths for a configuration file. Files will be checked in order, and the first existing one will be used. Defaults to the output of {@link fs.getConfigPaths}.
16
- * @param options Additional options to augment the final configuration with.
17
- */
18
- static async getConfiguration(contextName, paths, options = {}) {
19
- this.commonJSCompat(options);
20
- paths ??= await this.getConfigPaths();
21
- const deps = fs.getORMPackages();
22
- if (!deps.has('@mikro-orm/cli') && !process.env.MIKRO_ORM_ALLOW_GLOBAL_CLI) {
23
- throw new Error('@mikro-orm/cli needs to be installed as a local dependency!');
24
- }
25
- contextName ??= process.env.MIKRO_ORM_CONTEXT_NAME ?? 'default';
26
- const env = await this.loadEnvironmentVars();
27
- // oxfmt-ignore
28
- const configFinder = (cfg) => {
11
+ /**
12
+ * Gets a named configuration
13
+ *
14
+ * @param contextName Load a config with the given `contextName` value. Used when config file exports array or factory function. Setting it to "default" matches also config objects without `contextName` set.
15
+ * @param paths Array of possible paths for a configuration file. Files will be checked in order, and the first existing one will be used. Defaults to the output of {@link fs.getConfigPaths}.
16
+ * @param options Additional options to augment the final configuration with.
17
+ */
18
+ static async getConfiguration(contextName, paths, options = {}) {
19
+ this.commonJSCompat(options);
20
+ paths ??= await this.getConfigPaths();
21
+ const deps = fs.getORMPackages();
22
+ if (!deps.has('@mikro-orm/cli') && !process.env.MIKRO_ORM_ALLOW_GLOBAL_CLI) {
23
+ throw new Error('@mikro-orm/cli needs to be installed as a local dependency!');
24
+ }
25
+ contextName ??= process.env.MIKRO_ORM_CONTEXT_NAME ?? 'default';
26
+ const env = await this.loadEnvironmentVars();
27
+ // oxfmt-ignore
28
+ const configFinder = (cfg) => {
29
29
  return typeof cfg === 'object' && cfg !== null && ('contextName' in cfg ? cfg.contextName === contextName : contextName === 'default');
30
30
  };
31
- const isValidConfigFactoryResult = (cfg) => {
32
- return typeof cfg === 'object' && cfg !== null && (!('contextName' in cfg) || cfg.contextName === contextName);
33
- };
34
- const result = await this.getConfigFile(paths);
35
- if (!result[0]) {
36
- if (Utils.hasObjectKeys(env)) {
37
- const merged = Utils.mergeConfig({ contextName }, options.preferEnvVars ? options : env, options.preferEnvVars ? env : options);
38
- await loadOptionalDependencies(merged);
39
- return new Configuration(merged);
40
- }
41
- throw new Error(`MikroORM config file not found in ['${paths.join(`', '`)}']`);
31
+ const isValidConfigFactoryResult = cfg => {
32
+ return typeof cfg === 'object' && cfg !== null && (!('contextName' in cfg) || cfg.contextName === contextName);
33
+ };
34
+ const result = await this.getConfigFile(paths);
35
+ if (!result[0]) {
36
+ if (Utils.hasObjectKeys(env)) {
37
+ const merged = Utils.mergeConfig(
38
+ { contextName },
39
+ options.preferEnvVars ? options : env,
40
+ options.preferEnvVars ? env : options,
41
+ );
42
+ await loadOptionalDependencies(merged);
43
+ return new Configuration(merged);
44
+ }
45
+ throw new Error(`MikroORM config file not found in ['${paths.join(`', '`)}']`);
46
+ }
47
+ const path = result[0];
48
+ let tmp = result[1];
49
+ if (Array.isArray(tmp)) {
50
+ const tmpFirstIndex = tmp.findIndex(configFinder);
51
+ if (tmpFirstIndex === -1) {
52
+ // Static config not found. Try factory functions
53
+ let configCandidate;
54
+ for (let i = 0, l = tmp.length; i < l; ++i) {
55
+ const f = tmp[i];
56
+ if (typeof f !== 'function') {
57
+ continue;
58
+ }
59
+ configCandidate = await f(contextName);
60
+ if (!isValidConfigFactoryResult(configCandidate)) {
61
+ continue;
62
+ }
63
+ tmp = configCandidate;
64
+ break;
42
65
  }
43
- const path = result[0];
44
- let tmp = result[1];
45
66
  if (Array.isArray(tmp)) {
46
- const tmpFirstIndex = tmp.findIndex(configFinder);
47
- if (tmpFirstIndex === -1) {
48
- // Static config not found. Try factory functions
49
- let configCandidate;
50
- for (let i = 0, l = tmp.length; i < l; ++i) {
51
- const f = tmp[i];
52
- if (typeof f !== 'function') {
53
- continue;
54
- }
55
- configCandidate = await f(contextName);
56
- if (!isValidConfigFactoryResult(configCandidate)) {
57
- continue;
58
- }
59
- tmp = configCandidate;
60
- break;
61
- }
62
- if (Array.isArray(tmp)) {
63
- throw new Error(`MikroORM config '${contextName}' was not found within the config file '${path}'. Either add a config with this name to the array, or add a function that when given this name will return a configuration object without a name, or with name set to this name.`);
64
- }
65
- }
66
- else {
67
- const tmpLastIndex = tmp.findLastIndex(configFinder);
68
- if (tmpLastIndex !== tmpFirstIndex) {
69
- throw new Error(`MikroORM config '${contextName}' is not unique within the array exported by '${path}' (first occurrence index: ${tmpFirstIndex}; last occurrence index: ${tmpLastIndex})`);
70
- }
71
- tmp = tmp[tmpFirstIndex];
72
- }
73
- }
74
- else {
75
- if (tmp instanceof Function) {
76
- tmp = await tmp(contextName);
77
- if (!isValidConfigFactoryResult(tmp)) {
78
- throw new Error(`MikroORM config '${contextName}' was not what the function exported from '${path}' provided. Ensure it returns a config object with no name, or name matching the requested one.`);
79
- }
80
- }
81
- else {
82
- if (!configFinder(tmp)) {
83
- throw new Error(`MikroORM config '${contextName}' was not what the default export from '${path}' provided.`);
84
- }
85
- }
67
+ throw new Error(
68
+ `MikroORM config '${contextName}' was not found within the config file '${path}'. Either add a config with this name to the array, or add a function that when given this name will return a configuration object without a name, or with name set to this name.`,
69
+ );
86
70
  }
87
- const esmConfigOptions = this.isESM() ? { entityGenerator: { esmImport: true } } : {};
88
- await loadOptionalDependencies(tmp);
89
- const preferEnvVars = options.preferEnvVars ?? tmp.preferEnvVars;
90
- return new Configuration(Utils.mergeConfig({}, esmConfigOptions, tmp, preferEnvVars ? options : env, preferEnvVars ? env : options));
91
- }
92
- static commonJSCompat(options) {
93
- if (this.isESM()) {
94
- return;
71
+ } else {
72
+ const tmpLastIndex = tmp.findLastIndex(configFinder);
73
+ if (tmpLastIndex !== tmpFirstIndex) {
74
+ throw new Error(
75
+ `MikroORM config '${contextName}' is not unique within the array exported by '${path}' (first occurrence index: ${tmpFirstIndex}; last occurrence index: ${tmpLastIndex})`,
76
+ );
95
77
  }
96
- /* v8 ignore next */
97
- options.dynamicImportProvider ??=
98
- globalThis.dynamicImportProvider ??
99
- ((id) => {
100
- return createRequire(process.cwd())(fileURLToPath(id));
101
- });
102
- globalThis.dynamicImportProvider = options.dynamicImportProvider;
103
- }
104
- static async getORM(contextName, configPaths, opts = {}) {
105
- const options = await this.getConfiguration(contextName, configPaths, opts);
106
- const settings = this.getSettings();
107
- options.set('allowGlobalContext', true);
108
- options.set('debug', !!settings.verbose);
109
- options.getLogger().setDebugMode(!!settings.verbose);
110
- if (settings.preferTs !== false) {
111
- options.set('preferTs', true);
78
+ tmp = tmp[tmpFirstIndex];
79
+ }
80
+ } else {
81
+ if (tmp instanceof Function) {
82
+ tmp = await tmp(contextName);
83
+ if (!isValidConfigFactoryResult(tmp)) {
84
+ throw new Error(
85
+ `MikroORM config '${contextName}' was not what the function exported from '${path}' provided. Ensure it returns a config object with no name, or name matching the requested one.`,
86
+ );
112
87
  }
113
- // The only times when we don't care to have a warning about no entities is also the time when we ignore entities.
114
- if (opts.discovery?.warnWhenNoEntities === false) {
115
- options.set('entities', []);
116
- options.set('entitiesTs', []);
88
+ } else {
89
+ if (!configFinder(tmp)) {
90
+ throw new Error(`MikroORM config '${contextName}' was not what the default export from '${path}' provided.`);
117
91
  }
118
- return MikroORM.init(options.getAll());
92
+ }
119
93
  }
120
- static async isDBConnected(config, reason = false) {
121
- try {
122
- await config.getDriver().connect();
123
- const isConnected = await config.getDriver().getConnection().checkConnection();
124
- await config.getDriver().close();
125
- return isConnected.ok || (reason ? isConnected.reason : false);
126
- }
127
- catch {
128
- return false;
129
- }
94
+ const esmConfigOptions = this.isESM() ? { entityGenerator: { esmImport: true } } : {};
95
+ await loadOptionalDependencies(tmp);
96
+ const preferEnvVars = options.preferEnvVars ?? tmp.preferEnvVars;
97
+ return new Configuration(
98
+ Utils.mergeConfig({}, esmConfigOptions, tmp, preferEnvVars ? options : env, preferEnvVars ? env : options),
99
+ );
100
+ }
101
+ static commonJSCompat(options) {
102
+ if (this.isESM()) {
103
+ return;
130
104
  }
131
- static getDriverDependencies(config) {
132
- try {
133
- return config.getDriver().getDependencies();
134
- }
135
- catch {
136
- return [];
137
- }
105
+ /* v8 ignore next */
106
+ options.dynamicImportProvider ??=
107
+ globalThis.dynamicImportProvider ??
108
+ (id => {
109
+ return createRequire(process.cwd())(fileURLToPath(id));
110
+ });
111
+ globalThis.dynamicImportProvider = options.dynamicImportProvider;
112
+ }
113
+ static async getORM(contextName, configPaths, opts = {}) {
114
+ const options = await this.getConfiguration(contextName, configPaths, opts);
115
+ const settings = this.getSettings();
116
+ options.set('allowGlobalContext', true);
117
+ options.set('debug', !!settings.verbose);
118
+ options.getLogger().setDebugMode(!!settings.verbose);
119
+ if (settings.preferTs !== false) {
120
+ options.set('preferTs', true);
138
121
  }
139
- static dump(text, config) {
140
- if (config?.get('highlighter')) {
141
- text = config.get('highlighter').highlight(text);
142
- }
143
- // eslint-disable-next-line no-console
144
- console.log(text);
122
+ // The only times when we don't care to have a warning about no entities is also the time when we ignore entities.
123
+ if (opts.discovery?.warnWhenNoEntities === false) {
124
+ options.set('entities', []);
125
+ options.set('entitiesTs', []);
145
126
  }
146
- static getSettings() {
147
- const config = fs.getPackageConfig();
148
- const settings = { ...config['mikro-orm'] };
149
- const bool = (v) => ['true', 't', '1'].includes(v.toLowerCase());
150
- settings.preferTs =
151
- process.env.MIKRO_ORM_CLI_PREFER_TS != null ? bool(process.env.MIKRO_ORM_CLI_PREFER_TS) : settings.preferTs;
152
- settings.tsLoader = process.env.MIKRO_ORM_CLI_TS_LOADER ?? settings.tsLoader;
153
- settings.tsConfigPath = process.env.MIKRO_ORM_CLI_TS_CONFIG_PATH ?? settings.tsConfigPath;
154
- settings.verbose =
155
- process.env.MIKRO_ORM_CLI_VERBOSE != null ? bool(process.env.MIKRO_ORM_CLI_VERBOSE) : settings.verbose;
156
- if (process.env.MIKRO_ORM_CLI_CONFIG?.endsWith('.ts')) {
157
- settings.preferTs = true;
158
- }
159
- return settings;
127
+ return MikroORM.init(options.getAll());
128
+ }
129
+ static async isDBConnected(config, reason = false) {
130
+ try {
131
+ await config.getDriver().connect();
132
+ const isConnected = await config.getDriver().getConnection().checkConnection();
133
+ await config.getDriver().close();
134
+ return isConnected.ok || (reason ? isConnected.reason : false);
135
+ } catch {
136
+ return false;
160
137
  }
161
- static async getConfigPaths() {
162
- const settings = this.getSettings();
163
- const typeScriptSupport = settings.preferTs ?? Utils.detectTypeScriptSupport();
164
- const paths = [];
165
- if (process.env.MIKRO_ORM_CLI_CONFIG) {
166
- paths.push(process.env.MIKRO_ORM_CLI_CONFIG);
167
- }
168
- paths.push(...(settings.configPaths || []));
169
- if (typeScriptSupport) {
170
- paths.push('./src/mikro-orm.config.ts');
171
- paths.push('./mikro-orm.config.ts');
172
- }
173
- const distDir = fs.pathExists(process.cwd() + '/dist');
174
- const buildDir = fs.pathExists(process.cwd() + '/build');
175
- /* v8 ignore next */
176
- const path = distDir ? 'dist' : buildDir ? 'build' : 'src';
177
- paths.push(`./${path}/mikro-orm.config.js`);
178
- paths.push('./mikro-orm.config.js');
179
- /* v8 ignore next */
180
- return Utils.unique(paths).filter(p => !/\.[mc]?ts$/.exec(p) || typeScriptSupport);
138
+ }
139
+ static getDriverDependencies(config) {
140
+ try {
141
+ return config.getDriver().getDependencies();
142
+ } catch {
143
+ return [];
181
144
  }
182
- static async getConfigFile(paths) {
183
- for (let path of paths) {
184
- path = fs.absolutePath(path);
185
- path = fs.normalizePath(path);
186
- if (fs.pathExists(path)) {
187
- const config = await fs.dynamicImport(path);
188
- /* v8 ignore next */
189
- return [path, await (config.default ?? config)];
190
- }
191
- }
192
- return [];
145
+ }
146
+ static dump(text, config) {
147
+ if (config?.get('highlighter')) {
148
+ text = config.get('highlighter').highlight(text);
149
+ }
150
+ // eslint-disable-next-line no-console
151
+ console.log(text);
152
+ }
153
+ static getSettings() {
154
+ const config = fs.getPackageConfig();
155
+ const settings = { ...config['mikro-orm'] };
156
+ const bool = v => ['true', 't', '1'].includes(v.toLowerCase());
157
+ settings.preferTs =
158
+ process.env.MIKRO_ORM_CLI_PREFER_TS != null ? bool(process.env.MIKRO_ORM_CLI_PREFER_TS) : settings.preferTs;
159
+ settings.tsLoader = process.env.MIKRO_ORM_CLI_TS_LOADER ?? settings.tsLoader;
160
+ settings.tsConfigPath = process.env.MIKRO_ORM_CLI_TS_CONFIG_PATH ?? settings.tsConfigPath;
161
+ settings.verbose =
162
+ process.env.MIKRO_ORM_CLI_VERBOSE != null ? bool(process.env.MIKRO_ORM_CLI_VERBOSE) : settings.verbose;
163
+ if (process.env.MIKRO_ORM_CLI_CONFIG?.endsWith('.ts')) {
164
+ settings.preferTs = true;
165
+ }
166
+ return settings;
167
+ }
168
+ static async getConfigPaths() {
169
+ const settings = this.getSettings();
170
+ const typeScriptSupport = settings.preferTs ?? Utils.detectTypeScriptSupport();
171
+ const paths = [];
172
+ if (process.env.MIKRO_ORM_CLI_CONFIG) {
173
+ paths.push(process.env.MIKRO_ORM_CLI_CONFIG);
193
174
  }
194
- static async loadEnvironmentVars() {
195
- const ret = loadEnvironmentVars();
175
+ paths.push(...(settings.configPaths || []));
176
+ if (typeScriptSupport) {
177
+ paths.push('./src/mikro-orm.config.ts');
178
+ paths.push('./mikro-orm.config.ts');
179
+ }
180
+ const distDir = fs.pathExists(process.cwd() + '/dist');
181
+ const buildDir = fs.pathExists(process.cwd() + '/build');
182
+ /* v8 ignore next */
183
+ const path = distDir ? 'dist' : buildDir ? 'build' : 'src';
184
+ paths.push(`./${path}/mikro-orm.config.js`);
185
+ paths.push('./mikro-orm.config.js');
186
+ /* v8 ignore next */
187
+ return Utils.unique(paths).filter(p => !/\.[mc]?ts$/.exec(p) || typeScriptSupport);
188
+ }
189
+ static async getConfigFile(paths) {
190
+ for (let path of paths) {
191
+ path = fs.absolutePath(path);
192
+ path = fs.normalizePath(path);
193
+ if (fs.pathExists(path)) {
194
+ const config = await fs.dynamicImport(path);
196
195
  /* v8 ignore next */
197
- switch (process.env.MIKRO_ORM_TYPE) {
198
- case 'mongo':
199
- ret.driver ??= await import('@mikro-orm/sqlite').then(m => m.SqliteDriver);
200
- break;
201
- case 'mysql':
202
- ret.driver ??= await import('@mikro-orm/mysql').then(m => m.MySqlDriver);
203
- break;
204
- case 'mssql':
205
- ret.driver ??= await import('@mikro-orm/mssql').then(m => m.MsSqlDriver);
206
- break;
207
- case 'mariadb':
208
- ret.driver ??= await import('@mikro-orm/mariadb').then(m => m.MariaDbDriver);
209
- break;
210
- case 'postgresql':
211
- ret.driver ??= await import('@mikro-orm/postgresql').then(m => m.PostgreSqlDriver);
212
- break;
213
- case 'sqlite':
214
- ret.driver ??= await import('@mikro-orm/sqlite').then(m => m.SqliteDriver);
215
- break;
216
- case 'libsql':
217
- ret.driver ??= await import('@mikro-orm/libsql').then(m => m.LibSqlDriver);
218
- break;
219
- case 'oracledb':
220
- ret.driver ??= await import('@mikro-orm/oracledb').then(m => m.OracleDriver);
221
- break;
222
- }
223
- return ret;
196
+ return [path, await (config.default ?? config)];
197
+ }
224
198
  }
225
- static dumpDependencies() {
226
- const version = Utils.getORMVersion();
227
- CLIHelper.dump(' - dependencies:');
228
- CLIHelper.dump(` - mikro-orm ${colors.green(version)}`);
229
- CLIHelper.dump(` - node ${colors.green(process.versions.node)}`);
230
- if (fs.pathExists(process.cwd() + '/package.json')) {
231
- /* v8 ignore if */
232
- if (process.versions.bun) {
233
- CLIHelper.dump(` - typescript via bun`);
234
- }
235
- else {
236
- CLIHelper.dump(` - typescript ${CLIHelper.getModuleVersion('typescript')}`);
237
- }
238
- CLIHelper.dump(' - package.json ' + colors.green('found'));
239
- }
240
- else {
241
- CLIHelper.dump(' - package.json ' + colors.red('not found'));
242
- }
199
+ return [];
200
+ }
201
+ static async loadEnvironmentVars() {
202
+ const ret = loadEnvironmentVars();
203
+ /* v8 ignore next */
204
+ switch (process.env.MIKRO_ORM_TYPE) {
205
+ case 'mongo':
206
+ ret.driver ??= await import('@mikro-orm/sqlite').then(m => m.SqliteDriver);
207
+ break;
208
+ case 'mysql':
209
+ ret.driver ??= await import('@mikro-orm/mysql').then(m => m.MySqlDriver);
210
+ break;
211
+ case 'mssql':
212
+ ret.driver ??= await import('@mikro-orm/mssql').then(m => m.MsSqlDriver);
213
+ break;
214
+ case 'mariadb':
215
+ ret.driver ??= await import('@mikro-orm/mariadb').then(m => m.MariaDbDriver);
216
+ break;
217
+ case 'postgresql':
218
+ ret.driver ??= await import('@mikro-orm/postgresql').then(m => m.PostgreSqlDriver);
219
+ break;
220
+ case 'sqlite':
221
+ ret.driver ??= await import('@mikro-orm/sqlite').then(m => m.SqliteDriver);
222
+ break;
223
+ case 'libsql':
224
+ ret.driver ??= await import('@mikro-orm/libsql').then(m => m.LibSqlDriver);
225
+ break;
226
+ case 'oracledb':
227
+ ret.driver ??= await import('@mikro-orm/oracledb').then(m => m.OracleDriver);
228
+ break;
243
229
  }
244
- static getModuleVersion(name) {
245
- try {
246
- const path = `${this.resolveModulePath(name)}/package.json`;
247
- const pkg = fs.readJSONSync(path);
248
- return colors.green(pkg.version);
249
- }
250
- catch {
251
- return '';
252
- }
230
+ return ret;
231
+ }
232
+ static dumpDependencies() {
233
+ const version = Utils.getORMVersion();
234
+ CLIHelper.dump(' - dependencies:');
235
+ CLIHelper.dump(` - mikro-orm ${colors.green(version)}`);
236
+ CLIHelper.dump(` - node ${colors.green(process.versions.node)}`);
237
+ if (fs.pathExists(process.cwd() + '/package.json')) {
238
+ /* v8 ignore if */
239
+ if (process.versions.bun) {
240
+ CLIHelper.dump(` - typescript via bun`);
241
+ } else {
242
+ CLIHelper.dump(` - typescript ${CLIHelper.getModuleVersion('typescript')}`);
243
+ }
244
+ CLIHelper.dump(' - package.json ' + colors.green('found'));
245
+ } else {
246
+ CLIHelper.dump(' - package.json ' + colors.red('not found'));
253
247
  }
254
- /**
255
- * Resolve path to a module.
256
- * @param id The module to require
257
- * @param [from] Location to start the node resolution
258
- */
259
- static resolveModulePath(id, from = process.cwd()) {
260
- if (!extname(from)) {
261
- from = join(from, '__fake.js');
262
- }
263
- const path = fs.normalizePath(import.meta.resolve(id, pathToFileURL(from)));
264
- const parts = path.split('/');
265
- const idx = parts.lastIndexOf(id) + 1;
266
- parts.splice(idx, parts.length - idx);
267
- return parts.join('/');
248
+ }
249
+ static getModuleVersion(name) {
250
+ try {
251
+ const path = `${this.resolveModulePath(name)}/package.json`;
252
+ const pkg = fs.readJSONSync(path);
253
+ return colors.green(pkg.version);
254
+ } catch {
255
+ return '';
268
256
  }
269
- static dumpTable(options) {
270
- if (options.rows.length === 0) {
271
- return CLIHelper.dump(options.empty);
272
- }
273
- const data = [options.columns, ...options.rows];
274
- const lengths = options.columns.map(() => 0);
275
- data.forEach(row => {
276
- row.forEach((cell, idx) => {
277
- lengths[idx] = Math.max(lengths[idx], cell.length + 2);
278
- });
279
- });
280
- let ret = '';
281
- ret += colors.grey('┌' + lengths.map(length => '─'.repeat(length)).join('┬') + '┐\n');
282
- ret +=
283
- colors.grey('│') +
284
- lengths
285
- .map((length, idx) => ' ' + colors.red(options.columns[idx]) + ' '.repeat(length - options.columns[idx].length - 1))
286
- .join(colors.grey('│')) +
287
- colors.grey('│\n');
288
- ret += colors.grey('├' + lengths.map(length => '─'.repeat(length)).join('┼') + '┤\n');
289
- options.rows.forEach(row => {
290
- ret +=
291
- colors.grey('│') +
292
- lengths.map((length, idx) => ' ' + row[idx] + ' '.repeat(length - row[idx].length - 1)).join(colors.grey('│')) +
293
- colors.grey('│\n');
294
- });
295
- ret += colors.grey('└' + lengths.map(length => '─'.repeat(length)).join('┴') + '┘');
296
- CLIHelper.dump(ret);
257
+ }
258
+ /**
259
+ * Resolve path to a module.
260
+ * @param id The module to require
261
+ * @param [from] Location to start the node resolution
262
+ */
263
+ static resolveModulePath(id, from = process.cwd()) {
264
+ if (!extname(from)) {
265
+ from = join(from, '__fake.js');
297
266
  }
298
- /**
299
- * Tries to register TS support in the following order: oxc, swc, tsx, jiti, tsimp
300
- * Use `MIKRO_ORM_CLI_TS_LOADER` env var to set the loader explicitly.
301
- * This method is used only in CLI context.
302
- */
303
- static async registerTypeScriptSupport(configPath = 'tsconfig.json', tsLoader) {
304
- /* v8 ignore if */
305
- if (process.versions.bun) {
306
- return true;
307
- }
308
- process.env.SWC_NODE_PROJECT ??= configPath;
309
- process.env.TSIMP_PROJECT ??= configPath;
310
- process.env.MIKRO_ORM_CLI_ALWAYS_ALLOW_TS ??= '1';
311
- const explicitLoader = tsLoader ?? process.env.MIKRO_ORM_CLI_TS_LOADER ?? 'auto';
312
- const setEsmImportProvider = () => {
313
- return (globalThis.dynamicImportProvider = (id) => import(id).then(mod => mod?.default ?? mod));
314
- };
315
- const loaders = {
316
- oxc: { esm: '@oxc-node/core/register', cjs: '@oxc-node/core/register' },
317
- swc: { esm: '@swc-node/register/esm-register', cjs: '@swc-node/register' },
318
- tsx: { esm: 'tsx/esm/api', cjs: 'tsx/cjs/api', cb: (tsx) => tsx.register({ tsconfig: configPath }) },
319
- jiti: { cjs: 'jiti/register', cb: setEsmImportProvider },
320
- tsimp: { cjs: 'tsimp/import', cb: setEsmImportProvider },
321
- };
322
- for (const loader of Utils.keys(loaders)) {
323
- if (explicitLoader !== 'auto' && loader !== explicitLoader) {
324
- continue;
325
- }
326
- const { esm, cjs, cb } = loaders[loader];
327
- const isEsm = this.isESM();
328
- const module = isEsm && esm ? esm : cjs;
329
- const mod = await Utils.tryImport({ module });
330
- if (mod) {
331
- cb?.(mod);
332
- process.env.MIKRO_ORM_CLI_TS_LOADER = loader;
333
- return true;
334
- }
335
- }
336
- // eslint-disable-next-line no-console
337
- console.warn('Neither `oxc`, `swc`, `tsx`, `jiti` nor `tsimp` found in the project dependencies, support for working with TypeScript files might not work. To use `oxc`, install `@oxc-node/core`. To use `swc`, install both `@swc-node/register` and `@swc/core`.');
338
- return false;
267
+ const path = fs.normalizePath(import.meta.resolve(id, pathToFileURL(from)));
268
+ const parts = path.split('/');
269
+ const idx = parts.lastIndexOf(id) + 1;
270
+ parts.splice(idx, parts.length - idx);
271
+ return parts.join('/');
272
+ }
273
+ static dumpTable(options) {
274
+ if (options.rows.length === 0) {
275
+ return CLIHelper.dump(options.empty);
339
276
  }
340
- static isESM() {
341
- const config = fs.getPackageConfig();
342
- const type = config?.type ?? '';
343
- return type === 'module';
277
+ const data = [options.columns, ...options.rows];
278
+ const lengths = options.columns.map(() => 0);
279
+ data.forEach(row => {
280
+ row.forEach((cell, idx) => {
281
+ lengths[idx] = Math.max(lengths[idx], cell.length + 2);
282
+ });
283
+ });
284
+ let ret = '';
285
+ ret += colors.grey('┌' + lengths.map(length => '─'.repeat(length)).join('┬') + '┐\n');
286
+ ret +=
287
+ colors.grey('│') +
288
+ lengths
289
+ .map(
290
+ (length, idx) =>
291
+ ' ' + colors.red(options.columns[idx]) + ' '.repeat(length - options.columns[idx].length - 1),
292
+ )
293
+ .join(colors.grey('│')) +
294
+ colors.grey('│\n');
295
+ ret += colors.grey('├' + lengths.map(length => '─'.repeat(length)).join('┼') + '┤\n');
296
+ options.rows.forEach(row => {
297
+ ret +=
298
+ colors.grey('│') +
299
+ lengths.map((length, idx) => ' ' + row[idx] + ' '.repeat(length - row[idx].length - 1)).join(colors.grey('│')) +
300
+ colors.grey('│\n');
301
+ });
302
+ ret += colors.grey('└' + lengths.map(length => '─'.repeat(length)).join('┴') + '┘');
303
+ CLIHelper.dump(ret);
304
+ }
305
+ /**
306
+ * Tries to register TS support in the following order: oxc, swc, tsx, jiti, tsimp
307
+ * Use `MIKRO_ORM_CLI_TS_LOADER` env var to set the loader explicitly.
308
+ * This method is used only in CLI context.
309
+ */
310
+ static async registerTypeScriptSupport(configPath = 'tsconfig.json', tsLoader) {
311
+ /* v8 ignore if */
312
+ if (process.versions.bun) {
313
+ return true;
344
314
  }
345
- /* v8 ignore next */
346
- static showHelp() {
347
- yargs(process.argv.slice(2)).showHelp();
315
+ process.env.SWC_NODE_PROJECT ??= configPath;
316
+ process.env.TSIMP_PROJECT ??= configPath;
317
+ process.env.MIKRO_ORM_CLI_ALWAYS_ALLOW_TS ??= '1';
318
+ const explicitLoader = tsLoader ?? process.env.MIKRO_ORM_CLI_TS_LOADER ?? 'auto';
319
+ const setEsmImportProvider = () => {
320
+ return (globalThis.dynamicImportProvider = id => import(id).then(mod => mod?.default ?? mod));
321
+ };
322
+ const loaders = {
323
+ oxc: { esm: '@oxc-node/core/register', cjs: '@oxc-node/core/register' },
324
+ swc: { esm: '@swc-node/register/esm-register', cjs: '@swc-node/register' },
325
+ tsx: { esm: 'tsx/esm/api', cjs: 'tsx/cjs/api', cb: tsx => tsx.register({ tsconfig: configPath }) },
326
+ jiti: { cjs: 'jiti/register', cb: setEsmImportProvider },
327
+ tsimp: { cjs: 'tsimp/import', cb: setEsmImportProvider },
328
+ };
329
+ for (const loader of Utils.keys(loaders)) {
330
+ if (explicitLoader !== 'auto' && loader !== explicitLoader) {
331
+ continue;
332
+ }
333
+ const { esm, cjs, cb } = loaders[loader];
334
+ const isEsm = this.isESM();
335
+ const module = isEsm && esm ? esm : cjs;
336
+ const mod = await Utils.tryImport({ module });
337
+ if (mod) {
338
+ cb?.(mod);
339
+ process.env.MIKRO_ORM_CLI_TS_LOADER = loader;
340
+ return true;
341
+ }
348
342
  }
343
+ // eslint-disable-next-line no-console
344
+ console.warn(
345
+ 'Neither `oxc`, `swc`, `tsx`, `jiti` nor `tsimp` found in the project dependencies, support for working with TypeScript files might not work. To use `oxc`, install `@oxc-node/core`. To use `swc`, install both `@swc-node/register` and `@swc/core`.',
346
+ );
347
+ return false;
348
+ }
349
+ static isESM() {
350
+ const config = fs.getPackageConfig();
351
+ const type = config?.type ?? '';
352
+ return type === 'module';
353
+ }
354
+ /* v8 ignore next */
355
+ static showHelp() {
356
+ yargs(process.argv.slice(2)).showHelp();
357
+ }
349
358
  }