mongodb-memory-server-core 8.14.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 (52) 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 +3 -12
  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 +7 -5
  20. package/lib/util/MongoBinaryDownloadUrl.d.ts.map +1 -1
  21. package/lib/util/MongoBinaryDownloadUrl.js +90 -91
  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 +2 -1
  45. package/lib/util/resolveConfig.d.ts.map +1 -1
  46. package/lib/util/resolveConfig.js +10 -8
  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 +8 -12
@@ -2,19 +2,18 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MongoBinaryDownload = void 0;
4
4
  const tslib_1 = require("tslib");
5
- const os_1 = (0, tslib_1.__importDefault)(require("os"));
5
+ const os_1 = tslib_1.__importDefault(require("os"));
6
6
  const url_1 = require("url");
7
- const path_1 = (0, tslib_1.__importDefault)(require("path"));
7
+ const path_1 = tslib_1.__importDefault(require("path"));
8
8
  const fs_1 = require("fs");
9
- const md5_file_1 = (0, tslib_1.__importDefault)(require("md5-file"));
10
9
  const follow_redirects_1 = require("follow-redirects");
11
10
  const zlib_1 = require("zlib");
12
- const tar_stream_1 = (0, tslib_1.__importDefault)(require("tar-stream"));
13
- const yauzl_1 = (0, tslib_1.__importDefault)(require("yauzl"));
14
- const MongoBinaryDownloadUrl_1 = (0, tslib_1.__importDefault)(require("./MongoBinaryDownloadUrl"));
11
+ const tar_stream_1 = tslib_1.__importDefault(require("tar-stream"));
12
+ const yauzl_1 = tslib_1.__importDefault(require("yauzl"));
13
+ const MongoBinaryDownloadUrl_1 = tslib_1.__importDefault(require("./MongoBinaryDownloadUrl"));
15
14
  const https_proxy_agent_1 = require("https-proxy-agent");
16
- const resolveConfig_1 = (0, tslib_1.__importStar)(require("./resolveConfig"));
17
- const debug_1 = (0, tslib_1.__importDefault)(require("debug"));
15
+ const resolveConfig_1 = tslib_1.__importStar(require("./resolveConfig"));
16
+ const debug_1 = tslib_1.__importDefault(require("debug"));
18
17
  const utils_1 = require("./utils");
19
18
  const DryMongoBinary_1 = require("./DryMongoBinary");
20
19
  const readline_1 = require("readline");
@@ -24,21 +23,19 @@ const log = (0, debug_1.default)('MongoMS:MongoBinaryDownload');
24
23
  * Download and extract the "mongod" binary
25
24
  */
