mongodb-memory-server-core 8.15.1 → 9.0.0-beta.2

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 (52) hide show
  1. package/lib/MongoMemoryReplSet.d.ts +4 -20
  2. package/lib/MongoMemoryReplSet.d.ts.map +1 -1
  3. package/lib/MongoMemoryReplSet.js +283 -294
  4. package/lib/MongoMemoryReplSet.js.map +1 -1
  5. package/lib/MongoMemoryServer.d.ts +13 -26
  6. package/lib/MongoMemoryServer.d.ts.map +1 -1
  7. package/lib/MongoMemoryServer.js +340 -332
  8. package/lib/MongoMemoryServer.js.map +1 -1
  9. package/lib/util/DryMongoBinary.d.ts +2 -2
  10. package/lib/util/DryMongoBinary.d.ts.map +1 -1
  11. package/lib/util/DryMongoBinary.js +158 -172
  12. package/lib/util/DryMongoBinary.js.map +1 -1
  13. package/lib/util/MongoBinary.js +85 -85
  14. package/lib/util/MongoBinary.js.map +1 -1
  15. package/lib/util/MongoBinaryDownload.d.ts +2 -11
  16. package/lib/util/MongoBinaryDownload.d.ts.map +1 -1
  17. package/lib/util/MongoBinaryDownload.js +210 -262
  18. package/lib/util/MongoBinaryDownload.js.map +1 -1
  19. package/lib/util/MongoBinaryDownloadUrl.d.ts +3 -5
  20. package/lib/util/MongoBinaryDownloadUrl.d.ts.map +1 -1
  21. package/lib/util/MongoBinaryDownloadUrl.js +70 -100
  22. package/lib/util/MongoBinaryDownloadUrl.js.map +1 -1
  23. package/lib/util/MongoInstance.d.ts +3 -1
  24. package/lib/util/MongoInstance.d.ts.map +1 -1
  25. package/lib/util/MongoInstance.js +125 -126
  26. package/lib/util/MongoInstance.js.map +1 -1
  27. package/lib/util/errors.d.ts +10 -9
  28. package/lib/util/errors.d.ts.map +1 -1
  29. package/lib/util/errors.js +16 -27
  30. package/lib/util/errors.js.map +1 -1
  31. package/lib/util/getos/index.d.ts +1 -1
  32. package/lib/util/getos/index.d.ts.map +1 -1
  33. package/lib/util/getos/index.js +53 -59
  34. package/lib/util/getos/index.js.map +1 -1
  35. package/lib/util/getport/index.d.ts +34 -0
  36. package/lib/util/getport/index.d.ts.map +1 -0
  37. package/lib/util/getport/index.js +108 -0
  38. package/lib/util/getport/index.js.map +1 -0
  39. package/lib/util/lockfile.d.ts.map +1 -1
  40. package/lib/util/lockfile.js +155 -169
  41. package/lib/util/lockfile.js.map +1 -1
  42. package/lib/util/postinstallHelper.js +15 -18
  43. package/lib/util/postinstallHelper.js.map +1 -1
  44. package/lib/util/resolveConfig.d.ts +1 -1
  45. package/lib/util/resolveConfig.d.ts.map +1 -1
  46. package/lib/util/resolveConfig.js +10 -9
  47. package/lib/util/resolveConfig.js.map +1 -1
  48. package/lib/util/utils.d.ts +20 -4
  49. package/lib/util/utils.d.ts.map +1 -1
  50. package/lib/util/utils.js +135 -118
  51. package/lib/util/utils.js.map +1 -1
  52. package/package.json +9 -12
@@ -2,15 +2,17 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MongoMemoryServer = exports.MongoMemoryServerStates = exports.MongoMemoryServerEvents = void 0;
4
4
  const tslib_1 = require("tslib");
5
- const get_port_1 = (0, tslib_1.__importDefault)(require("get-port"));
5
+ const getport_1 = require("./util/getport");
6
6
  const utils_1 = require("./util/utils");
7
7
  const MongoInstance_1 = require("./util/MongoInstance");
8
- const debug_1 = (0, tslib_1.__importDefault)(require("debug"));
8
+ const debug_1 = tslib_1.__importDefault(require("debug"));
9
9
  const events_1 = require("events");
10
10
  const fs_1 = require("fs");
11
11
  const mongodb_1 = require("mongodb");
12
12
  const errors_1 = require("./util/errors");
13
- const os = (0, tslib_1.__importStar)(require("os"));
13
+ const os = tslib_1.__importStar(require("os"));
14
+ const DryMongoBinary_1 = require("./util/DryMongoBinary");
15
+ const semver = tslib_1.__importStar(require("semver"));
14
16
  const log = (0, debug_1.default)('MongoMS:MongoMemoryServer');
15
17
  /**
16
18
  * All Events for "MongoMemoryServer"
@@ -40,9 +42,13 @@ class MongoMemoryServer extends events_1.EventEmitter {
40
42
  * The Current State of this instance
41
43
  */
42
44
  this._state = MongoMemoryServerStates.new;
