// Complete downloadable launcher for a separate local learning folder. import fs from'node:fs';import path from'node:path';import crypto from'node:crypto';import{execFile}from'node:child_process';import{promisify}from'node:util';import{MongoMemoryReplSet}from'mongodb-memory-server-core'; const run=promisify(execFile),file=process.argv[2]&&path.resolve(process.argv[2]); if(!file||!fs.statSync(file).isFile()||!/(?:\.mongosh\.js|\.mjs)$/.test(file))throw Error('Usage: node run-lab.mjs path-to-your-trusted-downloaded-lesson'); const root=path.resolve('.bhylu-mongodb-lab'),directory=path.join(root,'runs',crypto.randomUUID());fs.mkdirSync(path.join(directory,'data'),{recursive:true}); const previousTemp=process.env.TEMP,previousTmp=process.env.TMP;process.env.TEMP=directory;process.env.TMP=directory;const password=crypto.randomBytes(24).toString('hex');let server; try{ server=await MongoMemoryReplSet.create({binary:{version:'8.0.12',downloadDir:path.join(root,'binary-cache'),checkMD5:true,systemBinary:process.env.BHYLU_MONGODB_BINARY||undefined},instanceOpts:[{dbPath:path.join(directory,'data')}],replSet:{count:1,name:'bhyluMongoLab',ip:'127.0.0.1',storageEngine:'wiredTiger',spawn:{windowsHide:true},auth:{enable:true,customRootName:'bhylu_lab',customRootPwd:password}}}); const uri=new URL(server.getUri('admin'));uri.username='bhylu_lab';uri.password=password;uri.searchParams.set('authSource','admin');if(uri.port==='27017')throw Error('Refusing normal database port'); const profile=path.join(directory,'child-profile');fs.mkdirSync(profile);const env={...process.env,BHYLU_MONGO_LAB:'YES',BHYLU_MONGO_URI:uri.href,MONGOSH_DISABLE_TELEMETRY:'1',APPDATA:profile,LOCALAPPDATA:profile}; const shell=file.endsWith('.mongosh.js'),result=await run(shell?(process.env.BHYLU_MONGOSH||'mongosh'):process.execPath,shell?['--nodb','--norc','--quiet','--file',file]:[file],{env,cwd:process.cwd(),windowsHide:true,timeout:120000,maxBuffer:8*1024*1024});process.stdout.write(result.stdout);process.stderr.write(result.stderr); }catch(error){console.error((error.stderr||error.message));process.exitCode=1;} finally{ if(server){const stopped=await server.stop({doCleanup:false,force:false});if(!stopped){console.error('Private lab server did not stop');process.exitCode=1;}} if(previousTemp===undefined)delete process.env.TEMP;else process.env.TEMP=previousTemp;if(previousTmp===undefined)delete process.env.TMP;else process.env.TMP=previousTmp; }