26
25
  class MongoBinaryDownload {
27
- // end get/set backwards compat section
28
26
  constructor(opts) {
29
- var _a, _b, _c, _d, _e, _f;
30
27
  (0, utils_1.assertion)(typeof opts.downloadDir === 'string', new Error('An DownloadDir must be specified!'));
31
- const version = (_a = opts.version) !== null && _a !== void 0 ? _a : (0, resolveConfig_1.default)(resolveConfig_1.ResolveConfigVariables.VERSION);
28
+ const version = opts.version ?? (0, resolveConfig_1.default)(resolveConfig_1.ResolveConfigVariables.VERSION);
32
29
  (0, utils_1.assertion)(typeof version === 'string', new Error('An MongoDB Binary version must be specified!'));
33
30
  // DryMongoBinary.generateOptions cannot be used here, because its async
34
31
  this.binaryOpts = {
35
- platform: (_b = opts.platform) !== null && _b !== void 0 ? _b : os_1.default.platform(),
36
- arch: (_c = opts.arch) !== null && _c !== void 0 ? _c : os_1.default.arch(),
32
+ platform: opts.platform ?? os_1.default.platform(),
33
+ arch: opts.arch ?? os_1.default.arch(),
37
34
  version: version,
38
35
  downloadDir: opts.downloadDir,
39
- checkMD5: (_d = opts.checkMD5) !== null && _d !== void 0 ? _d : (0, resolveConfig_1.envToBool)((0, resolveConfig_1.default)(resolveConfig_1.ResolveConfigVariables.MD5_CHECK)),
40
- systemBinary: (_e = opts.systemBinary) !== null && _e !== void 0 ? _e : '',
41
- os: (_f = opts.os) !== null && _f !== void 0 ? _f : { os: 'unknown' },
36
+ checkMD5: opts.checkMD5 ?? (0, resolveConfig_1.envToBool)((0, resolveConfig_1.default)(resolveConfig_1.ResolveConfigVariables.MD5_CHECK)),
37
+ systemBinary: opts.systemBinary ?? '',
38
+ os: opts.os ?? { os: 'unknown' },
42
39
  };
43
40
  this.dlProgress = {
44
41
  current: 0,
@@ -47,91 +44,53 @@ class MongoBinaryDownload {
47
44
  lastPrintedAt: 0,
48
45
  };
49
46
  }
50
- // TODO: for an major version, remove the compat get/set
51
- // the following get/set are to not break existing stuff
52
- get checkMD5() {
53
- return this.binaryOpts.checkMD5;
54
- }
55
- set checkMD5(val) {
56
- this.binaryOpts.checkMD5 = val;
57
- }
58
- get downloadDir() {
59
- return this.binaryOpts.downloadDir;
60
- }
61
- set downloadDir(val) {
62
- this.binaryOpts.downloadDir = val;
63
- }
64
- get arch() {
65
- return this.binaryOpts.arch;
66
- }
67
- set arch(val) {
68
- this.binaryOpts.arch = val;
69
- }
70
- get version() {
71
- return this.binaryOpts.version;
72
- }
73
- set version(val) {
74
- this.binaryOpts.version = val;
75
- }
76
- get platform() {
77
- return this.binaryOpts.platform;
78
- }
79
- set platform(val) {
80
- this.binaryOpts.platform = val;
81
- }
82
47
  /**
83
48
  * Get the full path with filename
84
49
  * @returns Absoulte Path with FileName
85
50
  */
86
- getPath() {
87
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
88
- const opts = yield DryMongoBinary_1.DryMongoBinary.generateOptions(this.binaryOpts);
89
- return DryMongoBinary_1.DryMongoBinary.combineBinaryName(this.downloadDir, yield DryMongoBinary_1.DryMongoBinary.getBinaryName(opts));
90
- });
51
+ async getPath() {
52
+ const opts = await DryMongoBinary_1.DryMongoBinary.generateOptions(this.binaryOpts);
53
+ return DryMongoBinary_1.DryMongoBinary.combineBinaryName(this.binaryOpts.downloadDir, await DryMongoBinary_1.DryMongoBinary.getBinaryName(opts));
91
54
  }
92
55
  /**
93
56
  * Get the path of the already downloaded "mongod" file
94
57
  * otherwise download it and then return the path
95
58
  */
96
- getMongodPath() {
97
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
98
- log('getMongodPath');
99
- const mongodPath = yield this.getPath();
100
- if (yield (0, utils_1.pathExists)(mongodPath)) {
101
- log(`getMongodPath: mongod path "${mongodPath}" already exists, using this`);
102
- return mongodPath;
103
- }
104
- const mongoDBArchive = yield this.startDownload();
105
- yield this.extract(mongoDBArchive);
106
- yield fs_1.promises.unlink(mongoDBArchive);
107
- if (yield (0, utils_1.pathExists)(mongodPath)) {
108
- return mongodPath;
109
- }
110
- throw new Error(`Cannot find downloaded mongod binary by path "${mongodPath}"`);
111
- });
59
+ async getMongodPath() {
60
+ log('getMongodPath');
61
+ const mongodPath = await this.getPath();
62
+ if (await (0, utils_1.pathExists)(mongodPath)) {
63
+ log(`getMongodPath: mongod path "${mongodPath}" already exists, using this`);
64
+ return mongodPath;
65
+ }
66
+ const mongoDBArchive = await this.startDownload();
67
+ await this.extract(mongoDBArchive);
68
+ await fs_1.promises.unlink(mongoDBArchive);
69
+ if (await (0, utils_1.pathExists)(mongodPath)) {
70
+ return mongodPath;
71
+ }
72
+ throw new Error(`Cannot find downloaded mongod binary by path "${mongodPath}"`);
112
73
  }
