mongodb-memory-server-core 8.15.0 → 9.0.0-beta.1

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