43
- this.opts = Object.assign({}, opts);
44
- // TODO: consider changing this to not be set if "instance.auth" is false in 9.0
45
- if (!(0, utils_1.isNullOrUndefined)(this.opts.auth)) {
45
+ this.opts = { ...opts };
46
+ // instance option "auth" will be automatically set and handled via AutomaticAuth
47
+ if ('auth' in (this.opts.instance ?? {})) {
48
+ log('opts.instance.auth was defined, but will be set automatically, ignoring');
49
+ delete this.opts.instance?.auth;
50
+ }
51
+ if (this.opts.auth?.enable === true) {
46
52
  // assign defaults
47
53
  this.auth = (0, utils_1.authDefault)(this.opts.auth);
48
54
  }
@@ -51,53 +57,47 @@ class MongoMemoryServer extends events_1.EventEmitter {
51
57
  * Create a Mongo-Memory-Sever Instance that can be awaited
52
58
  * @param opts Mongo-Memory-Sever Options
53
59
  */
54
- static create(opts) {
55
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
56
- log('create: Called .create() method');
57
- const instance = new MongoMemoryServer(Object.assign({}, opts));
58
- yield instance.start();
59
- return instance;
60
- });
60
+ static async create(opts) {
61
+ log('create: Called .create() method');
62
+ const instance = new MongoMemoryServer({ ...opts });
63
+ await instance.start();
64
+ return instance;
61
65
  }
62
66
  /**
63
67
  * Start the Mongod Instance
64
68
  * @param forceSamePort Force to use the Same Port, if already an "instanceInfo" exists
65
69
  * @throws if state is not "new" or "stopped"
66
70
  */
67
- start(forceSamePort = false) {
68
- var _a;
69
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
70
- this.debug('start: Called .start() method');
71
- switch (this._state) {
72
- case MongoMemoryServerStates.new:
73
- case MongoMemoryServerStates.stopped:
74
- break;
75
- case MongoMemoryServerStates.running:
76
- case MongoMemoryServerStates.starting:
77
- default:
78
- throw new errors_1.StateError([MongoMemoryServerStates.new, MongoMemoryServerStates.stopped], this.state);
79
- }
80
- (0, utils_1.assertion)((0, utils_1.isNullOrUndefined)((_a = this._instanceInfo) === null || _a === void 0 ? void 0 : _a.instance.mongodProcess), new Error('Cannot start because "instance.mongodProcess" is already defined!'));
81
- this.stateChange(MongoMemoryServerStates.starting);
82
- yield this._startUpInstance(forceSamePort).catch((err) => (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
83
- var _b;
84
- // add error information on macos-arm because "spawn Unknown system error -86" does not say much
85
- if (err instanceof Error && ((_b = err.message) === null || _b === void 0 ? void 0 : _b.includes('spawn Unknown system error -86'))) {
86
- if (os.platform() === 'darwin' && os.arch() === 'arm64') {
87
- err.message += err.message += ', Is Rosetta Installed and Setup correctly?';
88
- }
89
- }
90
- if (!debug_1.default.enabled('MongoMS:MongoMemoryServer')) {
91
- console.warn('Starting the MongoMemoryServer Instance failed, enable debug log for more information. Error:\n', err);
71
+ async start(forceSamePort = false) {
72
+ this.debug('start: Called .start() method');
73
+ switch (this._state) {
74
+ case MongoMemoryServerStates.new:
75
+ case MongoMemoryServerStates.stopped:
76
+ break;
77
+ case MongoMemoryServerStates.running:
78
+ case MongoMemoryServerStates.starting:
79
+ default:
80
+ throw new errors_1.StateError([MongoMemoryServerStates.new, MongoMemoryServerStates.stopped], this.state);
81
+ }
82
+ (0, utils_1.assertion)((0, utils_1.isNullOrUndefined)(this._instanceInfo?.instance.mongodProcess), new Error('Cannot start because "instance.mongodProcess" is already defined!'));
83
+ this.stateChange(MongoMemoryServerStates.starting);
84
+ await this._startUpInstance(forceSamePort).catch(async (err) => {
85
+ // add error information on macos-arm because "spawn Unknown system error -86" does not say much
86
+ if (err instanceof Error && err.message?.includes('spawn Unknown system error -86')) {
87
+ if (os.platform() === 'darwin' && os.arch() === 'arm64') {
88
+ err.message += err.message += ', Is Rosetta Installed and Setup correctly?';
92
89
  }
93
- this.debug('_startUpInstance threw a Error: ', err);
94
- yield this.stop({ doCleanup: false, force: false }); // still try to close the instance that was spawned, without cleanup for investigation
95
- this.stateChange(MongoMemoryServerStates.stopped);
96
- throw err;
97
- }));
98
- this.stateChange(MongoMemoryServerStates.running);
99
- this.debug('start: Instance fully Started');
90
+ }
91
+ if (!debug_1.default.enabled('MongoMS:MongoMemoryServer')) {
92
+ console.warn('Starting the MongoMemoryServer Instance failed, enable debug log for more information. Error:\n', err);
93
+ }
94
+ this.debug('_startUpInstance threw a Error: ', err);
95
+ await this.stop({ doCleanup: false, force: false }); // still try to close the instance that was spawned, without cleanup for investigation
96
+ this.stateChange(MongoMemoryServerStates.stopped);
97
+ throw err;
100
98
  });
99
+ this.stateChange(MongoMemoryServerStates.running);
100
+ this.debug('start: Instance fully Started');
101
101
  }
102
102
  /**
103
103
  * Change "this._state" to "newState" and emit "stateChange" with "newState"
@@ -112,217 +112,228 @@ class MongoMemoryServer extends events_1.EventEmitter {
112
112
  * @param msg The Message to log
113
113
  */
114
114
  debug(msg, ...extra) {
115
- var _a, _b;
116
- const port = (_b = (_a = this._instanceInfo) === null || _a === void 0 ? void 0 : _a.port) !== null && _b !== void 0 ? _b : 'unknown';
115
+ const port = this._instanceInfo?.port ?? 'unknown';
117
116
  log(`Mongo[${port}]: ${msg}`, ...extra);
118
117
  }
119
118
  /**
120
119
  * Find a new unlocked port
121
120
  * @param port A User defined default port
122
121
  */
123
- getNewPort(port) {
124
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
125
- const newPort = yield (0, get_port_1.default)({ port });
126
- // only log this message if a custom port was provided
127
- if (port != newPort && typeof port === 'number') {
128
- this.debug(`getNewPort: starting with port "${newPort}", since "${port}" was locked`);
129
- }
130
- return newPort;
131
- });
122
+ async getNewPort(port) {
123
+ const newPort = await (0, getport_1.getFreePort)(port);
124
+ // only log this message if a custom port was provided
125
+ if (port != newPort && typeof port === 'number') {
126
+ this.debug(`getNewPort: starting with port "${newPort}", since "${port}" was locked`);
127
+ }
128
+ return newPort;
132
129
  }
133
130
  /**
134
131
  * Construct Instance Starting Options
135
132
  */
136
- getStartOptions(forceSamePort = false) {
137
- var _a, _b, _c;
138
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
139
- this.debug(`getStartOptions: forceSamePort: ${forceSamePort}`);
140
- /** Shortcut to this.opts.instance */
141
- const instOpts = (_a = this.opts.instance) !== null && _a !== void 0 ? _a : {};
142
- /**
143
- * This variable is used for determining if "createAuth" should be run
144
- */
145
- let isNew = true;
146
- // use pre-defined port if available, otherwise generate a new port
147
- let port = typeof instOpts.port === 'number' ? instOpts.port : undefined;
148
- // if "forceSamePort" is not true, and get a available port
149
- if (!forceSamePort || (0, utils_1.isNullOrUndefined)(port)) {
150
- port = yield this.getNewPort(port);
133
+ async getStartOptions(forceSamePort = false) {
134
+ this.debug(`getStartOptions: forceSamePort: ${forceSamePort}`);
135
+ /** Shortcut to this.opts.instance */
136
+ const instOpts = this.opts.instance ?? {};
137
+ /**
138
+ * This variable is used for determining if "createAuth" should be run
139
+ */
140
+ let isNew = true;
141
+ // use pre-defined port if available, otherwise generate a new port
142
+ let port = typeof instOpts.port === 'number' ? instOpts.port : undefined;
143
+ // if "forceSamePort" is not true, and get a available port
144
+ if (!forceSamePort || (0, utils_1.isNullOrUndefined)(port)) {
145
+ port = await this.getNewPort(port);
146
+ }
147
+ const opts = await DryMongoBinary_1.DryMongoBinary.generateOptions(this.opts.binary);
148
+ let storageEngine = instOpts.storageEngine;
149
+ // warn when storage engine "ephemeralForTest" is explicitly used and switch to "wiredTiger"
150
+ if (storageEngine === 'ephemeralForTest' && semver.gte(opts.version, '7.0.0')) {
151
+ console.warn('Storage Engine "ephemeralForTest" is removed since mongodb 7.0.0, automatically using "wiredTiger"!\n' +
152
+ 'This warning is because the mentioned storage engine is explicitly used and mongodb version is 7.0.0 or higher');
153
+ storageEngine = 'wiredTiger';
154
+ }
155
+ if ((0, utils_1.isNullOrUndefined)(storageEngine)) {
156
+ if (semver.gte(opts.version, '7.0.0')) {
157
+ storageEngine = 'wiredTiger';
151
158
  }
152
- // consider directly using "this.opts.instance", to pass through all options, even if not defined in "StartupInstanceData"
153
- const data = {
154
- port: port,
155
- dbName: (0, utils_1.generateDbName)(instOpts.dbName),
156
- ip: (_b = instOpts.ip) !== null && _b !== void 0 ? _b : '127.0.0.1',
157
- storageEngine: (_c = instOpts.storageEngine) !== null && _c !== void 0 ? _c : 'ephemeralForTest',
158
- replSet: instOpts.replSet,
159
- dbPath: instOpts.dbPath,
160
- tmpDir: undefined,
161
- keyfileLocation: instOpts.keyfileLocation,
162
- launchTimeout: instOpts.launchTimeout,
163
- };
164
- if ((0, utils_1.isNullOrUndefined)(this._instanceInfo)) {
165
- // create a tmpDir instance if no "dbPath" is given
166
- if (!data.dbPath) {
167
- data.tmpDir = yield (0, utils_1.createTmpDir)('mongo-mem-');
168
- data.dbPath = data.tmpDir;
169
- isNew = true; // just to ensure "isNew" is "true" because a new temporary directory got created
170
- }
171
- else {
172
- this.debug(`getStartOptions: Checking if "${data.dbPath}}" (no new tmpDir) already has data`);
173
- const files = yield fs_1.promises.readdir(data.dbPath);
174
- isNew = files.length === 0; // if there are no files in the directory, assume that the database is new
175
- }
159
+ else {
160
+ storageEngine = 'ephemeralForTest';
161
+ }
162
+ }
163
+ // consider directly using "this.opts.instance", to pass through all options, even if not defined in "StartupInstanceData"
164
+ const data = {
165
+ port: port,
166
+ dbName: (0, utils_1.generateDbName)(instOpts.dbName),
167
+ ip: instOpts.ip ?? '127.0.0.1',
168
+ storageEngine: storageEngine,
169
+ replSet: instOpts.replSet,
170
+ dbPath: instOpts.dbPath,
171
+ tmpDir: undefined,
172
+ keyfileLocation: instOpts.keyfileLocation,
173
+ launchTimeout: instOpts.launchTimeout,
174
+ };
175
+ if ((0, utils_1.isNullOrUndefined)(this._instanceInfo)) {
176
+ // create a tmpDir instance if no "dbPath" is given
177
+ if (!data.dbPath) {
178
+ data.tmpDir = await (0, utils_1.createTmpDir)('mongo-mem-');
179
+ data.dbPath = data.tmpDir;
180
+ isNew = true; // just to ensure "isNew" is "true" because a new temporary directory got created
176
181
  }
177
182
  else {
178
- isNew = false;
183
+ this.debug(`getStartOptions: Checking if "${data.dbPath}}" (no new tmpDir) already has data`);
184
+ const files = await fs_1.promises.readdir(data.dbPath);
185
+ isNew = files.length === 0; // if there are no files in the directory, assume that the database is new
179
186
  }
180
- const enableAuth = (typeof instOpts.auth === 'boolean' ? instOpts.auth : true) && // check if auth is even meant to be enabled
181
- this.authObjectEnable();
182
- const createAuth = enableAuth && // re-use all the checks from "enableAuth"
183
- !(0, utils_1.isNullOrUndefined)(this.auth) && // needs to be re-checked because typescript complains
184
- (this.auth.force || isNew) && // check that either "isNew" or "this.auth.force" is "true"
185
- !instOpts.replSet; // dont run "createAuth" when its a replset, it will be run by the replset controller
186
- return {
187
- data: data,
188
- createAuth: createAuth,
189
- mongodOptions: {
190
- instance: Object.assign(Object.assign({}, data), { args: instOpts.args, auth: enableAuth }),
191
- binary: this.opts.binary,
192
- spawn: this.opts.spawn,
187
+ }
188
+ else {
189
+ isNew = false;
190
+ }
191
+ const enableAuth = this.authObjectEnable();
192
+ const createAuth = enableAuth && // re-use all the checks from "enableAuth"
193
+ !(0, utils_1.isNullOrUndefined)(this.auth) && // needs to be re-checked because typescript complains
194
+ (this.auth.force || isNew) && // check that either "isNew" or "this.auth.force" is "true"
195
+ !instOpts.replSet; // dont run "createAuth" when its a replset, it will be run by the replset controller
196
+ return {
197
+ data: data,
198
+ createAuth: createAuth,
199
+ mongodOptions: {
200
+ instance: {
201
+ ...data,
202
+ args: instOpts.args,
203
+ auth: enableAuth,
193
204
  },
194
- };
195
- });
205
+ binary: this.opts.binary,
206
+ spawn: this.opts.spawn,
207
+ },
208
+ };
196
209
  }
197
210
  /**
198
211
  * Internal Function to start an instance
199
212
  * @param forceSamePort Force to use the Same Port, if already an "instanceInfo" exists
200
213
  * @private
201
214
  */
202
- _startUpInstance(forceSamePort = false) {
203
- var _a, _b;
204
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
205
- this.debug('_startUpInstance: Called MongoMemoryServer._startUpInstance() method');
206
- if (!(0, utils_1.isNullOrUndefined)(this._instanceInfo)) {
207
- this.debug('_startUpInstance: "instanceInfo" already defined, reusing instance');
208
- if (!forceSamePort) {
209
- const newPort = yield this.getNewPort(this._instanceInfo.port);
210
- this._instanceInfo.instance.instanceOpts.port = newPort;
211
- this._instanceInfo.port = newPort;
212
- }
213
- yield this._instanceInfo.instance.start();
214
- return;
215
- }
216
- const { mongodOptions, createAuth, data } = yield this.getStartOptions(forceSamePort);
217
- this.debug(`_startUpInstance: Creating new MongoDB instance with options:`, mongodOptions);
218
- const instance = yield MongoInstance_1.MongoInstance.create(mongodOptions);
219
- this.debug(`_startUpInstance: Instance Started, createAuth: "${createAuth}"`);
220
- this._instanceInfo = Object.assign(Object.assign({}, data), { dbPath: data.dbPath, // because otherwise the types would be incompatible
221
- instance });
222
- // always set the "extraConnectionOptions" when "auth" is enabled, regardless of if "createAuth" gets run
223
- if (this.authObjectEnable() &&
224
- ((_a = mongodOptions.instance) === null || _a === void 0 ? void 0 : _a.auth) === true &&
225
- !(0, utils_1.isNullOrUndefined)(this.auth) // extra check again for typescript, because it cant reuse checks from "enableAuth" yet
226
- ) {
227
- instance.extraConnectionOptions = {
228
- authSource: 'admin',
229
- authMechanism: 'SCRAM-SHA-256',
230
- auth: {
231
- username: this.auth.customRootName,
232
- password: this.auth.customRootPwd,
233
- },
234
- };
235
- }
236
- // "isNullOrUndefined" because otherwise typescript complains about "this.auth" possibly being not defined
237
- if (!(0, utils_1.isNullOrUndefined)(this.auth) && createAuth) {
238
- this.debug(`_startUpInstance: Running "createAuth" (force: "${this.auth.force}")`);
239
- yield this.createAuth(data);
240
- }
241
- else {
242
- // extra "if" to log when "disable" is set to "true"
243
- if ((_b = this.opts.auth) === null || _b === void 0 ? void 0 : _b.disable) {
244
- this.debug('_startUpInstance: AutomaticAuth.disable is set to "true" skipping "createAuth"');
245
- }
215
+ async _startUpInstance(forceSamePort = false) {
216
+ this.debug('_startUpInstance: Called MongoMemoryServer._startUpInstance() method');
217
+ if (!(0, utils_1.isNullOrUndefined)(this._instanceInfo)) {
218
+ this.debug('_startUpInstance: "instanceInfo" already defined, reusing instance');
219
+ if (!forceSamePort) {
220
+ const newPort = await this.getNewPort(this._instanceInfo.port);
221
+ this._instanceInfo.instance.instanceOpts.port = newPort;
222
+ this._instanceInfo.port = newPort;
246
223
  }
247
- });
224
+ await this._instanceInfo.instance.start();
225
+ return;
226
+ }
227
+ const { mongodOptions, createAuth, data } = await this.getStartOptions(forceSamePort);
228
+ this.debug(`_startUpInstance: Creating new MongoDB instance with options:`, mongodOptions);
229
+ const instance = await MongoInstance_1.MongoInstance.create(mongodOptions);
230
+ this.debug(`_startUpInstance: Instance Started, createAuth: "${createAuth}"`);
231
+ this._instanceInfo = {
232
+ ...data,
233
+ dbPath: data.dbPath,
234
+ instance,
235
+ };
236
+ // always set the "extraConnectionOptions" when "auth" is enabled, regardless of if "createAuth" gets run
237
+ if (this.authObjectEnable() &&
238
+ mongodOptions.instance?.auth === true &&
239
+ !(0, utils_1.isNullOrUndefined)(this.auth) // extra check again for typescript, because it cant reuse checks from "enableAuth" yet
240
+ ) {
241
+ instance.extraConnectionOptions = {
242
+ authSource: 'admin',
243
+ authMechanism: 'SCRAM-SHA-256',
244
+ auth: {
245
+ username: this.auth.customRootName,
246
+ password: this.auth.customRootPwd,
247
+ },
248
+ };
249
+ }
250
+ // "isNullOrUndefined" because otherwise typescript complains about "this.auth" possibly being not defined
251
+ if (!(0, utils_1.isNullOrUndefined)(this.auth) && createAuth) {
252
+ this.debug(`_startUpInstance: Running "createAuth" (force: "${this.auth.force}")`);
253
+ await this.createAuth(data);
254
+ }
248
255
  }
249
- stop(cleanupOptions) {
250
- var _a, _b;
251
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
252
- this.debug('stop: Called .stop() method');
253
- /** Default to cleanup temporary, but not custom dbpaths */
254
- let cleanup = { doCleanup: true, force: false };
255
- // handle the old way of setting wheter to cleanup or not
256
- // TODO: for next major release (9.0), this should be removed
257
- if (typeof cleanupOptions === 'boolean') {
258
- cleanup.doCleanup = cleanupOptions;
259
- }
260
- // handle the new way of setting what and how to cleanup
261
- if (typeof cleanupOptions === 'object') {
262
- cleanup = cleanupOptions;
263
- }
264
- // just return "true" if there was never an instance
265
- if ((0, utils_1.isNullOrUndefined)(this._instanceInfo)) {
266
- this.debug('stop: "instanceInfo" is not defined (never ran?)');
267
- return false;
268
- }
269
- if (this._state === MongoMemoryServerStates.stopped) {
270
- this.debug('stop: state is "stopped", trying to stop / kill anyway');
271
- }
272
- this.debug(`stop: Stopping MongoDB server on port ${this._instanceInfo.port} with pid ${(_b = (_a = this._instanceInfo.instance) === null || _a === void 0 ? void 0 : _a.mongodProcess) === null || _b === void 0 ? void 0 : _b.pid}` // "undefined" would say more than ""
273
- );
274
- yield this._instanceInfo.instance.stop();
275
- this.stateChange(MongoMemoryServerStates.stopped);
276
- if (cleanup.doCleanup) {
277
- yield this.cleanup(cleanup);
278
- }
279
- return true;
280
- });
256
+ /**
257
+ * Stop the current In-Memory Instance
258
+ * @param cleanupOptions Set how to run ".cleanup", by default only `{ doCleanup: true }` is used
259
+ */
260
+ async stop(cleanupOptions) {
261
+ this.debug('stop: Called .stop() method');
262
+ /** Default to cleanup temporary, but not custom dbpaths */
263
+ let cleanup = { doCleanup: true, force: false };
264
+ // TODO: for next major release (10.0), this should be removed
265
+ if (typeof cleanupOptions === 'boolean') {
266
+ throw new Error('Unsupported argument type: boolean');
267
+ }
268
+ // handle the new way of setting what and how to cleanup
269
+ if (typeof cleanupOptions === 'object') {
270
+ cleanup = cleanupOptions;
271
+ }
272
+ // just return "true" if there was never an instance
273
+ if ((0, utils_1.isNullOrUndefined)(this._instanceInfo)) {
274
+ this.debug('stop: "instanceInfo" is not defined (never ran?)');
275
+ return false;
276
+ }
277
+ if (this._state === MongoMemoryServerStates.stopped) {
278
+ this.debug('stop: state is "stopped", trying to stop / kill anyway');
279
+ }
280
+ this.debug(`stop: Stopping MongoDB server on port ${this._instanceInfo.port} with pid ${this._instanceInfo.instance?.mongodProcess?.pid}` // "undefined" would say more than ""
281
+ );
282
+ await this._instanceInfo.instance.stop();
283
+ this.stateChange(MongoMemoryServerStates.stopped);
284
+ if (cleanup.doCleanup) {
285
+ await this.cleanup(cleanup);
286
+ }
287
+ return true;
281
288
  }
282
- cleanup(options) {
283
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
284
- assertionIsMMSState(MongoMemoryServerStates.stopped, this.state);
285
- /** Default to doing cleanup, but not forcing it */
286
- let cleanup = { doCleanup: true, force: false };
287
- // handle the old way of setting wheter to cleanup or not
288
- // TODO: for next major release (9.0), this should be removed
289
- if (typeof options === 'boolean') {
290
- cleanup.force = options;
291
- }
292
- // handle the new way of setting what and how to cleanup
293
- if (typeof options === 'object') {
294
- cleanup = options;
295
- }
296
- this.debug(`cleanup:`, cleanup);
297
- // dont do cleanup, if "doCleanup" is false
298
- if (!cleanup.doCleanup) {
299
- this.debug('cleanup: "doCleanup" is set to false');
300
- return;
301
- }
302
- if ((0, utils_1.isNullOrUndefined)(this._instanceInfo)) {
303
- this.debug('cleanup: "instanceInfo" is undefined');
304
- return;
305
- }
306
- (0, utils_1.assertion)((0, utils_1.isNullOrUndefined)(this._instanceInfo.instance.mongodProcess), new Error('Cannot cleanup because "instance.mongodProcess" is still defined'));
307
- const tmpDir = this._instanceInfo.tmpDir;
308
- if (!(0, utils_1.isNullOrUndefined)(tmpDir)) {
309
- this.debug(`cleanup: removing tmpDir at ${tmpDir}`);
310
- yield (0, utils_1.removeDir)(tmpDir);
289
+ /**
290
+ * Remove the defined dbPath
291
+ * @param options Set how to run a cleanup, by default `{ doCleanup: true }` is used
292
+ * @throws If "state" is not "stopped"
293
+ * @throws If "instanceInfo" is not defined
294
+ * @throws If an fs error occured
295
+ */
296
+ async cleanup(options) {
297
+ assertionIsMMSState(MongoMemoryServerStates.stopped, this.state);
298
+ /** Default to doing cleanup, but not forcing it */
299
+ let cleanup = { doCleanup: true, force: false };
300
+ // TODO: for next major release (10.0), this should be removed
301
+ if (typeof options === 'boolean') {
302
+ throw new Error('Unsupported argument type: boolean');
303
+ }
304
+ // handle the new way of setting what and how to cleanup
305
+ if (typeof options === 'object') {
306
+ cleanup = options;
307
+ }
308
+ this.debug(`cleanup:`, cleanup);
309
+ // dont do cleanup, if "doCleanup" is false
310
+ if (!cleanup.doCleanup) {
311
+ this.debug('cleanup: "doCleanup" is set to false');
312
+ return;
313
+ }
314
+ if ((0, utils_1.isNullOrUndefined)(this._instanceInfo)) {
315
+ this.debug('cleanup: "instanceInfo" is undefined');
316
+ return;
317
+ }
318
+ (0, utils_1.assertion)((0, utils_1.isNullOrUndefined)(this._instanceInfo.instance.mongodProcess), new Error('Cannot cleanup because "instance.mongodProcess" is still defined'));
319
+ const tmpDir = this._instanceInfo.tmpDir;
320
+ if (!(0, utils_1.isNullOrUndefined)(tmpDir)) {
321
+ this.debug(`cleanup: removing tmpDir at ${tmpDir}`);
322
+ await (0, utils_1.removeDir)(tmpDir);
323
+ }
324
+ if (cleanup.force) {
325
+ const dbPath = this._instanceInfo.dbPath;
326
+ const res = await (0, utils_1.statPath)(dbPath);
327
+ if ((0, utils_1.isNullOrUndefined)(res)) {
328
+ this.debug(`cleanup: force is true, but path "${dbPath}" dosnt exist anymore`);
311
329
  }
312
- if (cleanup.force) {
313
- const dbPath = this._instanceInfo.dbPath;
314
- const res = yield (0, utils_1.statPath)(dbPath);
315
- if ((0, utils_1.isNullOrUndefined)(res)) {
316
- this.debug(`cleanup: force is true, but path "${dbPath}" dosnt exist anymore`);
317
- }
318
- else {
319
- (0, utils_1.assertion)(res.isDirectory(), new Error('Defined dbPath is not a directory'));
320
- yield (0, utils_1.removeDir)(dbPath);
321
- }
330
+ else {
331
+ (0, utils_1.assertion)(res.isDirectory(), new Error('Defined dbPath is not a directory'));
332
+ await (0, utils_1.removeDir)(dbPath);
322
333
  }
323
- this.stateChange(MongoMemoryServerStates.new); // reset "state" to new, because the dbPath got removed
324
- this._instanceInfo = undefined;
325
- });
334
+ }
335
+ this.stateChange(MongoMemoryServerStates.new); // reset "state" to new, because the dbPath got removed
336
+ this._instanceInfo = undefined;
326
337
  }
327
338
  /**
328
339
  * Get Information about the currently running instance, if it is not running it returns "undefined"
@@ -340,45 +351,41 @@ class MongoMemoryServer extends events_1.EventEmitter {
340
351
  * Ensure that the instance is running
341
352
  * -> throws if instance cannot be started
342
353
  */
343
- ensureInstance() {
344
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
345
- this.debug('ensureInstance: Called .ensureInstance() method');
346
- switch (this._state) {
347
- case MongoMemoryServerStates.running:
348
- if (this._instanceInfo) {
349
- return this._instanceInfo;
354
+ async ensureInstance() {
355
+ this.debug('ensureInstance: Called .ensureInstance() method');
356
+ switch (this._state) {
357
+ case MongoMemoryServerStates.running:
358
+ if (this._instanceInfo) {
359
+ return this._instanceInfo;
360
+ }
361
+ throw new errors_1.InstanceInfoError('MongoMemoryServer.ensureInstance (state: running)');
362
+ case MongoMemoryServerStates.new:
363
+ case MongoMemoryServerStates.stopped:
364
+ break;
365
+ case MongoMemoryServerStates.starting:
366
+ return new Promise((res, rej) => this.once(MongoMemoryServerEvents.stateChange, (state) => {
367
+ if (state != MongoMemoryServerStates.running) {
368
+ rej(new Error(`"ensureInstance" waited for "running" but got a different state: "${state}"`));
369
+ return;
350
370
  }
351
- throw new errors_1.EnsureInstanceError(true);
352
- case MongoMemoryServerStates.new:
353
- case MongoMemoryServerStates.stopped:
354
- break;
355
- case MongoMemoryServerStates.starting:
356
- return new Promise((res, rej) => this.once(MongoMemoryServerEvents.stateChange, (state) => {
357
- if (state != MongoMemoryServerStates.running) {
358
- rej(new Error(`"ensureInstance" waited for "running" but got a different state: "${state}"`));
359
- return;
360
- }
361
- // this assertion is mainly for types (typescript otherwise would complain that "_instanceInfo" might be "undefined")
362
- (0, utils_1.assertion)(!(0, utils_1.isNullOrUndefined)(this._instanceInfo), new Error('InstanceInfo is undefined!'));
363
- res(this._instanceInfo);
364
- }));
365
- default:
366
- throw new errors_1.StateError([
367
- MongoMemoryServerStates.running,
368
- MongoMemoryServerStates.new,
369
- MongoMemoryServerStates.stopped,
370
- MongoMemoryServerStates.starting,
371
- ], this.state);
372
- }
373
- this.debug('ensureInstance: no running instance, calling "start()" command');
374
- yield this.start();
375
- this.debug('ensureInstance: "start()" command was succesfully resolved');
376
- // check again for 1. Typescript-type reasons and 2. if .start failed to throw an error
377
- if (!this._instanceInfo) {
378
- throw new errors_1.EnsureInstanceError(false);
379
- }
380
- return this._instanceInfo;
381
- });
371
+ // this assertion is mainly for types (typescript otherwise would complain that "_instanceInfo" might be "undefined")
372
+ (0, utils_1.assertion)(!(0, utils_1.isNullOrUndefined)(this._instanceInfo), new Error('InstanceInfo is undefined!'));
373
+ res(this._instanceInfo);
374
+ }));
375
+ default:
376
+ throw new errors_1.StateError([
377
+ MongoMemoryServerStates.running,
378
+ MongoMemoryServerStates.new,
379
+ MongoMemoryServerStates.stopped,
380
+ MongoMemoryServerStates.starting,
381
+ ], this.state);
382
+ }
383
+ this.debug('ensureInstance: no running instance, calling "start()" command');
384
+ await this.start();
385
+ this.debug('ensureInstance: "start()" command was succesfully resolved');
386
+ // check again for 1. Typescript-type reasons and 2. if .start failed to throw an error
387
+ (0, utils_1.assertion)(!!this._instanceInfo, new errors_1.InstanceInfoError('MongoMemoryServer.ensureInstance (after starting)'));
388
+ return this._instanceInfo;
382
389
  }
383
390
  /**
384
391
  * Generate the Connection string used by mongodb
@@ -407,71 +414,72 @@ class MongoMemoryServer extends events_1.EventEmitter {
407
414
  * @param data Used to get "ip" and "port"
408
415
  * @internal
409
416
  */
410
- createAuth(data) {
411
- var _a, _b, _c, _d;
412
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
413
- (0, utils_1.assertion)(!(0, utils_1.isNullOrUndefined)(this.auth), new Error('"createAuth" got called, but "this.auth" is undefined!'));
414
- assertionInstanceInfo(this._instanceInfo);
415
- this.debug('createAuth: options:', this.auth);
416
- let con = yield mongodb_1.MongoClient.connect((0, utils_1.uriTemplate)(data.ip, data.port, 'admin'));
417
- try {
418
- let db = con.db('admin'); // just to ensure it is actually the "admin" database AND to have the "Db" data
419
- // Create the root user
420
- this.debug(`createAuth: Creating Root user, name: "${this.auth.customRootName}"`);
421
- yield db.command({
422
- createUser: this.auth.customRootName,
423
- pwd: this.auth.customRootPwd,
424
- mechanisms: ['SCRAM-SHA-256'],
425
- customData: {
426
- createdBy: 'mongodb-memory-server',
427
- as: 'ROOTUSER',
428
- },
429
- roles: ['root'],
430
- // "writeConcern" is needced, otherwise replset servers might fail with "auth failed: such user does not exist"
431
- writeConcern: {
432
- w: 'majority',
433
- },
417
+ async createAuth(data) {
418
+ (0, utils_1.assertion)(!(0, utils_1.isNullOrUndefined)(this.auth), new Error('"createAuth" got called, but "this.auth" is undefined!'));
419
+ assertionInstanceInfo(this._instanceInfo);
420
+ this.debug('createAuth: options:', this.auth);
421
+ let con = await mongodb_1.MongoClient.connect((0, utils_1.uriTemplate)(data.ip, data.port, 'admin'));
422
+ try {
423
+ let db = con.db('admin'); // just to ensure it is actually the "admin" database AND to have the "Db" data
424
+ // Create the root user
425
+ this.debug(`createAuth: Creating Root user, name: "${this.auth.customRootName}"`);
426
+ await db.command({
427
+ createUser: this.auth.customRootName,
428
+ pwd: this.auth.customRootPwd,
429
+ mechanisms: ['SCRAM-SHA-256'],
430
+ customData: {
431
+ createdBy: 'mongodb-memory-server',
432
+ as: 'ROOTUSER',
433
+ },
434
+ roles: ['root'],
435
+ // "writeConcern" is needced, otherwise replset servers might fail with "auth failed: such user does not exist"
436
+ writeConcern: {
437
+ w: 'majority',
438
+ },
439
+ });
440
+ if (this.auth.extraUsers.length > 0) {
441
+ this.debug(`createAuth: Creating "${this.auth.extraUsers.length}" Custom Users`);
442
+ this.auth.extraUsers.sort((a, b) => {
443
+ if (a.database === 'admin') {
444
+ return -1; // try to make all "admin" at the start of the array
445
+ }
446
+ return a.database === b.database ? 0 : 1; // "0" to sort all databases that are the same after each other, and "1" to for pushing it back
434
447
  });
435
- if (this.auth.extraUsers.length > 0) {
436
- this.debug(`createAuth: Creating "${this.auth.extraUsers.length}" Custom Users`);
437
- this.auth.extraUsers.sort((a, b) => {
438
- if (a.database === 'admin') {
439
- return -1; // try to make all "admin" at the start of the array
440
- }
441
- return a.database === b.database ? 0 : 1; // "0" to sort all databases that are the same after each other, and "1" to for pushing it back
442
- });
443
- // reconnecting the database because the root user now exists and the "localhost exception" only allows the first user
444
- yield con.close();
445
- con = yield mongodb_1.MongoClient.connect(this.getUri('admin'), (_a = this._instanceInfo.instance.extraConnectionOptions) !== null && _a !== void 0 ? _a : {});
446
- db = con.db('admin');
447
- for (const user of this.auth.extraUsers) {
448
- user.database = (0, utils_1.isNullOrUndefined)(user.database) ? 'admin' : user.database;
449
- // just to have not to call "con.db" everytime in the loop if its the same
450
- if (user.database !== db.databaseName) {
451
- db = con.db(user.database);
452
- }
453
- this.debug('createAuth: Creating User: ', user);
454
- yield db.command({
455
- createUser: user.createUser,
456
- pwd: user.pwd,
457
- customData: Object.assign(Object.assign({}, user.customData), { createdBy: 'mongodb-memory-server', as: 'EXTRAUSER' }),
458
- roles: user.roles,
459
- authenticationRestrictions: (_b = user.authenticationRestrictions) !== null && _b !== void 0 ? _b : [],
460
- mechanisms: (_c = user.mechanisms) !== null && _c !== void 0 ? _c : ['SCRAM-SHA-256'],
461
- digestPassword: (_d = user.digestPassword) !== null && _d !== void 0 ? _d : true,
462
- // "writeConcern" is needced, otherwise replset servers might fail with "auth failed: such user does not exist"
463
- writeConcern: {
464
- w: 'majority',
465
- },
466
- });
448
+ // reconnecting the database because the root user now exists and the "localhost exception" only allows the first user
449
+ await con.close();
450
+ con = await mongodb_1.MongoClient.connect(this.getUri('admin'), this._instanceInfo.instance.extraConnectionOptions ?? {});
451
+ db = con.db('admin');
452
+ for (const user of this.auth.extraUsers) {
453
+ user.database = (0, utils_1.isNullOrUndefined)(user.database) ? 'admin' : user.database;
454
+ // just to have not to call "con.db" everytime in the loop if its the same
455
+ if (user.database !== db.databaseName) {
456
+ db = con.db(user.database);
467
457
  }
458
+ this.debug('createAuth: Creating User: ', user);
459
+ await db.command({
460
+ createUser: user.createUser,
461
+ pwd: user.pwd,
462
+ customData: {
463
+ ...user.customData,
464
+ createdBy: 'mongodb-memory-server',
465
+ as: 'EXTRAUSER',
466
+ },
467
+ roles: user.roles,
468
+ authenticationRestrictions: user.authenticationRestrictions ?? [],
469
+ mechanisms: user.mechanisms ?? ['SCRAM-SHA-256'],
470
+ digestPassword: user.digestPassword ?? true,
471
+ // "writeConcern" is needced, otherwise replset servers might fail with "auth failed: such user does not exist"
472
+ writeConcern: {
473
+ w: 'majority',
474
+ },
475
+ });
468
476
  }
469
477
  }
470
- finally {
471
- // close connection in any case (even if throwing a error or being successfull)
472
- yield con.close();
473
- }
474
- });
478
+ }
479
+ finally {
480
+ // close connection in any case (even if throwing a error or being successfull)
481
+ await con.close();
482
+ }
475
483
  }
476
484
  /**
477
485
  * Helper function to determine if the "auth" object is set and not to be disabled
@@ -482,9 +490,9 @@ class MongoMemoryServer extends events_1.EventEmitter {
482
490
  if ((0, utils_1.isNullOrUndefined)(this.auth)) {
483
491
  return false;
484
492
  }
485
- return typeof this.auth.disable === 'boolean' // if "this._replSetOpts.auth.disable" is defined, use that
486
- ? !this.auth.disable // invert the disable boolean, because "auth" should only be disabled if "disabled = true"
487
- : true; // if "this._replSetOpts.auth.disable" is not defined, default to true because "this._replSetOpts.auth" is defined
493
+ return typeof this.auth.enable === 'boolean' // if "this._replSetOpts.auth.enable" is defined, use that
494
+ ? this.auth.enable
495
+ : false; // if "this._replSetOpts.auth.enable" is not defined, default to false
488
496
  }
489
497
  }
490
498
  exports.MongoMemoryServer = MongoMemoryServer;