113
74
  /**
114
75
  * Download the MongoDB Archive and check it against an MD5
115
76
  * @returns The MongoDB Archive location
116
77
  */
117
- startDownload() {
118
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
119
- log('startDownload');
120
- const mbdUrl = new MongoBinaryDownloadUrl_1.default(this.binaryOpts);
121
- yield (0, utils_1.mkdir)(this.downloadDir);
122
- try {
123
- yield fs_1.promises.access(this.downloadDir, fs_1.constants.X_OK | fs_1.constants.W_OK); // check that this process has permissions to create files & modify file contents & read file contents
124
- }
125
- catch (err) {
126
- console.error(`Download Directory at "${this.downloadDir}" does not have sufficient permissions to be used by this process\n` +
127
- 'Needed Permissions: Write & Execute (-wx)\n');
128
- throw err;
129
- }
130
- const downloadUrl = yield mbdUrl.getDownloadUrl();
131
- const mongoDBArchive = yield this.download(downloadUrl);
132
- yield this.makeMD5check(`${downloadUrl}.md5`, mongoDBArchive);
133
- return mongoDBArchive;
134
- });
78
+ async startDownload() {
79
+ log('startDownload');
80
+ const mbdUrl = new MongoBinaryDownloadUrl_1.default(this.binaryOpts);
81
+ await (0, utils_1.mkdir)(this.binaryOpts.downloadDir);
82
+ try {
83
+ await fs_1.promises.access(this.binaryOpts.downloadDir, fs_1.constants.X_OK | fs_1.constants.W_OK); // check that this process has permissions to create files & modify file contents & read file contents
84
+ }
85
+ catch (err) {
86
+ console.error(`Download Directory at "${this.binaryOpts.downloadDir}" does not have sufficient permissions to be used by this process\n` +
87
+ 'Needed Permissions: Write & Execute (-wx)\n');
88
+ throw err;
89
+ }
90
+ const downloadUrl = await mbdUrl.getDownloadUrl();
91
+ const mongoDBArchive = await this.download(downloadUrl);
92
+ await this.makeMD5check(`${downloadUrl}.md5`, mongoDBArchive);
93
+ return mongoDBArchive;
135
94
  }
136
95
  /**
137
96
  * Download MD5 file and check it against the MongoDB Archive
@@ -142,94 +101,87 @@ class MongoBinaryDownload {
142
101
  * @returns {true} if the md5 check was successful
143
102
  * @throws if the md5 check failed
144
103
  */
145
- makeMD5check(urlForReferenceMD5, mongoDBArchive) {
146
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
147
- log('makeMD5check: Checking MD5 of downloaded binary...');
148
- if (!this.checkMD5) {
149
- log('makeMD5check: checkMD5 is disabled');
150
- return undefined;
151
- }
152
- const archiveMD5Path = yield this.download(urlForReferenceMD5);
153
- const signatureContent = (yield fs_1.promises.readFile(archiveMD5Path)).toString('utf-8');
154
- const regexMatch = signatureContent.match(/^\s*([\w\d]+)\s*/i);
155
- const md5SigRemote = regexMatch ? regexMatch[1] : null;
156
- const md5SigLocal = md5_file_1.default.sync(mongoDBArchive);
157
- log(`makeMD5check: Local MD5: ${md5SigLocal}, Remote MD5: ${md5SigRemote}`);
158
- if (md5SigRemote !== md5SigLocal) {
159
- throw new errors_1.Md5CheckFailedError(md5SigLocal, md5SigRemote || 'unknown');
160
- }
161
- yield fs_1.promises.unlink(archiveMD5Path);
162
- return true;
163
- });
104
+ async makeMD5check(urlForReferenceMD5, mongoDBArchive) {
105
+ log('makeMD5check: Checking MD5 of downloaded binary...');
106
+ if (!this.binaryOpts.checkMD5) {
107
+ log('makeMD5check: checkMD5 is disabled');
108
+ return undefined;
109
+ }
110
+ const archiveMD5Path = await this.download(urlForReferenceMD5);
111
+ const signatureContent = (await fs_1.promises.readFile(archiveMD5Path)).toString('utf-8');
112
+ const regexMatch = signatureContent.match(/^\s*([\w\d]+)\s*/i);
113
+ const md5SigRemote = regexMatch ? regexMatch[1] : null;
114
+ const md5SigLocal = await (0, utils_1.md5FromFile)(mongoDBArchive);
115
+ log(`makeMD5check: Local MD5: ${md5SigLocal}, Remote MD5: ${md5SigRemote}`);
116
+ if (md5SigRemote !== md5SigLocal) {
117
+ throw new errors_1.Md5CheckFailedError(md5SigLocal, md5SigRemote || 'unknown');
118
+ }
119
+ await fs_1.promises.unlink(archiveMD5Path);
120
+ return true;
164
121
  }
165
122
  /**
166
123
  * Download file from downloadUrl
167
124
  * @param downloadUrl URL to download a File
168
125
  * @returns The Path to the downloaded archive file
169
126
  */
170
- download(downloadUrl) {
171
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
172
- log('download');
173
- const proxy = process.env['yarn_https-proxy'] ||
174
- process.env.yarn_proxy ||
175
- process.env['npm_config_https-proxy'] ||
176
- process.env.npm_config_proxy ||
177
- process.env.https_proxy ||
178
- process.env.http_proxy ||
179
- process.env.HTTPS_PROXY ||
180
- process.env.HTTP_PROXY;
181
- const strictSsl = process.env.npm_config_strict_ssl === 'true';
182
- const urlObject = new url_1.URL(downloadUrl);
183
- urlObject.port = urlObject.port || '443';
184
- const requestOptions = {
185
- method: 'GET',
186
- rejectUnauthorized: strictSsl,
187
- protocol: (0, resolveConfig_1.envToBool)((0, resolveConfig_1.default)(resolveConfig_1.ResolveConfigVariables.USE_HTTP)) ? 'http:' : 'https:',
188
- agent: proxy ? new https_proxy_agent_1.HttpsProxyAgent(proxy) : undefined,
189
- };
190
- const filename = urlObject.pathname.split('/').pop();
191
- if (!filename) {
192
- throw new Error(`MongoBinaryDownload: missing filename for url "${downloadUrl}"`);
193
- }
194
- const downloadLocation = path_1.default.resolve(this.downloadDir, filename);
195
- const tempDownloadLocation = path_1.default.resolve(this.downloadDir, `${filename}.downloading`);
196
- log(`download: Downloading${proxy ? ` via proxy "${proxy}"` : ''}: "${downloadUrl}"`);
197
- if (yield (0, utils_1.pathExists)(downloadLocation)) {
198
- log('download: Already downloaded archive found, skipping download');
199
- return downloadLocation;
200
- }
201
- this.assignDownloadingURL(urlObject);
202
- const downloadedFile = yield this.httpDownload(urlObject, requestOptions, downloadLocation, tempDownloadLocation);
203
- return downloadedFile;
204
- });
127
+ async download(downloadUrl) {
128
+ log('download');
129
+ const proxy = process.env['yarn_https-proxy'] ||
130
+ process.env.yarn_proxy ||
131
+ process.env['npm_config_https-proxy'] ||
132
+ process.env.npm_config_proxy ||
133
+ process.env.https_proxy ||
134
+ process.env.http_proxy ||
135
+ process.env.HTTPS_PROXY ||
136
+ process.env.HTTP_PROXY;
137
+ const strictSsl = process.env.npm_config_strict_ssl === 'true';
138
+ const urlObject = new url_1.URL(downloadUrl);
139
+ urlObject.port = urlObject.port || '443';
140
+ const requestOptions = {
141
+ method: 'GET',
142
+ rejectUnauthorized: strictSsl,
143
+ protocol: (0, resolveConfig_1.envToBool)((0, resolveConfig_1.default)(resolveConfig_1.ResolveConfigVariables.USE_HTTP)) ? 'http:' : 'https:',
144
+ agent: proxy ? new https_proxy_agent_1.HttpsProxyAgent(proxy) : undefined,
145
+ };
146
+ const filename = urlObject.pathname.split('/').pop();
147
+ if (!filename) {
148
+ throw new Error(`MongoBinaryDownload: missing filename for url "${downloadUrl}"`);
149
+ }
150
+ const downloadLocation = path_1.default.resolve(this.binaryOpts.downloadDir, filename);
151
+ const tempDownloadLocation = path_1.default.resolve(this.binaryOpts.downloadDir, `${filename}.downloading`);
152
+ log(`download: Downloading${proxy ? ` via proxy "${proxy}"` : ''}: "${downloadUrl}"`);
153
+ if (await (0, utils_1.pathExists)(downloadLocation)) {
154
+ log('download: Already downloaded archive found, skipping download');
155
+ return downloadLocation;
156
+ }
157
+ this.assignDownloadingURL(urlObject);
158
+ const downloadedFile = await this.httpDownload(urlObject, requestOptions, downloadLocation, tempDownloadLocation);
159
+ return downloadedFile;
205
160
  }
206
161
  /**
207
162
  * Extract given Archive
208
163
  * @param mongoDBArchive Archive location
209
164
  * @returns extracted directory location
210
165
  */
211
- extract(mongoDBArchive) {
212
- var _a, _b;
213
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
214
- log('extract');
215
- const mongodbFullPath = yield this.getPath();
216
- log(`extract: archive: "${mongoDBArchive}" final: "${mongodbFullPath}"`);
217
- yield (0, utils_1.mkdir)(path_1.default.dirname(mongodbFullPath));
218
- const filter = (file) => /(?:bin\/(?:mongod(?:\.exe)?))$/i.test(file);
219
- if (/(.tar.gz|.tgz)$/.test(mongoDBArchive)) {
220
- yield this.extractTarGz(mongoDBArchive, mongodbFullPath, filter);
221
- }
222
- else if (/.zip$/.test(mongoDBArchive)) {
223
- yield this.extractZip(mongoDBArchive, mongodbFullPath, filter);
224
- }
225
- else {
226
- throw new Error(`MongoBinaryDownload: unsupported archive "${mongoDBArchive}" (downloaded from "${(_a = this._downloadingUrl) !== null && _a !== void 0 ? _a : 'unknown'}"). Broken archive from MongoDB Provider?`);
227
- }
228
- if (!(yield (0, utils_1.pathExists)(mongodbFullPath))) {
229
- throw new Error(`MongoBinaryDownload: missing mongod binary in "${mongoDBArchive}" (downloaded from "${(_b = this._downloadingUrl) !== null && _b !== void 0 ? _b : 'unknown'}"). Broken archive from MongoDB Provider?`);
230
- }
231
- return mongodbFullPath;
232
- });
166
+ async extract(mongoDBArchive) {
167
+ log('extract');
168
+ const mongodbFullPath = await this.getPath();
169
+ log(`extract: archive: "${mongoDBArchive}" final: "${mongodbFullPath}"`);
170
+ await (0, utils_1.mkdir)(path_1.default.dirname(mongodbFullPath));
171
+ const filter = (file) => /(?:bin\/(?:mongod(?:\.exe)?))$/i.test(file);
172
+ if (/(.tar.gz|.tgz)$/.test(mongoDBArchive)) {
173
+ await this.extractTarGz(mongoDBArchive, mongodbFullPath, filter);
174
+ }
175
+ else if (/.zip$/.test(mongoDBArchive)) {
176
+ await this.extractZip(mongoDBArchive, mongodbFullPath, filter);
177
+ }
178
+ else {
179
+ throw new Error(`MongoBinaryDownload: unsupported archive "${mongoDBArchive}" (downloaded from "${this._downloadingUrl ?? 'unknown'}"). Broken archive from MongoDB Provider?`);
180
+ }
181
+ if (!(await (0, utils_1.pathExists)(mongodbFullPath))) {
182
+ throw new Error(`MongoBinaryDownload: missing mongod binary in "${mongoDBArchive}" (downloaded from "${this._downloadingUrl ?? 'unknown'}"). Broken archive from MongoDB Provider?`);
183
+ }
184
+ return mongodbFullPath;
233
185
  }
234
186
  /**
235
187
  * Extract a .tar.gz archive
@@ -237,34 +189,32 @@ class MongoBinaryDownload {
237
189
  * @param extractPath Directory to extract to
238
190
  * @param filter Method to determine which files to extract
239
191
  */
240
- extractTarGz(mongoDBArchive, extractPath, filter) {
241
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
242
- log('extractTarGz');
243
- const extract = tar_stream_1.default.extract();
244
- extract.on('entry', (header, stream, next) => {
245
- if (filter(header.name)) {
246
- stream.pipe((0, fs_1.createWriteStream)(extractPath, {
247
- mode: 0o775,
248
- }));
249
- }
250
- stream.on('end', () => next());
251
- stream.resume();
252
- });
253
- return new Promise((res, rej) => {
254
- (0, fs_1.createReadStream)(mongoDBArchive)
255
- .on('error', (err) => {
256
- rej(new errors_1.GenericMMSError('Unable to open tarball ' + mongoDBArchive + ': ' + err));
257
- })
258
- .pipe((0, zlib_1.createUnzip)())
259
- .on('error', (err) => {
260
- rej(new errors_1.GenericMMSError('Error during unzip for ' + mongoDBArchive + ': ' + err));
261
- })
262
- .pipe(extract)
263
- .on('error', (err) => {
264
- rej(new errors_1.GenericMMSError('Error during untar for ' + mongoDBArchive + ': ' + err));
265
- })
266
- .on('finish', res);
267
- });
192
+ async extractTarGz(mongoDBArchive, extractPath, filter) {
193
+ log('extractTarGz');
194
+ const extract = tar_stream_1.default.extract();
195
+ extract.on('entry', (header, stream, next) => {
196
+ if (filter(header.name)) {
197
+ stream.pipe((0, fs_1.createWriteStream)(extractPath, {
198
+ mode: 0o775,
199
+ }));
200
+ }
201
+ stream.on('end', () => next());
202
+ stream.resume();
203
+ });
204
+ return new Promise((res, rej) => {
205
+ (0, fs_1.createReadStream)(mongoDBArchive)
206
+ .on('error', (err) => {
207
+ rej(new errors_1.GenericMMSError('Unable to open tarball ' + mongoDBArchive + ': ' + err));
208
+ })
209
+ .pipe((0, zlib_1.createUnzip)())
210
+ .on('error', (err) => {
211
+ rej(new errors_1.GenericMMSError('Error during unzip for ' + mongoDBArchive + ': ' + err));
212
+ })
213
+ .pipe(extract)
214
+ .on('error', (err) => {
215
+ rej(new errors_1.GenericMMSError('Error during untar for ' + mongoDBArchive + ': ' + err));
216
+ })
217
+ .on('finish', res);
268
218
  });
269
219
  }
270
220
  /**
@@ -273,29 +223,27 @@ class MongoBinaryDownload {
273
223
  * @param extractPath Directory to extract to
274
224
  * @param filter Method to determine which files to extract
275
225
  */
276
- extractZip(mongoDBArchive, extractPath, filter) {
277
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
278
- log('extractZip');
279
- return new Promise((resolve, reject) => {
280
- yauzl_1.default.open(mongoDBArchive, { lazyEntries: true }, (err, zipfile) => {
281
- if (err || !zipfile) {
282
- return reject(err);
226
+ async extractZip(mongoDBArchive, extractPath, filter) {
227
+ log('extractZip');
228
+ return new Promise((resolve, reject) => {
229
+ yauzl_1.default.open(mongoDBArchive, { lazyEntries: true }, (err, zipfile) => {
230
+ if (err || !zipfile) {
231
+ return reject(err);
232
+ }
233
+ zipfile.readEntry();
234
+ zipfile.on('end', () => resolve());
235
+ zipfile.on('entry', (entry) => {
236
+ if (!filter(entry.fileName)) {
237
+ return zipfile.readEntry();
283
238
  }
284
- zipfile.readEntry();
285
- zipfile.on('end', () => resolve());
286
- zipfile.on('entry', (entry) => {
287
- if (!filter(entry.fileName)) {
288
- return zipfile.readEntry();
239
+ zipfile.openReadStream(entry, (err2, r) => {
240
+ if (err2 || !r) {
241
+ return reject(err2);
289
242
  }
290
- zipfile.openReadStream(entry, (err2, r) => {
291
- if (err2 || !r) {
292
- return reject(err2);
293
- }
294
- r.on('end', () => zipfile.readEntry());
295
- r.pipe((0, fs_1.createWriteStream)(extractPath, {
296
- mode: 0o775,
297
- }));
298
- });
243
+ r.on('end', () => zipfile.readEntry());
244
+ r.pipe((0, fs_1.createWriteStream)(extractPath, {
245
+ mode: 0o775,
246
+ }));
299
247
  });
300
248
  });
301
249
  });
@@ -307,59 +255,59 @@ class MongoBinaryDownload {
307
255
  * @param downloadLocation The location the File should be after the download
308
256
  * @param tempDownloadLocation The location the File should be while downloading
309
257
  */
310
- httpDownload(url, httpOptions, downloadLocation, tempDownloadLocation) {
311
- return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
312
- log('httpDownload');
313
- const downloadUrl = this.assignDownloadingURL(url);
314
- const maxRedirects = parseInt((0, resolveConfig_1.default)(resolveConfig_1.ResolveConfigVariables.MAX_REDIRECTS) || '');
315
- const useHttpsOptions = Object.assign({ maxRedirects: Number.isNaN(maxRedirects) ? 2 : maxRedirects }, httpOptions);
316
- return new Promise((resolve, reject) => {
317
- log(`httpDownload: trying to download "${downloadUrl}"`);
318
- follow_redirects_1.https
319
- .get(url, useHttpsOptions, (response) => {
320
- if (response.statusCode != 200) {
321
- if (response.statusCode === 403) {
322
- reject(new errors_1.DownloadError(downloadUrl, "Status Code is 403 (MongoDB's 404)\n" +
323
- "This means that the requested version-platform combination doesn't exist\n" +
324
- "Try to use different version 'new MongoMemoryServer({ binary: { version: 'X.Y.Z' } })'\n" +
325
- 'List of available versions can be found here: ' +
326
- 'https://www.mongodb.com/download-center/community/releases/archive'));
327
- return;
328
- }
329
- reject(new errors_1.DownloadError(downloadUrl, `Status Code isnt 200! (it is ${response.statusCode})`));
258
+ async httpDownload(url, httpOptions, downloadLocation, tempDownloadLocation) {
259
+ log('httpDownload');
260
+ const downloadUrl = this.assignDownloadingURL(url);
261
+ const maxRedirects = parseInt((0, resolveConfig_1.default)(resolveConfig_1.ResolveConfigVariables.MAX_REDIRECTS) || '');
262
+ const useHttpsOptions = {
263
+ maxRedirects: Number.isNaN(maxRedirects) ? 2 : maxRedirects,
264
+ ...httpOptions,
265
+ };
266
+ return new Promise((resolve, reject) => {
267
+ log(`httpDownload: trying to download "${downloadUrl}"`);
268
+ follow_redirects_1.https
269
+ .get(url, useHttpsOptions, (response) => {
270
+ if (response.statusCode != 200) {
271
+ if (response.statusCode === 403) {
272
+ reject(new errors_1.DownloadError(downloadUrl, "Status Code is 403 (MongoDB's 404)\n" +
273
+ "This means that the requested version-platform combination doesn't exist\n" +
274
+ "Try to use different version 'new MongoMemoryServer({ binary: { version: 'X.Y.Z' } })'\n" +
275
+ 'List of available versions can be found here: ' +
276
+ 'https://www.mongodb.com/download-center/community/releases/archive'));
330
277
  return;
331
278
  }
332
- if (typeof response.headers['content-length'] != 'string') {
333
- reject(new errors_1.DownloadError(downloadUrl, 'Response header "content-length" is empty!'));
279
+ reject(new errors_1.DownloadError(downloadUrl, `Status Code isnt 200! (it is ${response.statusCode})`));
280
+ return;
281
+ }
282
+ if (typeof response.headers['content-length'] != 'string') {
283
+ reject(new errors_1.DownloadError(downloadUrl, 'Response header "content-length" is empty!'));
284
+ return;
285
+ }
286
+ this.dlProgress.current = 0;
287
+ this.dlProgress.length = parseInt(response.headers['content-length'], 10);
288
+ this.dlProgress.totalMb = Math.round((this.dlProgress.length / 1048576) * 10) / 10;
289
+ const fileStream = (0, fs_1.createWriteStream)(tempDownloadLocation);
290
+ response.pipe(fileStream);
291
+ fileStream.on('finish', async () => {
292
+ if (this.dlProgress.current < this.dlProgress.length &&
293
+ !httpOptions.path?.endsWith('.md5')) {
294
+ reject(new errors_1.DownloadError(downloadUrl, `Too small (${this.dlProgress.current} bytes) mongod binary downloaded.`));
334
295
  return;
335
296
  }
336
- this.dlProgress.current = 0;
337
- this.dlProgress.length = parseInt(response.headers['content-length'], 10);
338
- this.dlProgress.totalMb = Math.round((this.dlProgress.length / 1048576) * 10) / 10;
339
- const fileStream = (0, fs_1.createWriteStream)(tempDownloadLocation);
340
- response.pipe(fileStream);
341
- fileStream.on('finish', () => (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
342
- var _a;
343
- if (this.dlProgress.current < this.dlProgress.length &&
344
- !((_a = httpOptions.path) === null || _a === void 0 ? void 0 : _a.endsWith('.md5'))) {
345
- reject(new errors_1.DownloadError(downloadUrl, `Too small (${this.dlProgress.current} bytes) mongod binary downloaded.`));
346
- return;
347
- }
348
- this.printDownloadProgress({ length: 0 }, true);
349
- fileStream.close();
350
- yield fs_1.promises.rename(tempDownloadLocation, downloadLocation);
351
- log(`httpDownload: moved "${tempDownloadLocation}" to "${downloadLocation}"`);
352
- resolve(downloadLocation);
353
- }));
354
- response.on('data', (chunk) => {
355
- this.printDownloadProgress(chunk);
356
- });
357
- })
358
- .on('error', (err) => {
359
- // log it without having debug enabled
360
- console.error(`Couldnt download "${downloadUrl}"!`, err.message);
361
- reject(new errors_1.DownloadError(downloadUrl, err.message));
297
+ this.printDownloadProgress({ length: 0 }, true);
298
+ fileStream.close();
299
+ await fs_1.promises.rename(tempDownloadLocation, downloadLocation);
300
+ log(`httpDownload: moved "${tempDownloadLocation}" to "${downloadLocation}"`);
301
+ resolve(downloadLocation);
302
+ });
303
+ response.on('data', (chunk) => {
304
+ this.printDownloadProgress(chunk);
362
305
  });
306
+ })
307
+ .on('error', (err) => {
308
+ // log it without having debug enabled
309
+ console.error(`Couldnt download "${downloadUrl}"!`, err.message);
310
+ reject(new errors_1.DownloadError(downloadUrl, err.message));
363
311
  });
364
312
  });
365
313
  }
@@ -376,8 +324,8 @@ class MongoBinaryDownload {
376
324
  this.dlProgress.lastPrintedAt = now;
377
325
  const percentComplete = Math.round(((100.0 * this.dlProgress.current) / this.dlProgress.length) * 10) / 10;
378
326
  const mbComplete = Math.round((this.dlProgress.current / 1048576) * 10) / 10;
379
- const crReturn = this.platform === 'win32' ? '\x1b[0G' : '\r';
380
- const message = `Downloading MongoDB "${this.version}": ${percentComplete}% (${mbComplete}mb / ${this.dlProgress.totalMb}mb)${crReturn}`;
327
+ const crReturn = this.binaryOpts.platform === 'win32' ? '\x1b[0G' : '\r';
328
+ const message = `Downloading MongoDB "${this.binaryOpts.version}": ${percentComplete}% (${mbComplete}mb / ${this.dlProgress.totalMb}mb)${crReturn}`;
381
329
  if (process.stdout.isTTY) {
382
330
  // if TTY overwrite last line over and over until finished and clear line to avoid residual characters
383
331
  (0, readline_1.clearLine)(process.stdout, 0); // this is because "process.stdout.clearLine" does not exist anymore